From b71bacfcfdbb9ab5d87ceec4d974719bbd6a824b Mon Sep 17 00:00:00 2001 From: Your Name Date: Wed, 18 Sep 2024 00:04:45 +0800 Subject: [PATCH] gin --- api-param/main.go | 25 +++++++++ cookie/main.go | 33 ++++++++++++ cookie/practice.go | 37 ++++++++++++++ form-param/demo_login/main.go | 58 +++++++++++++++++++++ form-param/page/login.html | 35 +++++++++++++ go.mod | 33 ++++++++++++ go.sum | 77 ++++++++++++++++++++++++++++ helloworld/main.go | 32 ++++++++++++ html-xuanran/main.go | 21 ++++++++ json-form-uri-bind-json/form.html | 18 +++++++ json-form-uri-bind-json/main.go | 85 +++++++++++++++++++++++++++++++ middleware/main.go | 52 +++++++++++++++++++ middleware/practice.go | 36 +++++++++++++ multiple-response/main.go | 50 ++++++++++++++++++ redirect/main.go | 15 ++++++ routers-group/main.go | 32 ++++++++++++ session/main.go | 10 ++++ sync_async/main.go | 27 ++++++++++ templates/index.tmpl | 5 ++ url-param/main.go | 22 ++++++++ 20 files changed, 703 insertions(+) create mode 100644 api-param/main.go create mode 100644 cookie/main.go create mode 100644 cookie/practice.go create mode 100644 form-param/demo_login/main.go create mode 100644 form-param/page/login.html create mode 100644 go.mod create mode 100644 go.sum create mode 100644 helloworld/main.go create mode 100644 html-xuanran/main.go create mode 100644 json-form-uri-bind-json/form.html create mode 100644 json-form-uri-bind-json/main.go create mode 100644 middleware/main.go create mode 100644 middleware/practice.go create mode 100644 multiple-response/main.go create mode 100644 redirect/main.go create mode 100644 routers-group/main.go create mode 100644 session/main.go create mode 100644 sync_async/main.go create mode 100644 templates/index.tmpl create mode 100644 url-param/main.go diff --git a/api-param/main.go b/api-param/main.go new file mode 100644 index 0000000..0e6c8b6 --- /dev/null +++ b/api-param/main.go @@ -0,0 +1,25 @@ +package main + +import ( + "github.com/gin-gonic/gin" + "net/http" +) + +func main() { + r := gin.Default() + //可以添加api参数 + //访问的是 localhost:8000/user/{$name} + r.GET("/user/:name", func(c *gin.Context) { + name := c.Param("name") + c.String(http.StatusOK, name) + }) + //访问的是 localhost:8000/user/{$name}/* + //返回结果{$name} is /* + r.GET("/user/:name/*ready", func(c *gin.Context) { + name := c.Param("name") + action := c.Param("ready") + c.String(http.StatusOK, name+" is "+action) + }) + + r.Run(":8000") +} diff --git a/cookie/main.go b/cookie/main.go new file mode 100644 index 0000000..c0a6a3d --- /dev/null +++ b/cookie/main.go @@ -0,0 +1,33 @@ +package main + +import ( + "fmt" + "github.com/gin-gonic/gin" +) + +//cookie +//客户端请求服务端,服务端发送cookie给客户端 + +func main() { + r := gin.Default() + //服务端要给客户端cookie + r.GET("cookie", func(c *gin.Context) { + //获取客户端是否携带cookie + cookie, err := c.Cookie("key_cookie") + if err != nil { + fmt.Println(err) + cookie = "NotSet" + + } + c.SetCookie("key_cookie", "value_cookie", 60, "/", "localhost", false, true) + //设置cookie + //maxAge int 过期时间单位是秒 + //path, cookie所在目录 + //domain 域名 + //secure 是否只能通过https访问 + //httpOnly bool 是否允许别人通过js获取cookie + fmt.Println("cookie的值是:", cookie) + }) + r.Run(":8000") + +} diff --git a/cookie/practice.go b/cookie/practice.go new file mode 100644 index 0000000..9d22216 --- /dev/null +++ b/cookie/practice.go @@ -0,0 +1,37 @@ +package main + +import ( + "github.com/gin-gonic/gin" + "net/http" +) + +//设置两个路由login和home +//home查看访问信息 +//login会设置cookie + +func checkCookie(c *gin.Context) { + cookie, err := c.Cookie("login") + if err != nil || cookie != "true" { + c.JSON(http.StatusForbidden, gin.H{"error": http.StatusText(http.StatusForbidden)}) + //如果校验不通过,就结束后续的请求 + c.Abort() + return + } + c.Next() + return +} + +func main() { + r := gin.Default() + { + r.GET("/login", func(c *gin.Context) { + c.SetCookie("login", "true", 60, "/", "localhost", false, true) + c.String(http.StatusOK, "login success!") + }) + r.GET("/home", checkCookie, func(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"data": "home"}) + }) + } + + r.Run(":8000") +} diff --git a/form-param/demo_login/main.go b/form-param/demo_login/main.go new file mode 100644 index 0000000..3dea050 --- /dev/null +++ b/form-param/demo_login/main.go @@ -0,0 +1,58 @@ +package main + +import ( + "fmt" + "github.com/gin-gonic/gin" + "log" + "net/http" +) + +func main() { + r := gin.Default() + r.POST("/form", func(c *gin.Context) { + //表单参数设置默认值 + types := c.DefaultPostForm("type", "default") + //接受其他的 + username := c.PostForm("username") + password := c.PostForm("password") + //多选框 + hobbys := c.PostFormArray("hobby") + c.String(http.StatusOK, + fmt.Sprintf("type is %s,username is %s,password is %s,hobby is %v", types, username, password, hobbys)) + + }) + r.POST("/upload", func(c *gin.Context) { + //表单取文件 + file, _ := c.FormFile("file") + log.Println(file.Filename) + //上传到项目的根目录,名字就用本身的 + c.SaveUploadedFile(file, file.Filename) + //打印信息 + c.String(200, fmt.Sprintf("uploaded file is %s", file.Filename)) + + }) + //限制表单上传大小8MB 默认为32MB + r.POST("/uploads", func(c *gin.Context) { + r.MaxMultipartMemory = 8 << 20 + //表单取文件 + form, err := c.MultipartForm() + if err != nil { + c.String(http.StatusBadRequest, err.Error()) + } + //获取所有图片 + files := form.File["files"] + for _, file := range files { + //逐个存 + err = c.SaveUploadedFile(file, file.Filename) + if err != nil { + c.String(http.StatusBadRequest, err.Error()) + return + } + + } + c.String(200, fmt.Sprintf("uploaded files is %s,num:%v", form.File["files"][0].Filename, len(files))) + + }) + + r.Run(":8000") +} diff --git a/form-param/page/login.html b/form-param/page/login.html new file mode 100644 index 0000000..96dca79 --- /dev/null +++ b/form-param/page/login.html @@ -0,0 +1,35 @@ + + + + + 登录 + + + +
+ 用户名: +
+ 密  码: + 兴  趣: + 跑步 + 游戏 + 金钱 +
+ +
+ + +
+ 头像: +
+ +
+ +
+ 多个文件: +
+ +
+ + + \ No newline at end of file diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..38389b4 --- /dev/null +++ b/go.mod @@ -0,0 +1,33 @@ +module Gin + +go 1.23.0 + +require ( + github.com/bytedance/sonic v1.12.2 // indirect + github.com/bytedance/sonic/loader v0.2.0 // indirect + github.com/cloudwego/base64x v0.1.4 // indirect + github.com/cloudwego/iasm v0.2.0 // indirect + github.com/gabriel-vasile/mimetype v1.4.5 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/gin-gonic/gin v1.10.0 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.22.1 // indirect + github.com/goccy/go-json v0.10.3 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.8 // indirect + github.com/leodido/go-urn v1.4.0 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/pelletier/go-toml/v2 v2.2.3 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + golang.org/x/arch v0.10.0 // indirect + golang.org/x/crypto v0.27.0 // indirect + golang.org/x/net v0.29.0 // indirect + golang.org/x/sys v0.25.0 // indirect + golang.org/x/text v0.18.0 // indirect + google.golang.org/protobuf v1.34.2 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..1de6a82 --- /dev/null +++ b/go.sum @@ -0,0 +1,77 @@ +github.com/bytedance/sonic v1.12.2 h1:oaMFuRTpMHYLpCntGca65YWt5ny+wAceDERTkT2L9lg= +github.com/bytedance/sonic v1.12.2/go.mod h1:B8Gt/XvtZ3Fqj+iSKMypzymZxw/FVwgIGKzMzT9r/rk= +github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/bytedance/sonic/loader v0.2.0 h1:zNprn+lsIP06C/IqCHs3gPQIvnvpKbbxyXQP1iU4kWM= +github.com/bytedance/sonic/loader v0.2.0/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU= +github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y= +github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w= +github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg= +github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.5 h1:J7wGKdGu33ocBOhGy0z653k/lFKLFDPJMG8Gql0kxn4= +github.com/gabriel-vasile/mimetype v1.4.5/go.mod h1:ibHel+/kbxn9x2407k1izTA1S81ku1z/DlgOW2QE0M4= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU= +github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y= +github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= +github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= +github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.22.1 h1:40JcKH+bBNGFczGuoBYgX4I6m/i27HYW8P9FDk5PbgA= +github.com/go-playground/validator/v10 v10.22.1/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM= +github.com/goccy/go-json v0.10.3 h1:KZ5WoDbxAIgm2HNbYckL0se1fHD6rz5j4ywS6ebzDqA= +github.com/goccy/go-json v0.10.3/go.mod h1:oq7eo15ShAhp70Anwd5lgX2pLfOS3QCiwU/PULtXL6M= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.8 h1:+StwCXwm9PdpiEkPyzBXIy+M9KUb4ODm0Zarf1kS5BM= +github.com/klauspost/cpuid/v2 v2.2.8/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ= +github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= +github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= +github.com/pelletier/go-toml/v2 v2.2.3 h1:YmeHyLY8mFWbdkNWwpr+qIL2bEqT0o95WSdkNHvL12M= +github.com/pelletier/go-toml/v2 v2.2.3/go.mod h1:MfCQTFTvCcUyyvvwm1+G6H/jORL20Xlb6rzQu9GuUkc= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.10.0 h1:S3huipmSclq3PJMNe76NGwkBR504WFkQ5dhzWzP8ZW8= +golang.org/x/arch v0.10.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.27.0 h1:GXm2NjJrPaiv/h1tb2UH8QfgC/hOf/+z0p6PT8o1w7A= +golang.org/x/crypto v0.27.0/go.mod h1:1Xngt8kV6Dvbssa53Ziq6Eqn0HqbZi5Z6R0ZpwQzt70= +golang.org/x/net v0.29.0 h1:5ORfpBpCs4HzDYoodCDBbwHzdR5UrLBZ3sOnUJmFoHo= +golang.org/x/net v0.29.0/go.mod h1:gLkgy8jTGERgjzMic6DS9+SP0ajcu6Xu3Orq/SpETg0= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.25.0 h1:r+8e+loiHxRqhXVl6ML1nO3l1+oFoWbnlu2Ehimmi34= +golang.org/x/sys v0.25.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.18.0 h1:XvMDiNzPAl0jr17s6W9lcaIhGUfUORdGCNsuLmPG224= +golang.org/x/text v0.18.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/helloworld/main.go b/helloworld/main.go new file mode 100644 index 0000000..e83d72f --- /dev/null +++ b/helloworld/main.go @@ -0,0 +1,32 @@ +package main + +import ( + "github.com/gin-gonic/gin" + "net/http" +) + +//gin 的hello world + +func main() { + //1.创建路由 + + // 默认使用了两个中间件 Logger(), Recovery() + r := gin.Default() + + //r:=gin.New() //也可以创建不带中间件的路由 + + //2.绑定路由规则 + //gin.Context 封装了request和response + r.GET("/", func(c *gin.Context) { + c.String(http.StatusOK, "Hello world") + }) + r.POST("/post", post) + r.PUT("/put") + + //3.监听端口 默认在8080 + r.Run(":8000") +} + +func post(c *gin.Context) { + +} diff --git a/html-xuanran/main.go b/html-xuanran/main.go new file mode 100644 index 0000000..a6edd97 --- /dev/null +++ b/html-xuanran/main.go @@ -0,0 +1,21 @@ +package main + +import ( + "github.com/gin-gonic/gin" + "net/http" +) + +//html渲染 + +func main() { + //创建路由 + r := gin.Default() + //加载模板文件 + r.LoadHTMLGlob("./templates/*") + r.GET("/index", func(c *gin.Context) { + //根据文件名渲染 + //JSON将title替换 + c.HTML(http.StatusOK, "index.tmpl", gin.H{"title": "我的标题"}) + }) + r.Run(":8000") +} diff --git a/json-form-uri-bind-json/form.html b/json-form-uri-bind-json/form.html new file mode 100644 index 0000000..c069ea5 --- /dev/null +++ b/json-form-uri-bind-json/form.html @@ -0,0 +1,18 @@ + + + + + 登录 + + +
+ 用户名: + +
+ 密  码: + + + +
+ + \ No newline at end of file diff --git a/json-form-uri-bind-json/main.go b/json-form-uri-bind-json/main.go new file mode 100644 index 0000000..f0a965b --- /dev/null +++ b/json-form-uri-bind-json/main.go @@ -0,0 +1,85 @@ +package main + +import ( + "github.com/gin-gonic/gin" + "net/http" +) + +type Login struct { + //binding:"required" required 修饰的字段,若接受为控制 则报错 是必选字段 + User string `form:"username" json:"user" uri:"user" xml:"user" binding:"required"` + Password string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"` +} + +func main() { + //绑定JSON-结构体 + //bindJson() + //绑定form-结构体 + //bindForm() + //绑定uri-结构体 + //bindUri() + +} + +func bindJson() { + r := gin.Default() + //Json绑定 + r.POST("/loginJSON", func(c *gin.Context) { + //声明接收的变量 + var json Login + //将request中的body,自动按照json格式解析到结构体 + //gin.H封装了生成json数据的工具 + if err := c.ShouldBindJSON(&json); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + //判断用户名密码是否正确 + if json.User != "admin" || json.Password != "admin" { + c.JSON(http.StatusUnauthorized, gin.H{"error": "wrong username or password"}) + return + } + c.JSON(http.StatusOK, gin.H{"message": "ok"}) + }) + r.Run(":8000") +} + +func bindForm() { + r := gin.Default() + r.POST("/loginform", func(c *gin.Context) { + var form Login + //Bind()默认解析并绑定form格式 + //根据请求头中的content-type自动推断 + if err := c.Bind(&form); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + if form.User != "admin" || form.Password != "admin" { + c.JSON(http.StatusUnauthorized, gin.H{"error": "wrong username or password"}) + return + } + c.JSON(http.StatusOK, gin.H{"message": "ok"}) + + }) + r.Run(":8000") +} + +// http://127.0.0.1/admin/admin +func bindUri() { + r := gin.Default() + r.GET("/:user/:password", func(c *gin.Context) { + var login Login + //Bind()默认解析并绑定form格式 + //根据请求头中的content-type自动推断 + if err := c.ShouldBindUri(&login); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + if login.User != "admin" || login.Password != "admin" { + c.JSON(http.StatusUnauthorized, gin.H{"error": "wrong username or password"}) + return + } + c.JSON(http.StatusOK, gin.H{"message": "ok"}) + + }) + r.Run(":8000") +} diff --git a/middleware/main.go b/middleware/main.go new file mode 100644 index 0000000..44e88ae --- /dev/null +++ b/middleware/main.go @@ -0,0 +1,52 @@ +package main + +import ( + "fmt" + "github.com/gin-gonic/gin" + "time" +) + +//定义一个GIN中间件 + +func middleware() gin.HandlerFunc { + return func(c *gin.Context) { + t1 := time.Now() + fmt.Println("中间件开始执行了") + //设置变量到context的key中,可以通过GET取到 + c.Set("request", "中间件") + //执行函数 拦截handler + c.Next() + status := c.Writer.Status() + fmt.Println("中间件执行完毕", status) + t2 := time.Since(t1) + fmt.Println("time: ", t2) + } +} + +func main() { + //1.创建路由 + r := gin.Default() + //注册中间件 + r.Use(middleware()) + //{}是为了代码规范 + { + r.GET("/middleware", func(c *gin.Context) { + //取值 + + req, _ := c.Get("request") + fmt.Println("req:", req) + //页面接收 + c.JSON(200, gin.H{"request": req}) + }) + //跟路由后面是定义的局部中间件 + r.GET("/middleware2", middleware(), func(c *gin.Context) { + //取值 + + req, _ := c.Get("request") + fmt.Println("req:", req) + //页面接收 + c.JSON(200, gin.H{"request": req}) + }) + } + r.Run(":8000") +} diff --git a/middleware/practice.go b/middleware/practice.go new file mode 100644 index 0000000..bf0d3b2 --- /dev/null +++ b/middleware/practice.go @@ -0,0 +1,36 @@ +package main + +import ( + "fmt" + "github.com/gin-gonic/gin" + "time" +) + +//定义一个中间件程序计时,执行函数后应该打印的执行时间 + +func timeCal(c *gin.Context) { + start := time.Now() + c.Next() + //统计时间 + since := time.Since(start) + fmt.Println("程序耗时", since) +} + +func main() { + r := gin.Default() + r.Use(timeCal) + shopping := r.Group("/shopping") + { + shopping.GET("/index", shopIndexHandler) + shopping.GET("/home", shophomeHandler) + } + r.Run(":8000") +} + +func shopIndexHandler(c *gin.Context) { + time.Sleep(time.Second * 5) +} + +func shophomeHandler(c *gin.Context) { + time.Sleep(time.Second * 3) +} diff --git a/multiple-response/main.go b/multiple-response/main.go new file mode 100644 index 0000000..2e01f5b --- /dev/null +++ b/multiple-response/main.go @@ -0,0 +1,50 @@ +package main + +import ( + "github.com/gin-gonic/gin" + "github.com/gin-gonic/gin/testdata/protoexample" +) + +var r = gin.Default() + +// 多种响应方式 +func main() { + //1.JSON + r.GET("/someJSON", func(c *gin.Context) { + c.JSON(200, gin.H{"someJson": true}) + }) + //2.结构体响应 + r.GET("/someStruct", func(c *gin.Context) { + var msg struct { + Name string + Massage string + Num int + } + msg.Name = "hello" + msg.Num = 100 + msg.Massage = "root" + c.JSON(200, &msg) + + }) + //3.XML + r.GET("/someXml", func(c *gin.Context) { + c.XML(200, gin.H{"someXml": true}) + }) + //4.YAML响应 + r.GET("/someYaml", func(c *gin.Context) { + c.YAML(200, gin.H{"someYaml": true}) + }) + //5.protobuf格式,谷歌开发的高效存储读取的工具 + r.GET("/someProtobuf", func(c *gin.Context) { + reps := []int64{int64(1), int64(2)} + //定义数据 + label := "label" + //传protobuf格式数据 + data := &protoexample.Test{ + Label: &label, + Reps: reps, + } + c.ProtoBuf(200, data) + }) + r.Run(":8000") +} diff --git a/redirect/main.go b/redirect/main.go new file mode 100644 index 0000000..293854f --- /dev/null +++ b/redirect/main.go @@ -0,0 +1,15 @@ +package main + +import ( + "github.com/gin-gonic/gin" + "net/http" +) + +func main() { + r := gin.Default() + r.GET("/redirect", func(c *gin.Context) { + //支持内部和外部重定向 + c.Redirect(http.StatusMovedPermanently, "http://www.baidu.com") + }) + r.Run(":8000") +} diff --git a/routers-group/main.go b/routers-group/main.go new file mode 100644 index 0000000..c6cdc20 --- /dev/null +++ b/routers-group/main.go @@ -0,0 +1,32 @@ +package main + +import ( + "fmt" + "github.com/gin-gonic/gin" +) + +func main() { + r := gin.Default() + //路由组:处理GET请求 + v1 := r.Group("/v1") + //{}是书写规范 + { + v1.GET("/login", login) + v1.GET("/submit", submit) + } + v2 := r.Group("/v2") + { + v2.POST("/login", login) + v2.POST("/submit", submit) + } + r.Run(":8000") +} + +func login(c *gin.Context) { + name := c.DefaultQuery("name", "Jack") + c.String(200, fmt.Sprintf("hello:%s", name)) +} +func submit(c *gin.Context) { + name := c.DefaultQuery("name", "lily") + c.String(200, fmt.Sprintf("hello:%s", name)) +} diff --git a/session/main.go b/session/main.go new file mode 100644 index 0000000..0de05ec --- /dev/null +++ b/session/main.go @@ -0,0 +1,10 @@ +package main + +//session中间件开发 +//1.session模块设计 +//本质上就是k-v。通过key进行增删改查 +//session可以存储在内存或者redis中 + +func main() { + +} diff --git a/sync_async/main.go b/sync_async/main.go new file mode 100644 index 0000000..6e5523d --- /dev/null +++ b/sync_async/main.go @@ -0,0 +1,27 @@ +package main + +import ( + "github.com/gin-gonic/gin" + "log" + "time" +) + +func main() { + r := gin.Default() + r.GET("/log_async", func(c *gin.Context) { + //1.异步 + //启动goroutine时,不应该使用原始上下文,应该使用副本来处理 + copyContext := c.Copy() + go func() { + //异步处理 + time.Sleep(3 * time.Second) + log.Println("异步执行:" + copyContext.Request.URL.Path) + }() + }) + //2.同步 + r.GET("/log_sync", func(c *gin.Context) { + time.Sleep(3 * time.Second) + log.Println("同步执行:" + c.Request.URL.Path) + }) + r.Run(":8000") +} diff --git a/templates/index.tmpl b/templates/index.tmpl new file mode 100644 index 0000000..4bd6915 --- /dev/null +++ b/templates/index.tmpl @@ -0,0 +1,5 @@ + +

+ {{.title}} +

+ \ No newline at end of file diff --git a/url-param/main.go b/url-param/main.go new file mode 100644 index 0000000..aa22dd5 --- /dev/null +++ b/url-param/main.go @@ -0,0 +1,22 @@ +package main + +import ( + "fmt" + "github.com/gin-gonic/gin" + "net/http" +) + +// url 参数 +// 可以通过DefaultQuery()或者Query()方法获取 +// DefaultQuery() 若参数不存在则返回默认值 +// Query() 若参数不存在 则返回空串 +func main() { + r := gin.Default() + r.GET("/welcome", func(c *gin.Context) { + name := c.DefaultQuery("name", "wangao") //第二个参数是默认值 + c.String(http.StatusOK, fmt.Sprintf("hello %s", name)) + }) + r.Run(":8000") + //访问 /welcome 返回的是hello wangao (默认值) + //访问 /welcome?name=Jack 返回的是hello Jack +}