一、Gin特点
1、性能优秀
2、基于官方的net/http的有限封装
3、方便 灵活的中间件
4、数据绑定很强大
5、社区比较活跃
二、Gin安装
安装:go get github.com/gin-gonic/gin如果要更新:go get -u github.com/gin-gonic/gin
三、Gin使用
3.1、第一个示例
package mainimport ( "github.com/gin-gonic/gin")func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run() //listen and serve on 0.0.0.0:8080}
a. 然后运行 go run example1.go 之后,b. 在浏览器上输入:http://localhost:8080/ping输出结果:{"message":"pong"}
3.2、基本路由
// 创建带有默认中间件的路由:r := gin.Default()//创建不带中间件的路由://r := gin.New()r.GET("/someGet", getting)r.POST("/somePost", posting)r.PUT("/somePut", putting)r.DELETE("/someDelete", deleting)r.PATCH("/somePatch", patching)r.HEAD("/someHead", head)r.OPTIONS("/someOptions", options)
3.3、获取路由参数
3.3.1、Parameters in path
package mainimport ( "github.com/gin-gonic/gin" "net/http")func main() { r := gin.Default() //这个能匹配 /user/tom , 但是不能匹配 /user/ 或 /user r.GET("/user/:name", func(c *gin.Context) { name := c.Param("name") c.String(http.StatusOK, "Hello %s", name) }) //有一个方法可以匹配 /user/tom, 也可以匹配 /user/tom/send //如果没有任何了路由匹配 /user/tom, 它将会跳转到 /user/tom/ r.GET("/user/:name/*action", func(c *gin.Context) { name := c.Param("name") action := c.Param("action") message := name + " is " + action c.String(http.StatusOK, message) }) r.Run(":8080")}a. 然后运行 go run param1.go 之后,b. 在浏览器上输入:http://localhost:8080/user/tom输出结果:Hello tomc. 在浏览器上输入:http://localhost:8080/user/tom/输出结果:tom is /d. 在浏览器上输入:http://localhost:8080/user/tom/pig输出结构: tom is /pig
3.3.2、query param
一般匹配这种形式的url /welcome?firstname=Jane&lastname=Doe
package main//Querystring parametersimport ( "github.com/gin-gonic/gin" "net/http")func main() { r := gin.Default() r.GET("/welcome", func(c *gin.Context) { firstname := c.DefaultQuery("firstname", "Guest") //如果没有值,还可以给一个默认值 lastname := c.Query("lastname") c.String(http.StatusOK, "Hello %s %s ", firstname, lastname) }) r.Run(":8080")}
a. 然后运行 go run param2.go 之后,b. 在浏览器上输入:http://localhost:8080/welcome?lastname=jimmy输出结果:Hello Guest jimmy
c. 在浏览器上输入:http://localhost:8080/welcome?lastname=jimmy&firstname=tom 输出结果:Hello tom jimmy
3.3.4、表单参数 Form
Multipart/Urlencoded Form
package mainimport ( "github.com/gin-gonic/gin" // "net/http")func main() { r := gin.Default() r.POST("/form_post", func(c *gin.Context) { message := c.PostForm("message") nick := c.DefaultPostForm("nick", "guest") c.JSON(200, gin.H{ "status": "posted", "message": message, "nick": nick, }) }) r.Run(":8080")}
3.3.5、 混合型的query + post form
package mainimport ( // "fmt" "github.com/gin-gonic/gin")/*POST /post?id=1234&page=1 HTTP/1.1Content-Type: application/x-www-form-urlencodedname=manu&message=this_is_great*/func main() { r := gin.Default() r.POST("/post", func(c *gin.Context) { id := c.Query("id") page := c.DefaultQuery("page", "0") name := c.PostForm("name") message := c.PostForm("message") // fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message) c.JSON(200, gin.H{ "id": id, "page": page, "name": name, "message": message, }) }) r.Run(":8080")}
3.4、解析数据绑定
我们可以给一个请求的数据绑定到一个类型,gin支持绑定的类型有JSON,XML和标准的表单数据(foo=bar&boo=baz)。 注意绑定时需要设置绑定类型的标签。比如绑定json数据时,
设置 json:"fieldname"
package mainimport ( "github.com/gin-gonic/gin" "net/http")// Binding from JSONtype User struct { Username string `form:"username" json:"username" binding:"required"` Password string `form:"password" json:"password" binding:"required"` Age int `form:"age" json:"age"`}func main() { r := gin.Default() // Example for binding JSON ({"username": "manu", "password": "123"}) r.POST("/loginJSON", func(c *gin.Context) { var json User if err := c.ShouldBindJSON(&json); err == nil { if json.Username == "manu" && json.Password == "123" { c.JSON(http.StatusOK, gin.H{"status": "you are logged in"}) } else { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized", "username": json.Username, "pass": json.Password}) } } else { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } }) // Example for binding a HTML form (user=manu&password=123) r.POST("/loginForm", func(c *gin.Context) { var form User if err := c.ShouldBind(&form); err != nil { if form.Username == "manu" && form.Password == "123" { c.JSON(http.StatusOK, gin.H{"status": "you are logged in 2"}) } else { c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized 2"}) } } else { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } }) r.Run(":8080")}