go-GIN 入门到 ….(继续更新中)
装置 gin
-
参考
https://gin-gonic.com/docs/quickstart/
-
设置环境变量
export GOPATH=~/golang export PATH=$PATH:$GOPATH/bin # or by vim ~/.bashrc or by ~/.zshrc
-
gin
$ go get -u github.com/gin-gonic/gin
疾速开始
-
创立文件
// example.go package main import("github.com/gin-gonic/gin") func main(){r := gin.Default() r.GET("/", func(c *gin.Context){ c.JSON(200, gin.H{"msg": "pong",}) }) r.Run()}
-
运行文件
$ go run main.go [GIN-debug] [WARNING] Creating an Engine instance with the Logger and Recovery middleware already attached. [GIN-debug] [WARNING] Running in "debug" mode. Switch to "release" mode in production. - using env: export GIN_MODE=release - using code: gin.SetMode(gin.ReleaseMode) [GIN-debug] GET / --> main.main.func1 (3 handlers) [GIN-debug] [WARNING] You trusted all proxies, this is NOT safe. We recommend you to set a value. Please check https://pkg.go.dev/github.com/gin-gonic/gin#readme-don-t-trust-all-proxies for details. [GIN-debug] Environment variable PORT is undefined. Using port :8080 by default [GIN-debug] Listening and serving HTTP on :8080
路由
-
无参数
r.GET("/hello", func(c *gin.Context){c.String(200, "hello") })
$ curl http://127.0.0.1:8080/hello hello %
-
动静路由
r.GET("/hello/:name", func(c *gin.Context){name := c.Param("name") c.String(200, name) })
$ curl http://127.0.0.1:8080/hello/golang golang
-
带 Query 参数
// hello?name=xxx&age=xxx r.GET("/hello", func(c *gin.Context){name := c.Query("name") age := c.DefaultQuery("age", "18") // 不存在取左边的默认值 c.String(200, "%s: %s", name, age) })
$ curl http://127.0.0.1:8080/hello?name=golang golang: 18
-
获取 POST 参数
r.POST("/hello", func(c *gin.Context){name := c.PostForm("name") age := c.DefaultPostForm("age", "18") c.JSON(200, gin.H{ "name": name, "age": age, }) })
$ curl http://127.0.0.1:8080/hello -X POST -d 'name=golang&age=26' {"age":"26","name":"golang"}
-
Map 参数 (字典参数)
r.POST("/hello", func(c *gin.Context){ages := c.QueryMap("ages") names := c.PostFormMap("names") c.JSON(200, gin.H{ "name": names, "age": ages, }) })
$ curl -g "http://localhost:8080/hello?ages[a]=18&ages[b]=26" -X POST -d 'names[a]=Sam&names[b]=David' {"age":{"a":"18","b":"26"},"name":{"a":"Sam","b":"David"}}
-
重定向 (Redirect)
r.GET("/goIndex", func(c *gin.Context){ c.Request.URL.Path = "/" r.HandleContext(c) })
$ curl http://127.0.0.1:8080/goIndex {"msg":"pong"}
-
分组路由 (Grouping Routes)
defaultHandler := func(c *gin.Context) { c.JSON(200, gin.H{"path": c.FullPath(), }) } // group: v1 v1 := r.Group("/v1") {v1.GET("/name1", defaultHandler) v1.GET("/name2", defaultHandler) } // group: v2 v2 := r.Group("/v2") {v2.GET("/name1", defaultHandler) v2.GET("/name2", defaultHandler) }
$ curl http://127.0.0.1:8080/v1/name1 {"path":"/v1/name1"} $ curl http://127.0.0.1:8080/v1/name2 {"path":"/v1/name2"} $ curl http://127.0.0.1:8080/v2/name1 {"path":"/v2/name1"} $ curl http://127.0.0.1:8080/v2/name2 {"path":"/v2/name2"}