Gin 中文文档

Gin 中文文档,本文档基于 Gin 官方文档。不定期更新。

Gin 中文文档 - 图1

Build Status codecov Go Report Card GoDoc Join the chat at https://gitter.im/gin-gonic/gin Sourcegraph Open Source Helpers Release

Gin 是一个使用 Go 语言写的 web 框架.它拥有与 Martini 相似的 API,但它比 Martini 快 40 多倍。Gin 内部使用 Golang 最快的 HTTP 路由器 httprouter。如果你需要更高的性能,更快的开发效率,你会喜欢上 Gin。

Contents

安装

Installation

安装 gin 包之前,需要先下载安装 Go 以及设置好 Go 工作空间。

  1. 下载安装(Go 版本 1.10+):
  1. $ go get -u github.com/gin-gonic/gin
  1. 导入包:
  1. import "github.com/gin-gonic/gin"
  1. (可选) 导入 net/http。 如果需要 http 包中的一些参量如 http.StatusOK
  1. import "net/http"

使用包管理工具 Govendor

  1. go get govendor
  1. $ go get github.com/kardianos/govendor
  1. 创建项目文件夹并进入
  1. $ mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"
  1. 初始化你的项目并添加 gin
  1. $ govendor init
  2. $ govendor fetch github.com/gin-gonic/gin@v1.3
  1. 复制一个模板到项目
  1. $ curl https://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go > main.go
  1. 启动项目
  1. $ go run main.go

快速开始

Quick start

  1. # 假定下面的代码在 example.go 文件中
  2. $ cat example.go
  1. package main
  2. import "github.com/gin-gonic/gin"
  3. func main() {
  4. r := gin.Default()
  5. r.GET("/ping", func(c *gin.Context) {
  6. c.JSON(200, gin.H{
  7. "message": "pong",
  8. })
  9. })
  10. r.Run() // listen and serve on 0.0.0.0:8080
  11. }
  1. # 云运行 example.go 然后在浏览器访问 0.0.0.0:8080/ping
  2. $ go run example.go

基准

Benchmarks

Gin 使用 HttpRouter 的一个定制版本

查看所有基准

Benchmark name (1) (2) (3) (4)
BenchmarkGin_GithubAll 30000 48375 0 0
BenchmarkAce_GithubAll 10000 134059 13792 167
BenchmarkBear_GithubAll 5000 534445 86448 943
BenchmarkBeego_GithubAll 3000 592444 74705 812
BenchmarkBone_GithubAll 200 6957308 698784 8453
BenchmarkDenco_GithubAll 10000 158819 20224 167
BenchmarkEcho_GithubAll 10000 154700 6496 203
BenchmarkGocraftWeb_GithubAll 3000 570806 131656 1686
BenchmarkGoji_GithubAll 2000 818034 56112 334
BenchmarkGojiv2_GithubAll 2000 1213973 274768 3712
BenchmarkGoJsonRest_GithubAll 2000 785796 134371 2737
BenchmarkGoRestful_GithubAll 300 5238188 689672 4519
BenchmarkGorillaMux_GithubAll 100 10257726 211840 2272
BenchmarkHttpRouter_GithubAll 20000 105414 13792 167
BenchmarkHttpTreeMux_GithubAll 10000 319934 65856 671
BenchmarkKocha_GithubAll 10000 209442 23304 843
BenchmarkLARS_GithubAll 20000 62565 0 0
BenchmarkMacaron_GithubAll 2000 1161270 204194 2000
BenchmarkMartini_GithubAll 200 9991713 226549 2325
BenchmarkPat_GithubAll 200 5590793 1499568 27435
BenchmarkPossum_GithubAll 10000 319768 84448 609
BenchmarkR2router_GithubAll 10000 305134 77328 979
BenchmarkRivet_GithubAll 10000 132134 16272 167
BenchmarkTango_GithubAll 3000 552754 63826 1618
BenchmarkTigerTonic_GithubAll 1000 1439483 239104 5374
BenchmarkTraffic_GithubAll 100 11383067 2659329 21848
BenchmarkVulcan_GithubAll 5000 394253 19894 609
  • (1): 持续时间达到的总重复次数越多,意味着结果越好
  • (2): 单次重复持续时间(ns / op)越低越好
  • (3): 堆内存(B / op)越低越好
  • (4): 平均每次重复分配 (allocs/op) 越低越好

Gin v1. stable

  • Zero allocation router.
  • Still the fastest http router and framework. From routing to writing.
  • Complete suite of unit tests
  • Battle tested
  • API frozen, new releases will not break your code.

使用 jsoniter 构建

Build with jsoniter

Gin 使用 encoding/json 作为默认的 json 解析器但你可以构建时指定成 jsoniter

  1. $ go build -tags=jsoniter .

API示例

Api examples

使用 GET, POST, PUT, PATCH, DELETE 和 OPTIONS 路由方法

Using GET, POST, PUT, PATCH, DELETE and OPTIONS

  1. func main() {
  2. // 禁用控制台颜色
  3. // gin.DisableConsoleColor()
  4. // 用默认的中间件创建一个gin路由器:
  5. // logger and recovery (crash-free) middleware
  6. // 包含日志和恢复(不崩溃)中间件
  7. router := gin.Default()
  8. router.GET("/someGet", getting)
  9. router.POST("/somePost", posting)
  10. router.PUT("/somePut", putting)
  11. router.DELETE("/someDelete", deleting)
  12. router.PATCH("/somePatch", patching)
  13. router.HEAD("/someHead", head)
  14. router.OPTIONS("/someOptions", options)
  15. // By default it serves on :8080 unless a
  16. // PORT environment variable was defined.
  17. // 默认监听8080端口,除非指定了PORT环境变量
  18. router.Run()
  19. // router.Run(":3000") 指定端口号为 :3000
  20. }

路径参数

Parameters in path

  1. func main() {
  2. router := gin.Default()
  3. // 路由1 匹配 /user/john,但是不匹配 /user/ 或 /user
  4. router.GET("/user/:name", func(c *gin.Context) {
  5. name := c.Param("name")
  6. c.String(http.StatusOK, "Hello %s", name)
  7. })
  8. // 路由2 这个会匹配 /user/john/ 和 /user/john/send
  9. router.GET("/user/:name/*action", func(c *gin.Context) {
  10. name := c.Param("name")
  11. action := c.Param("action")
  12. message := name + " is " + action
  13. c.String(http.StatusOK, message)
  14. })
  15. // 注意 /user/:name 和 /user/:name/是俩个完全不同的路由
  16. router.Run(":8080")
  17. }

查询字符串参数

Querystring parameters

  1. func main() {
  2. router := gin.Default()
  3. // 查询字符串参数通过解析基础请求对象获得
  4. // 请求响应匹配url: /welcome?firstname=Jane&lastname=Doe
  5. router.GET("/welcome", func(c *gin.Context) {
  6. // 取firstname的值,不存在则设为Guest
  7. firstname := c.DefaultQuery("firstname", "Guest")
  8. lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")
  9. c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
  10. })
  11. router.Run(":8080")
  12. }

Multipart/Urlencoded 表单

Multipart/Urlencoded Form

  1. func main() {
  2. router := gin.Default()
  3. router.POST("/form_post", func(c *gin.Context) {
  4. message := c.PostForm("message")
  5. nick := c.DefaultPostForm("nick", "anonymous")
  6. c.JSON(200, gin.H{
  7. "status": "posted",
  8. "message": message,
  9. "nick": nick,
  10. })
  11. })
  12. router.Run(":8080")
  13. }

其他示例: 查询 + 表单

Another example: query + post form

  1. POST /post?id=1234&page=1 HTTP/1.1
  2. Content-Type: application/x-www-form-urlencoded
  3. name=manu&message=this_is_great
  1. func main() {
  2. router := gin.Default()
  3. router.POST("/post", func(c *gin.Context) {
  4. // url 中查询数据
  5. id := c.Query("id")
  6. page := c.DefaultQuery("page", "0")
  7. // post 表单中数据
  8. name := c.PostForm("name")
  9. message := c.PostForm("message")
  10. fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
  11. })
  12. router.Run(":8080")
  13. }
  1. id: 1234; page: 1; name: manu; message: this_is_great

以映射表示的查询字符串或者表单参数

Map as querystring or postform parameters

  1. POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1
  2. Content-Type: application/x-www-form-urlencoded
  3. names[first]=thinkerou&names[second]=tianou
  1. func main() {
  2. router := gin.Default()
  3. router.POST("/post", func(c *gin.Context) {
  4. ids := c.QueryMap("ids")
  5. names := c.PostFormMap("names")
  6. fmt.Printf("ids: %v; names: %v", ids, names)
  7. })
  8. router.Run(":8080")
  9. }
  1. ids: map[b:hello a:1234], names: map[second:tianou first:thinkerou]

上传文件

Upload files

单个文件

参考问题 #774 和细节 example code.

file.Filename 是不可信的。 查看 MDN Content-Disposition#1693

filename 总是可选的,应用程序不能盲目地使用它:应该删除路径信息,并执行到服务器文件系统规则的转换。

  1. func main() {
  2. router := gin.Default()
  3. // 设置可以上传 multipart 表单的最大体积(默认为 32MiB)
  4. // router.MaxMultipartMemory = 8 << 20 // 8 MiB
  5. router.POST("/upload", func(c *gin.Context) {
  6. // single file
  7. file, _ := c.FormFile("file")
  8. log.Println(file.Filename)
  9. // 复制文件到指定目标
  10. // c.SaveUploadedFile(file, dst)
  11. c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
  12. })
  13. router.Run(":8080")
  14. }

使用 curl:

  1. curl -X POST http://localhost:8080/upload \
  2. -F "file=@/Users/appleboy/test.zip" \
  3. -H "Content-Type: multipart/form-data"

多个文件

查看细节 example code.

  1. func main() {
  2. router := gin.Default()
  3. // 设置可以上传 multipart 表单的最大体积(默认为 32MiB)
  4. // router.MaxMultipartMemory = 8 << 20 // 8 MiB
  5. router.POST("/upload", func(c *gin.Context) {
  6. // Multipart form
  7. form, _ := c.MultipartForm()
  8. files := form.File["upload[]"]
  9. for _, file := range files {
  10. log.Println(file.Filename)
  11. // Upload the file to specific dst.
  12. // c.SaveUploadedFile(file, dst)
  13. }
  14. c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
  15. })
  16. router.Run(":8080")
  17. }

使用 curl:

  1. curl -X POST http://localhost:8080/upload \
  2. -F "upload[]=@/Users/appleboy/test1.zip" \
  3. -F "upload[]=@/Users/appleboy/test2.zip" \
  4. -H "Content-Type: multipart/form-data"

分组路由

Grouping routes

  1. func main() {
  2. router := gin.Default()
  3. // Simple group: v1
  4. v1 := router.Group("/v1")
  5. {
  6. v1.POST("/login", loginEndpoint)
  7. v1.POST("/submit", submitEndpoint)
  8. v1.POST("/read", readEndpoint)
  9. }
  10. // Simple group: v2
  11. v2 := router.Group("/v2")
  12. {
  13. v2.POST("/login", loginEndpoint)
  14. v2.POST("/submit", submitEndpoint)
  15. v2.POST("/read", readEndpoint)
  16. }
  17. router.Run(":8080")
  18. }

无中间件路由

Blank Gin without middleware by default

使用

  1. r := gin.New()

而不是

  1. // 默认情况已启用了 log 和恢复中间件
  2. r := gin.Default()

使用中间件

Using middleware

  1. func main() {
  2. // 创建不含默认中间件的路由
  3. r := gin.New()
  4. // 全局中间件
  5. // Logger 中间件会将日志写到 gin.DefaultWriter 即使指定 GIN_MODE=release
  6. // 默认情况下 gin.DefaultWriter = os.Stdout
  7. r.Use(gin.Logger())
  8. // Recovery 中间件从任何 panic 恢复 并且写入一个 500 状态码
  9. r.Use(gin.Recovery())
  10. // 可以随心添加中间件到任何你想要添加的路由上
  11. r.GET("/benchmark", MyBenchLogger(), benchEndpoint)
  12. // 认证分组
  13. // authorized := r.Group("/", AuthRequired())
  14. // exactly the same as:
  15. authorized := r.Group("/")
  16. // per group middleware! in this case we use the custom created
  17. // AuthRequired() middleware just in the "authorized" group.
  18. authorized.Use(AuthRequired())
  19. {
  20. authorized.POST("/login", loginEndpoint)
  21. authorized.POST("/submit", submitEndpoint)
  22. authorized.POST("/read", readEndpoint)
  23. // 嵌套分组
  24. testing := authorized.Group("testing")
  25. testing.GET("/analytics", analyticsEndpoint)
  26. }
  27. // Listen and serve on 0.0.0.0:8080
  28. r.Run(":8080")
  29. }

如何写日志

How to write log file

  1. func main() {
  2. // 当你不需要写入日志时颜色提示时, 关闭控制台颜色.
  3. gin.DisableConsoleColor()
  4. // 将日志写入指定文件
  5. f, _ := os.Create("gin.log")
  6. gin.DefaultWriter = io.MultiWriter(f)
  7. // 同时使用文件与控制台记录日志
  8. // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
  9. router := gin.Default()
  10. router.GET("/ping", func(c *gin.Context) {
  11. c.String(200, "pong")
  12. })
  13. router.Run(":8080")
  14. }

自定义 log format

Custom log format

  1. func main() {
  2. router := gin.New()
  3. // LoggerWithFormatter 中间件将 log 写入 gin.DefaultWriter
  4. // 默认情况下 gin.DefaultWriter = os.Stdout
  5. router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
  6. // 自定义格式
  7. return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
  8. param.ClientIP,
  9. param.TimeStamp.Format(time.RFC1123),
  10. param.Method,
  11. param.Path,
  12. param.Request.Proto,
  13. param.StatusCode,
  14. param.Latency,
  15. param.Request.UserAgent(),
  16. param.ErrorMessage,
  17. )
  18. }))
  19. router.Use(gin.Recovery())
  20. router.GET("/ping", func(c *gin.Context) {
  21. c.String(200, "pong")
  22. })
  23. router.Run(":8080")
  24. }

输出:

  1. ::1 - [Fri, 07 Dec 2018 17:04:38 JST] "GET /ping HTTP/1.1 200 122.767µs "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36" "

Controlling Log output coloring

默认情况下,控制台输出的日志颜色依赖于检测到的 TTY。

永远不为日志着色:

  1. func main() {
  2. // 禁用日志颜色
  3. gin.DisableConsoleColor()
  4. // 创建一个包含默认中间件的 gin 路由器:
  5. // logger and recovery (crash-free) middleware
  6. router := gin.Default()
  7. router.GET("/ping", func(c *gin.Context) {
  8. c.String(200, "pong")
  9. })
  10. router.Run(":8080")
  11. }

总是为日志着色:

  1. func main() {
  2. // 强制使用日志颜色
  3. gin.DisableConsoleColor()
  4. // 创建一个包含默认中间件的 gin 路由器:
  5. // logger and recovery (crash-free) middleware
  6. router := gin.Default()
  7. router.GET("/ping", func(c *gin.Context) {
  8. c.String(200, "pong")
  9. })
  10. router.Run(":8080")
  11. }

模型绑定与验证

Model binding and validation

使用 model binding 绑定请求主体到类型,Gin 支持绑定 JSON, XML, 标准表单。(foo=bar&boo=baz)

Gin 使用 go-playground/validator.v8 验证。 在 此处 查看有关标签用法的完整文档。

注意你需要在所需要绑定的字段设置对应的绑定标签。例如,当从 JSON 绑定时,设置 json:"fieldname"

Gin 提供两种方法集绑定

  • Type - Must bind
    • Methods - Bind, BindJSON, BindXML, BindQuery
    • Behavior - 这些方法底层使用 MustBindWith 。如果绑定失败,该请求会使用 c.AbortWithError(400, err).SetType(ErrorTypeBind) 中止舍弃。 返回 400 状态码,设置 Content-Type 首部为 text/plain; charset=utf-8。注意如果你在此后想设置状态状态码,会导致一个 警告 [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422。 如果你想更好地掌控该行为,考虑使用 ShouldBind 方法。
  • Type - Should bind
    • Methods - ShouldBind, ShouldBindJSON, ShouldBindXML, ShouldBindQuery
    • Behavior - 这些方法底层使用 ShouldBindWith。如果绑定失败,由开发者掌控处理请求与错误。

Gin 会从首部 Content-Type字段推断绑定内容的类型,如果你确定需要绑定内容的类型,可以使用 MustBindWith 或者 ShouldBindWith

你同样可以指定绑定必须提供的字段。如果一个带有 binding:"required" 标签的类型绑定时无对应值,将返回一个错误。

  1. // Binding from JSON
  2. type Login struct {
  3. User string `form:"user" json:"user" xml:"user" binding:"required"`
  4. Password string `form:"password" json:"password" xml:"password" binding:"required"`
  5. }
  6. func main() {
  7. router := gin.Default()
  8. // Example for binding JSON ({"user": "manu", "password": "123"})
  9. router.POST("/loginJSON", func(c *gin.Context) {
  10. var json Login
  11. if err := c.ShouldBindJSON(&json); err != nil {
  12. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  13. return
  14. }
  15. if json.User != "manu" || json.Password != "123" {
  16. c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
  17. return
  18. }
  19. c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
  20. })
  21. // Example for binding XML (
  22. // <?xml version="1.0" encoding="UTF-8"?>
  23. // <root>
  24. // <user>user</user>
  25. // <password>123</user>
  26. // </root>)
  27. router.POST("/loginXML", func(c *gin.Context) {
  28. var xml Login
  29. if err := c.ShouldBindXML(&xml); err != nil {
  30. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  31. return
  32. }
  33. if xml.User != "manu" || xml.Password != "123" {
  34. c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
  35. return
  36. }
  37. c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
  38. })
  39. // Example for binding a HTML form (user=manu&password=123)
  40. router.POST("/loginForm", func(c *gin.Context) {
  41. var form Login
  42. // This will infer what binder to use depending on the content-type header.
  43. if err := c.ShouldBind(&form); err != nil {
  44. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  45. return
  46. }
  47. if form.User != "manu" || form.Password != "123" {
  48. c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
  49. return
  50. }
  51. c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
  52. })
  53. // Listen and serve on 0.0.0.0:8080
  54. router.Run(":8080")
  55. }

Sample request

  1. $ curl -v -X POST \
  2. http://localhost:8080/loginJSON \
  3. -H 'content-type: application/json' \
  4. -d '{ "user": "manu" }'
  5. > POST /loginJSON HTTP/1.1
  6. > Host: localhost:8080
  7. > User-Agent: curl/7.51.0
  8. > Accept: */*
  9. > content-type: application/json
  10. > Content-Length: 18
  11. >
  12. * upload completely sent off: 18 out of 18 bytes
  13. < HTTP/1.1 400 Bad Request
  14. < Content-Type: application/json; charset=utf-8
  15. < Date: Fri, 04 Aug 2017 03:51:31 GMT
  16. < Content-Length: 100
  17. <
  18. {"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}

跳过验证

使用上面的 curl 命令,将返回错误。因为 Password 字段使用了 binding:"required"。 如果使用 binding:"-",则不会返回错误。

自定义验证器

Custom Validators

可以注册自定义验证器,查看 example code

  1. package main
  2. import (
  3. "net/http"
  4. "reflect"
  5. "time"
  6. "github.com/gin-gonic/gin"
  7. "github.com/gin-gonic/gin/binding"
  8. "gopkg.in/go-playground/validator.v8"
  9. )
  10. // Booking contains binded and validated data.
  11. type Booking struct {
  12. CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`
  13. CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`
  14. }
  15. func bookableDate(
  16. v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,
  17. field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,
  18. ) bool {
  19. if date, ok := field.Interface().(time.Time); ok {
  20. today := time.Now()
  21. if today.Year() > date.Year() || today.YearDay() > date.YearDay() {
  22. return false
  23. }
  24. }
  25. return true
  26. }
  27. func main() {
  28. route := gin.Default()
  29. if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
  30. v.RegisterValidation("bookabledate", bookableDate)
  31. }
  32. route.GET("/bookable", getBookable)
  33. route.Run(":8085")
  34. }
  35. func getBookable(c *gin.Context) {
  36. var b Booking
  37. if err := c.ShouldBindWith(&b, binding.Query); err == nil {
  38. c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
  39. } else {
  40. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  41. }
  42. }
  1. $ curl "localhost:8085/bookable?check_in=2018-04-16&check_out=2018-04-17"
  2. {"message":"Booking dates are valid!"}
  3. $ curl "localhost:8085/bookable?check_in=2018-03-08&check_out=2018-03-09"
  4. {"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}

Struct level validations 可以同样以此注册。 查看 struct-lvl-validation example 学习更多。

只绑定查询字符串

Only Bind Query String

ShouldBindQuery 方法只从查询字符串绑定,而不包括 POST 方法提供的数据。 查看 detail information

  1. package main
  2. import (
  3. "log"
  4. "github.com/gin-gonic/gin"
  5. )
  6. type Person struct {
  7. Name string `form:"name"`
  8. Address string `form:"address"`
  9. }
  10. func main() {
  11. route := gin.Default()
  12. route.Any("/testing", startPage)
  13. route.Run(":8085")
  14. }
  15. func startPage(c *gin.Context) {
  16. var person Person
  17. if c.ShouldBindQuery(&person) == nil {
  18. log.Println("====== Only Bind By Query String ======")
  19. log.Println(person.Name)
  20. log.Println(person.Address)
  21. }
  22. c.String(200, "Success")
  23. }

绑定查询字符串或者 Post Data

Bind Query String or Post Data

查看 detail information

  1. package main
  2. import (
  3. "log"
  4. "time"
  5. "github.com/gin-gonic/gin"
  6. )
  7. type Person struct {
  8. Name string `form:"name"`
  9. Address string `form:"address"`
  10. Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`
  11. CreateTime time.Time `form:"createTime" time_format:"unixNano"`
  12. UnixTime time.Time `form:"unixTime" time_format:"unix"`
  13. }
  14. func main() {
  15. route := gin.Default()
  16. route.GET("/testing", startPage)
  17. route.Run(":8085")
  18. }
  19. func startPage(c *gin.Context) {
  20. var person Person
  21. // If `GET`, only `Form` binding engine (`query`) used.
  22. // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).
  23. // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48
  24. if c.ShouldBind(&person) == nil {
  25. log.Println(person.Name)
  26. log.Println(person.Address)
  27. log.Println(person.Birthday)
  28. log.Println(person.CreateTime)
  29. log.Println(person.UnixTime)
  30. }
  31. c.String(200, "Success")
  32. }

测试:

  1. $ curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"

绑定 Uri

Bind Uri

查看 detail information

  1. package main
  2. import "github.com/gin-gonic/gin"
  3. type Person struct {
  4. ID string `uri:"id" binding:"required,uuid"`
  5. Name string `uri:"name" binding:"required"`
  6. }
  7. func main() {
  8. route := gin.Default()
  9. route.GET("/:name/:id", func(c *gin.Context) {
  10. var person Person
  11. if err := c.ShouldBindUri(&person); err != nil {
  12. c.JSON(400, gin.H{"msg": err})
  13. return
  14. }
  15. c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID})
  16. })
  17. route.Run(":8088")
  18. }

测试:

  1. $ curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3
  2. $ curl -v localhost:8088/thinkerou/not-uuid

绑定 Header

Bind Header

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gin-gonic/gin"
  5. )
  6. type testHeader struct {
  7. Rate int `header:"Rate"`
  8. Domain string `header:"Domain"`
  9. }
  10. func main() {
  11. r := gin.Default()
  12. r.GET("/", func(c *gin.Context) {
  13. h := testHeader{}
  14. if err := c.ShouldBindHeader(&h); err != nil {
  15. c.JSON(200, err)
  16. }
  17. fmt.Printf("%#v\n", h)
  18. c.JSON(200, gin.H{"Rate": h.Rate, "Domain": h.Domain})
  19. })
  20. r.Run()
  21. // client
  22. // curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/
  23. // output
  24. // {"Domain":"music","Rate":300}
  25. }

绑定 HTML 复选框

Bind HTML checkboxes

查看 detail information

main.go

  1. ...
  2. type myForm struct {
  3. Colors []string `form:"colors[]"`
  4. }
  5. ...
  6. func formHandler(c *gin.Context) {
  7. var fakeForm myForm
  8. c.ShouldBind(&fakeForm)
  9. c.JSON(200, gin.H{"color": fakeForm.Colors})
  10. }
  11. ...

form.html

  1. <form action="/" method="POST">
  2. <p>Check some colors</p>
  3. <label for="red">Red</label>
  4. <input type="checkbox" name="colors[]" value="red" id="red" />
  5. <label for="green">Green</label>
  6. <input type="checkbox" name="colors[]" value="green" id="green" />
  7. <label for="blue">Blue</label>
  8. <input type="checkbox" name="colors[]" value="blue" id="blue" />
  9. <input type="submit" />
  10. </form>

结果:

  1. {"color":["red","green","blue"]}

Multipart/Urlencoded 表单绑定

Multipart/Urlencoded binding

  1. type ProfileForm struct {
  2. Name string `form:"name" binding:"required"`
  3. Avatar *multipart.FileHeader `form:"avatar" binding:"required"`
  4. // or for multiple files
  5. // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"`
  6. }
  7. func main() {
  8. router := gin.Default()
  9. router.POST("/profile", func(c *gin.Context) {
  10. // 你可以绑定 multipart form 通过明确的绑定声明:
  11. // c.ShouldBindWith(&form, binding.Form)
  12. // 或者简单地使用 ShouldBind method 自动绑定:
  13. var form ProfileForm
  14. // 该情况下 gin 会自动选择合适的绑定类型
  15. if err := c.ShouldBind(&form); err != nil {
  16. c.String(http.StatusBadRequest, "bad request")
  17. return
  18. }
  19. err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename)
  20. if err != nil {
  21. c.String(http.StatusInternalServerError, "unknown error")
  22. return
  23. }
  24. // db.Save(&form)
  25. c.String(http.StatusOK, "ok")
  26. })
  27. router.Run(":8080")
  28. }

测试:

  1. $ curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile

XML, JSON, YAML and ProtoBuf 渲染

XML, JSON, YAML and ProtoBuf rendering

  1. func main() {
  2. r := gin.Default()
  3. // gin.H 是 map[string]interface{} 的快捷方法
  4. r.GET("/someJSON", func(c *gin.Context) {
  5. c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  6. })
  7. r.GET("/moreJSON", func(c *gin.Context) {
  8. // 你同样可以使用结构体
  9. var msg struct {
  10. Name string `json:"user"`
  11. Message string
  12. Number int
  13. }
  14. msg.Name = "Lena"
  15. msg.Message = "hey"
  16. msg.Number = 123
  17. // 注意 msg.Name 在 JSON 中变成了用 "user" 表示
  18. // 输出: {"user": "Lena", "Message": "hey", "Number": 123}
  19. c.JSON(http.StatusOK, msg)
  20. })
  21. r.GET("/someXML", func(c *gin.Context) {
  22. c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  23. })
  24. r.GET("/someYAML", func(c *gin.Context) {
  25. c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  26. })
  27. r.GET("/someProtoBuf", func(c *gin.Context) {
  28. reps := []int64{int64(1), int64(2)}
  29. label := "test"
  30. // 该 protobuf 的定义在 testdata/protoexample 文件中
  31. data := &protoexample.Test{
  32. Label: &label,
  33. Reps: reps,
  34. }
  35. // 数据在响应中变成二进制格式
  36. // 输出protoexample.Test protobuf序列化数据
  37. c.ProtoBuf(http.StatusOK, data)
  38. })
  39. // Listen and serve on 0.0.0.0:8080
  40. r.Run(":8080")
  41. }

SecureJSON

使用 SecureJSON 防止 JSON 劫持. Default prepends "while(1)," to response body if the given struct is array values.

  1. func main() {
  2. r := gin.Default()
  3. // 可以使用自定义的安全 json 前缀
  4. // r.SecureJsonPrefix(")]}',\n")
  5. r.GET("/someJSON", func(c *gin.Context) {
  6. names := []string{"lena", "austin", "foo"}
  7. // 输出: while(1);["lena","austin","foo"]
  8. c.SecureJSON(http.StatusOK, names)
  9. })
  10. // Listen and serve on 0.0.0.0:8080
  11. r.Run(":8080")
  12. }

JSONP

JSONP

使用 JSONP 请求来自不同域名中的服务器的数据。如果存在查询参数回调,则将回调添加到响应体

  1. func main() {
  2. r := gin.Default()
  3. r.GET("/JSONP", func(c *gin.Context) {
  4. data := gin.H{
  5. "foo": "bar",
  6. }
  7. //callback is x
  8. // Will output : x({\"foo\":\"bar\"})
  9. c.JSONP(http.StatusOK, data)
  10. })
  11. // Listen and serve on 0.0.0.0:8080
  12. r.Run(":8080")
  13. // client
  14. // curl http://127.0.0.1:8080/JSONP?callback=x
  15. }

AsciiJSON

使用 AsciiJSON 生成只由 ASCII 编码的 JSON 字符。

  1. func main() {
  2. r := gin.Default()
  3. r.GET("/someJSON", func(c *gin.Context) {
  4. data := map[string]interface{}{
  5. "lang": "GO语言",
  6. "tag": "<br>",
  7. }
  8. // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}
  9. c.AsciiJSON(http.StatusOK, data)
  10. })
  11. // Listen and serve on 0.0.0.0:8080
  12. r.Run(":8080")
  13. }

PureJSON

Normally, JSON replaces special HTML characters with their unicode entities, e.g. < becomes \u003c. If you want to encode such characters literally, you can use PureJSON instead. This feature is unavailable in Go 1.6 and lower.

  1. func main() {
  2. r := gin.Default()
  3. // Serves unicode entities
  4. r.GET("/json", func(c *gin.Context) {
  5. c.JSON(200, gin.H{
  6. "html": "<b>Hello, world!</b>",
  7. })
  8. })
  9. // Serves literal characters
  10. r.GET("/purejson", func(c *gin.Context) {
  11. c.PureJSON(200, gin.H{
  12. "html": "<b>Hello, world!</b>",
  13. })
  14. })
  15. // listen and serve on 0.0.0.0:8080
  16. r.Run(":8080)
  17. }

提供静态文件

Serving static files

  1. func main() {
  2. router := gin.Default()
  3. router.Static("/assets", "./assets")
  4. router.StaticFS("/more_static", http.Dir("my_file_system"))
  5. router.StaticFile("/favicon.ico", "./resources/favicon.ico")
  6. // Listen and serve on 0.0.0.0:8080
  7. router.Run(":8080")
  8. }

Serving data from reader

  1. func main() {
  2. router := gin.Default()
  3. router.GET("/someDataFromReader", func(c *gin.Context) {
  4. response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")
  5. if err != nil || response.StatusCode != http.StatusOK {
  6. c.Status(http.StatusServiceUnavailable)
  7. return
  8. }
  9. reader := response.Body
  10. contentLength := response.ContentLength
  11. contentType := response.Header.Get("Content-Type")
  12. extraHeaders := map[string]string{
  13. "Content-Disposition": `attachment; filename="gopher.png"`,
  14. }
  15. c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)
  16. })
  17. router.Run(":8080")
  18. }

HTML 渲染

HTML rendering

使用 LoadHTMLGlob() 或者 LoadHTMLFiles()

  1. func main() {
  2. router := gin.Default()
  3. // 加载所有的模板文件
  4. router.LoadHTMLGlob("templates/*")
  5. // 加载某个模板文件
  6. // router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
  7. router.GET("/index", func(c *gin.Context) {
  8. c.HTML(http.StatusOK, "index.tmpl", gin.H{
  9. "title": "Main website",
  10. })
  11. })
  12. router.Run(":8080")
  13. }

templates/index.tmpl

  1. <html>
  2. <h1>
  3. {{ .title }}
  4. </h1>
  5. </html>

渲染原生 HTML

  1. g.LoagHTMLFiles(filepath.Join(staticPath, "index.html"))
  2. router.GET("/", func(c *gin.Context) {
  3. c.HTML(http.StatusOK, "index.html", nil)
  4. })
  5. // 或者
  6. router.GET("/", func(c *gin.Context) {
  7. c.File(filepath.Join(staticPath, "index.html"))
  8. })

使用不同文件夹相同名称的 HTML 模板

  1. func main() {
  2. router := gin.Default()
  3. router.LoadHTMLGlob("templates/**/*")
  4. router.GET("/posts/index", func(c *gin.Context) {
  5. c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
  6. "title": "Posts",
  7. })
  8. })
  9. router.GET("/users/index", func(c *gin.Context) {
  10. c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
  11. "title": "Users",
  12. })
  13. })
  14. router.Run(":8080")
  15. }

templates/posts/index.tmpl

  1. {{ define "posts/index.tmpl" }}
  2. <html><h1>
  3. {{ .title }}
  4. </h1>
  5. <p>Using posts/index.tmpl</p>
  6. </html>
  7. {{ end }}

templates/users/index.tmpl

  1. {{ define "users/index.tmpl" }}
  2. <html><h1>
  3. {{ .title }}
  4. </h1>
  5. <p>Using users/index.tmpl</p>
  6. </html>
  7. {{ end }}

自定义模板渲染器

可以使用自定义 HTML 模板渲染器

  1. import "html/template"
  2. func main() {
  3. router := gin.Default()
  4. html := template.Must(template.ParseFiles("file1", "file2"))
  5. router.SetHTMLTemplate(html)
  6. router.Run(":8080")
  7. }

自定义分隔符

可以自定义分隔符

  1. r := gin.Default()
  2. r.Delims("{[{", "}]}")
  3. r.LoadHTMLGlob("/path/to/templates"))

自定义模板函数

查看细节 example code.

main.go

  1. import (
  2. "fmt"
  3. "html/template"
  4. "net/http"
  5. "time"
  6. "github.com/gin-gonic/gin"
  7. )
  8. func formatAsDate(t time.Time) string {
  9. year, month, day := t.Date()
  10. return fmt.Sprintf("%d%02d/%02d", year, month, day)
  11. }
  12. func main() {
  13. router := gin.Default()
  14. router.Delims("{[{", "}]}")
  15. router.SetFuncMap(template.FuncMap{
  16. "formatAsDate": formatAsDate,
  17. })
  18. router.LoadHTMLFiles("./testdata/template/raw.tmpl")
  19. router.GET("/raw", func(c *gin.Context) {
  20. c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{
  21. "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
  22. })
  23. })
  24. router.Run(":8080")
  25. }

raw.tmpl

  1. Date: {[{.now | formatAsDate}]}

显示:

  1. Date: 2017/07/01

多模板

Multitemplate

Gin 默认情况下只允许使用一个模板文件. 点击 这里 看如何使用如 go 1.6 block template 来实现多模板渲染.

重定向

Redirects

发起一个 HTTP 重定向很容易,支持内部与外部链接。

  1. r.GET("/test", func(c *gin.Context) {
  2. c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
  3. })

发起一个路由重定向,使用 HandleContext

  1. r.GET("/test", func(c *gin.Context) {
  2. c.Request.URL.Path = "/test2"
  3. r.HandleContext(c)
  4. })
  5. r.GET("/test2", func(c *gin.Context) {
  6. c.JSON(200, gin.H{"hello": "world"})
  7. })

自定义中间件

Custom Middleware

  1. func Logger() gin.HandlerFunc {
  2. return func(c *gin.Context) {
  3. t := time.Now()
  4. // 设置变量example
  5. c.Set("example", "12345")
  6. // 请求之前
  7. c.Next()
  8. // 请求之后
  9. latency := time.Since(t)
  10. log.Print(latency)
  11. // 访问我们发送的状态
  12. status := c.Writer.Status()
  13. log.Println(status)
  14. }
  15. }
  16. func main() {
  17. r := gin.New()
  18. r.Use(Logger())
  19. r.GET("/test", func(c *gin.Context) {
  20. example := c.MustGet("example").(string)
  21. // it would print: "12345"
  22. log.Println(example)
  23. })
  24. // Listen and serve on 0.0.0.0:8080
  25. r.Run(":8080")
  26. }

使用 BasicAuth() 中间件

Using BasicAuth middleware

  1. // 模拟隐私数据
  2. var secrets = gin.H{
  3. "foo": gin.H{"email": "foo@bar.com", "phone": "123433"},
  4. "austin": gin.H{"email": "austin@example.com", "phone": "666"},
  5. "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},
  6. }
  7. func main() {
  8. r := gin.Default()
  9. // 下面分组使用 gin.BasicAuth() 中间件
  10. // gin.Accounts是map[string]string的快捷方法
  11. authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
  12. "foo": "bar",
  13. "austin": "1234",
  14. "lena": "hello2",
  15. "manu": "4321",
  16. }))
  17. // /admin/secrets 端点
  18. // 点击访问 "localhost:8080/admin/secrets
  19. authorized.GET("/secrets", func(c *gin.Context) {
  20. // 获取用户,由BasicAuth middleware代理设置
  21. user := c.MustGet(gin.AuthUserKey).(string)
  22. if secret, ok := secrets[user]; ok {
  23. c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
  24. } else {
  25. c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})
  26. }
  27. })
  28. // Listen and serve on 0.0.0.0:8080
  29. r.Run(":8080")
  30. }

中间件中的协程

Goroutines inside a middleware

在中间件或者处理器中开启协程时,不应使用原来的 context 上下文,只可以使用一个只读的副本。

  1. func main() {
  2. r := gin.Default()
  3. r.GET("/long_async", func(c *gin.Context) {
  4. // 创建副本用于协程之中
  5. cCp := c.Copy()
  6. go func() {
  7. // 假设一个运行5秒的任务
  8. time.Sleep(5 * time.Second)
  9. // 注意你在使用context的副本
  10. log.Println("Done! in path " + cCp.Request.URL.Path)
  11. }()
  12. })
  13. r.GET("/long_sync", func(c *gin.Context) {
  14. // 假设一个运行5秒的任务
  15. time.Sleep(5 * time.Second)
  16. // 不在协程中,可直接使用context
  17. log.Println("Done! in path " + c.Request.URL.Path)
  18. })
  19. // Listen and serve on 0.0.0.0:8080
  20. r.Run(":8080")
  21. }

自定义 HTTP 配置

Custom HTTP configuration

直接使用 http.ListenAndServe() 如下:

  1. func main() {
  2. router := gin.Default()
  3. http.ListenAndServe(":8080", router)
  4. }

或者

  1. func main() {
  2. router := gin.Default()
  3. s := &http.Server{
  4. Addr: ":8080",
  5. Handler: router,
  6. ReadTimeout: 10 * time.Second,
  7. WriteTimeout: 10 * time.Second,
  8. MaxHeaderBytes: 1 << 20,
  9. }
  10. s.ListenAndServe()
  11. }

Support Let’s Encrypt

example for 1-line LetsEncrypt HTTPS servers.

  1. package main
  2. import (
  3. "log"
  4. "github.com/gin-gonic/autotls"
  5. "github.com/gin-gonic/gin"
  6. )
  7. func main() {
  8. r := gin.Default()
  9. // Ping handler
  10. r.GET("/ping", func(c *gin.Context) {
  11. c.String(200, "pong")
  12. })
  13. log.Fatal(autotls.Run(r, "example1.com", "example2.com"))
  14. }

自定义 autocert 管理器的示例.

  1. package main
  2. import (
  3. "log"
  4. "github.com/gin-gonic/autotls"
  5. "github.com/gin-gonic/gin"
  6. "golang.org/x/crypto/acme/autocert"
  7. )
  8. func main() {
  9. r := gin.Default()
  10. // Ping handler
  11. r.GET("/ping", func(c *gin.Context) {
  12. c.String(200, "pong")
  13. })
  14. m := autocert.Manager{
  15. Prompt: autocert.AcceptTOS,
  16. HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),
  17. Cache: autocert.DirCache("/var/www/.cache"),
  18. }
  19. log.Fatal(autotls.RunWithManager(r, &m))
  20. }

使用 Gin 运行多服务

Run multiple service using Gin

请参阅 问题 并尝试以下示例:

  1. package main
  2. import (
  3. "log"
  4. "net/http"
  5. "time"
  6. "github.com/gin-gonic/gin"
  7. "golang.org/x/sync/errgroup"
  8. )
  9. var (
  10. g errgroup.Group
  11. )
  12. func router01() http.Handler {
  13. e := gin.New()
  14. e.Use(gin.Recovery())
  15. e.GET("/", func(c *gin.Context) {
  16. c.JSON(
  17. http.StatusOK,
  18. gin.H{
  19. "code": http.StatusOK,
  20. "error": "Welcome server 01",
  21. },
  22. )
  23. })
  24. return e
  25. }
  26. func router02() http.Handler {
  27. e := gin.New()
  28. e.Use(gin.Recovery())
  29. e.GET("/", func(c *gin.Context) {
  30. c.JSON(
  31. http.StatusOK,
  32. gin.H{
  33. "code": http.StatusOK,
  34. "error": "Welcome server 02",
  35. },
  36. )
  37. })
  38. return e
  39. }
  40. func main() {
  41. server01 := &http.Server{
  42. Addr: ":8080",
  43. Handler: router01(),
  44. ReadTimeout: 5 * time.Second,
  45. WriteTimeout: 10 * time.Second,
  46. }
  47. server02 := &http.Server{
  48. Addr: ":8081",
  49. Handler: router02(),
  50. ReadTimeout: 5 * time.Second,
  51. WriteTimeout: 10 * time.Second,
  52. }
  53. g.Go(func() error {
  54. return server01.ListenAndServe()
  55. })
  56. g.Go(func() error {
  57. return server02.ListenAndServe()
  58. })
  59. if err := g.Wait(); err != nil {
  60. log.Fatal(err)
  61. }
  62. }

优雅重启或停止

Graceful restart or stop

以下方式可以让你优雅的重启或停止你的 web 服务器。

我们可以用 fvbock/endless 取代默认的 ListenAndServe。 请参阅 问题 #296 获得更多细节.

  1. router := gin.Default()
  2. router.GET("/", handler)
  3. // [...]
  4. endless.ListenAndServe(":4242", router)

endless 的替代品:

  • manners: A polite Go HTTP server that shuts down gracefully.
  • graceful: Graceful is a Go package enabling graceful shutdown of an http.Handler server.
  • grace: Graceful restart & zero downtime deploy for Go servers.

如果你在使用 Go 1.8,你可能并不需要这个库。考虑使用 http.Server 的内建 Shutdown() 方法优雅关闭。 查看示例 graceful-shutdown.

  1. // +build go1.8
  2. package main
  3. import (
  4. "context"
  5. "log"
  6. "net/http"
  7. "os"
  8. "os/signal"
  9. "syscall"
  10. "time"
  11. "github.com/gin-gonic/gin"
  12. )
  13. func main() {
  14. router := gin.Default()
  15. router.GET("/", func(c *gin.Context) {
  16. time.Sleep(5 * time.Second)
  17. c.String(http.StatusOK, "Welcome Gin Server")
  18. })
  19. srv := &http.Server{
  20. Addr: ":8080",
  21. Handler: router,
  22. }
  23. go func() {
  24. // service connections
  25. if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
  26. log.Fatalf("listen: %s\n", err)
  27. }
  28. }()
  29. // Wait for interrupt signal to gracefully shutdown the server with
  30. // a timeout of 5 seconds.
  31. quit := make(chan os.Signal)
  32. // kill (no param) default send syscall.SIGTERM
  33. // kill -2 is syscall.SIGINT
  34. // kill -9 is syscall.SIGKILL but can't be catch, so don't need add it
  35. signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
  36. <-quit
  37. log.Println("Shutdown Server ...")
  38. ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  39. defer cancel()
  40. if err := srv.Shutdown(ctx); err != nil {
  41. log.Fatal("Server Shutdown:", err)
  42. }
  43. // catching ctx.Done(). timeout of 5 seconds.
  44. select {
  45. case <-ctx.Done():
  46. log.Println("timeout of 5 seconds.")
  47. }
  48. log.Println("Server exiting")
  49. }

将服务器构建为一个包含模板文件的二进制文件

Build a single binary with templates

可以通过使用 go-assets,将服务器构建为包含模板的单个二进制文件

  1. func main() {
  2. r := gin.New()
  3. t, err := loadTemplate()
  4. if err != nil {
  5. panic(err)
  6. }
  7. r.SetHTMLTemplate(t)
  8. r.GET("/", func(c *gin.Context) {
  9. c.HTML(http.StatusOK, "/html/index.tmpl",nil)
  10. })
  11. r.Run(":8080")
  12. }
  13. // loadTemplate loads templates embedded by go-assets-builder
  14. func loadTemplate() (*template.Template, error) {
  15. t := template.New("")
  16. for name, file := range Assets.Files {
  17. if file.IsDir() || !strings.HasSuffix(name, ".tmpl") {
  18. continue
  19. }
  20. h, err := ioutil.ReadAll(file)
  21. if err != nil {
  22. return nil, err
  23. }
  24. t, err = t.New(name).Parse(string(h))
  25. if err != nil {
  26. return nil, err
  27. }
  28. }
  29. return t, nil
  30. }

See a complete example in the https://github.com/gin-gonic/examples/tree/master/assets-in-binary directory.

使用自定义结构绑定表单数据

Bind form-data request with custom struct

以下使用自定义结构的示例:

  1. type StructA struct {
  2. FieldA string `form:"field_a"`
  3. }
  4. type StructB struct {
  5. NestedStruct StructA
  6. FieldB string `form:"field_b"`
  7. }
  8. type StructC struct {
  9. NestedStructPointer *StructA
  10. FieldC string `form:"field_c"`
  11. }
  12. type StructD struct {
  13. NestedAnonyStruct struct {
  14. FieldX string `form:"field_x"`
  15. }
  16. FieldD string `form:"field_d"`
  17. }
  18. func GetDataB(c *gin.Context) {
  19. var b StructB
  20. c.Bind(&b)
  21. c.JSON(200, gin.H{
  22. "a": b.NestedStruct,
  23. "b": b.FieldB,
  24. })
  25. }
  26. func GetDataC(c *gin.Context) {
  27. var b StructC
  28. c.Bind(&b)
  29. c.JSON(200, gin.H{
  30. "a": b.NestedStructPointer,
  31. "c": b.FieldC,
  32. })
  33. }
  34. func GetDataD(c *gin.Context) {
  35. var b StructD
  36. c.Bind(&b)
  37. c.JSON(200, gin.H{
  38. "x": b.NestedAnonyStruct,
  39. "d": b.FieldD,
  40. })
  41. }
  42. func main() {
  43. r := gin.Default()
  44. r.GET("/getb", GetDataB)
  45. r.GET("/getc", GetDataC)
  46. r.GET("/getd", GetDataD)
  47. r.Run()
  48. }

Using the command curl command result:

  1. $ curl "http://localhost:8080/getb?field_a=hello&field_b=world"
  2. {"a":{"FieldA":"hello"},"b":"world"}
  3. $ curl "http://localhost:8080/getc?field_a=hello&field_c=world"
  4. {"a":{"FieldA":"hello"},"c":"world"}
  5. $ curl "http://localhost:8080/getd?field_x=hello&field_d=world"
  6. {"d":"world","x":{"FieldX":"hello"}}

尝试将 body 绑定到不同的结构中

Try to bind body into different structs

The normal methods for binding request body consumes c.Request.Body and they cannot be called multiple times.

  1. type formA struct {
  2. Foo string `json:"foo" xml:"foo" binding:"required"`
  3. }
  4. type formB struct {
  5. Bar string `json:"bar" xml:"bar" binding:"required"`
  6. }
  7. func SomeHandler(c *gin.Context) {
  8. objA := formA{}
  9. objB := formB{}
  10. // This c.ShouldBind consumes c.Request.Body and it cannot be reused.
  11. if errA := c.ShouldBind(&objA); errA == nil {
  12. c.String(http.StatusOK, `the body should be formA`)
  13. // Always an error is occurred by this because c.Request.Body is EOF now.
  14. } else if errB := c.ShouldBind(&objB); errB == nil {
  15. c.String(http.StatusOK, `the body should be formB`)
  16. } else {
  17. ...
  18. }
  19. }

For this, you can use c.ShouldBindBodyWith.

  1. func SomeHandler(c *gin.Context) {
  2. objA := formA{}
  3. objB := formB{}
  4. // This reads c.Request.Body and stores the result into the context.
  5. if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil {
  6. c.String(http.StatusOK, `the body should be formA`)
  7. // At this time, it reuses body stored in the context.
  8. } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {
  9. c.String(http.StatusOK, `the body should be formB JSON`)
  10. // And it can accepts other formats
  11. } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {
  12. c.String(http.StatusOK, `the body should be formB XML`)
  13. } else {
  14. ...
  15. }
  16. }
  • c.ShouldBindBodyWith stores body into the context before binding. This has a slight impact to performance, so you should not use this method if you are enough to call binding at once.
  • This feature is only needed for some formats — JSON, XML, MsgPack, ProtoBuf. For other formats, Query, Form, FormPost, FormMultipart, can be called by c.ShouldBind() multiple times without any damage to performance (See #1341).

http2 server push

http2 server push

http.Pusher is supported only go1.8+. See the golang blog for detail information.

  1. package main
  2. import (
  3. "html/template"
  4. "log"
  5. "github.com/gin-gonic/gin"
  6. )
  7. var html = template.Must(template.New("https").Parse(`
  8. <html>
  9. <head>
  10. <title>Https Test</title>
  11. <script src="/assets/app.js"></script>
  12. </head>
  13. <body>
  14. <h1 style="color:red;">Welcome, Ginner!</h1>
  15. </body>
  16. </html>
  17. `))
  18. func main() {
  19. r := gin.Default()
  20. r.Static("/assets", "./assets")
  21. r.SetHTMLTemplate(html)
  22. r.GET("/", func(c *gin.Context) {
  23. if pusher := c.Writer.Pusher(); pusher != nil {
  24. // use pusher.Push() to do server push
  25. if err := pusher.Push("/assets/app.js", nil); err != nil {
  26. log.Printf("Failed to push: %v", err)
  27. }
  28. }
  29. c.HTML(200, "https", gin.H{
  30. "status": "success",
  31. })
  32. })
  33. // Listen and Server in https://127.0.0.1:8080
  34. r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")
  35. }

定义路由日志记录格式

Define format for the log of routes

默认路由日志格式如下:

  1. [GIN-debug] POST /foo --> main.main.func1 (3 handlers)
  2. [GIN-debug] GET /bar --> main.main.func2 (3 handlers)
  3. [GIN-debug] GET /status --> main.main.func3 (3 handlers)

如果你想以给定的格式记录日志(例如 JSON 的键值或其他数据),可以使用 gin.DebugPrintRputeFunc 定义格式。下面的例子,我们使用标准日志包记录所有路由, 但你也可以使用符合你需求的其他日志包。

  1. import (
  2. "log"
  3. "net/http"
  4. "github.com/gin-gonic/gin"
  5. )
  6. func main() {
  7. r := gin.Default()
  8. gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {
  9. log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers)
  10. }
  11. r.POST("/foo", func(c *gin.Context) {
  12. c.JSON(http.StatusOK, "foo")
  13. })
  14. r.GET("/bar", func(c *gin.Context) {
  15. c.JSON(http.StatusOK, "bar")
  16. })
  17. r.GET("/status", func(c *gin.Context) {
  18. c.JSON(http.StatusOK, "ok")
  19. })
  20. // Listen and Server in http://0.0.0.0:8080
  21. r.Run()
  22. }

Set and get a cookie

  1. import (
  2. "fmt"
  3. "github.com/gin-gonic/gin"
  4. )
  5. func main() {
  6. router := gin.Default()
  7. router.GET("/cookie", func(c *gin.Context) {
  8. cookie, err := c.Cookie("gin_cookie")
  9. if err != nil {
  10. cookie = "NotSet"
  11. c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)
  12. }
  13. fmt.Printf("Cookie value: %s \n", cookie)
  14. })
  15. router.Run()
  16. }

Testing

net/http/httptest包很适合用于HTTP测试。

  1. package main
  2. func setupRouter() *gin.Engine {
  3. r := gin.Default()
  4. r.GET("/ping", func(c *gin.Context) {
  5. c.String(200, "pong")
  6. })
  7. return r
  8. }
  9. func main() {
  10. r := setupRouter()
  11. r.Run(":8080")
  12. }

测试代码示例如下:

  1. package main
  2. import (
  3. "net/http"
  4. "net/http/httptest"
  5. "testing"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. func TestPingRoute(t *testing.T) {
  9. router := setupRouter()
  10. w := httptest.NewRecorder()
  11. req, _ := http.NewRequest("GET", "/ping", nil)
  12. router.ServeHTTP(w, req)
  13. assert.Equal(t, 200, w.Code)
  14. assert.Equal(t, "pong", w.Body.String())
  15. }

Users

Awesome project lists using Gin web framework.

  • drone: Drone is a Continuous Delivery platform built on Docker, written in Go.
  • gorush: A push notification server written in Go.
  • fnproject: The container native, cloud agnostic serverless platform.