首页
/ Gin 快速上手实战:从路由、中间件到绑定校验、响应渲染与服务器配置的完整指南

Gin 快速上手实战:从路由、中间件到绑定校验、响应渲染与服务器配置的完整指南

2026-09-04 21:37:50作者:田桥桑Industrious

本文以 Gin 官方快速上手文档 docs/doc.md 为主线,系统讲解 Gin 的构建标签、路由定义、中间件机制、请求绑定与校验、多格式响应渲染、服务器配置与 HTTP 测试等全部核心能力。文中每个知识点均结合当前仓库源码(gin.gocontext.gobinding/binding.gologger.gocodec/json/api.go)进行佐证,帮助你在掌握完整可运行示例的同时理解底层实现。

构建标签:可选的 JSON 引擎与可裁剪的 MsgPack

Gin 默认使用标准库 encoding/json,但提供了三个构建标签来切换 JSON 实现,仓库中 codec/json/ 目录下的 jsoniter.gogo_json.gosonic.go 分别对应不同引擎:

# jsoniter
go build -tags=jsoniter .

# go-json
go build -tags=go_json .

# sonic
go build -tags=sonic .

MsgPack 渲染功能默认开启,若不需要,可用 nomsgpack 标签关闭以减小二进制体积(从 binding/binding.go 顶部的 //go:build !nomsgpack 约束可以印证该裁剪机制):

go build -tags=nomsgpack .

当前 go.mod 声明 go 1.25.0,并同时依赖 json-iterator/gogoccy/go-jsonbytedance/sonic 三个 JSON 库,它们仅在对应构建标签激活时参与编译。仓库的 Makefile 中的 test 目标支持通过 TESTTAGS 变量携带构建标签跑测试,例如 make test TESTTAGS=-tags=jsoniter

路由:HTTP 方法、路径参数与查询参数

注册各类 HTTP 方法

gin.Default() 会创建带有 Logger 和 Recovery 中间件的引擎(对应 gin.goDefault() 函数内 engine.Use(Logger(), Recovery()) 的调用):

func main() {
  // Creates a gin router with default middleware:
  // logger and recovery (crash-free) middleware
  router := gin.Default()

  router.GET("/someGet", getting)
  router.POST("/somePost", posting)
  router.PUT("/somePut", putting)
  router.DELETE("/someDelete", deleting)
  router.PATCH("/somePatch", patching)
  router.HEAD("/someHead", head)
  router.OPTIONS("/someOptions", options)

  // By default, it serves on :8080 unless a
  // PORT environment variable was defined.
  router.Run()
  // router.Run(":3000") for a hard coded port
}

Run() 本质是 http.ListenAndServe(addr, router) 的快捷方式,且会阻塞调用方 goroutine(见 gin.go)。仓库还提供 RunTLSRunUnixRunFdRunQUICRunListener 等变体,分别对应 TLS、unix socket、文件描述符、QUIC 和自定义 net.Listener 场景。

路径参数

func main() {
  router := gin.Default()

  // This handler will match /user/john but will not match /user/ or /user
  router.GET("/user/:name", func(c *gin.Context) {
    name := c.Param("name")
    c.String(http.StatusOK, "Hello %s", name)
  })

  // However, this one will match /user/john/ and also /user/john/send
  // If no other routers match /user/john, it will redirect to /user/john/
  router.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)
  })

  // For each matched request Context will hold the route definition
  router.POST("/user/:name/*action", func(c *gin.Context) {
    b := c.FullPath() == "/user/:name/*action" // true
    c.String(http.StatusOK, "%t", b)
  })

  // This handler will add a new router for /user/groups.
  // Exact routes are resolved before param routes, regardless of the order they were defined.
  // Routes starting with /user/groups are never interpreted as /user/:name/... routes
  router.GET("/user/groups", func(c *gin.Context) {
    c.String(http.StatusOK, "The available groups are [...]")
  })

  router.Run(":8080")
}

三个要点值得注意:

  • :name 是单段参数,*action 是通配符参数,匹配剩余所有路径段;
  • c.FullPath() 返回当前请求命中的路由定义路径(而非请求路径),可用于在通配路由中区分实际匹配的模式;
  • 精确路由的优先级高于参数路由,且与注册顺序无关。从源码结构看,该行为由 Engine 内部按 HTTP 方法维护的路由树(gin.goaddRoute 将每个方法的路径挂到独立的 node 树)保证。

查询字符串参数

func main() {
  router := gin.Default()

  // Query string parameters are parsed using the existing underlying request object.
  // The request responds to a URL matching: /welcome?firstname=Jane&lastname=Doe
  router.GET("/welcome", func(c *gin.Context) {
    firstname := c.DefaultQuery("firstname", "Guest")
    lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")

    c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
  })
  router.Run(":8080")
}

Multipart/Urlencoded Form

func main() {
  router := gin.Default()

  router.POST("/form_post", func(c *gin.Context) {
    message := c.PostForm("message")
    nick := c.DefaultPostForm("nick", "anonymous")

    c.JSON(http.StatusOK, gin.H{
      "status":  "posted",
      "message": message,
      "nick":    nick,
    })
  })
  router.Run(":8080")
}

查询参数与 POST 表单可以组合使用,例如以下请求同时携带 query 与 body:

POST /post?id=1234&page=1 HTTP/1.1
Content-Type: application/x-www-form-urlencoded

name=manu&message=this_is_great
func main() {
  router := gin.Default()

  router.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)
  })
  router.Run(":8080")
}

输出:

id: 1234; page: 1; name: manu; message: this_is_great

当值本身就是映射时,可用 QueryMap / PostFormMap 一次取出:

POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1
Content-Type: application/x-www-form-urlencoded

names[first]=thinkerou&names[second]=tianou
func main() {
  router := gin.Default()

  router.POST("/post", func(c *gin.Context) {
    ids := c.QueryMap("ids")
    names := c.PostFormMap("names")

    fmt.Printf("ids: %v; names: %v", ids, names)
  })
  router.Run(":8080")
}

输出:

ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou]

文件上传

上传单个文件:

func main() {
  router := gin.Default()
  // Set a lower memory limit for multipart forms (default is 32 MiB)
  router.MaxMultipartMemory = 8 << 20  // 8 MiB
  router.POST("/upload", func(c *gin.Context) {
    // Single file
    file, _ := c.FormFile("file")
    log.Println(file.Filename)

    // Upload the file to specific dst.
    c.SaveUploadedFile(file, dst)

    c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
  })
  router.Run(":8080")
}

curl 验证:

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

安全提示file.Filename 不应被信任。文件名是客户端可选提供的,应用中应剥离其中的路径信息并遵循服务器文件系统规则后再使用。

MaxMultipartMemory 的默认值为 32 MiB,对应 gin.go 中的常量 defaultMultipartMemory = 32 << 20,它最终作为 http.Request.ParseMultipartForm 的内存上限参数。

多文件上传使用 c.MultipartForm() 直接获取整个表单(context.goFormFile 内部也依赖它):

func main() {
  router := gin.Default()
  // Set a lower memory limit for multipart forms (default is 32 MiB)
  router.MaxMultipartMemory = 8 << 20  // 8 MiB
  router.POST("/upload", func(c *gin.Context) {
    // Multipart form
    form, _ := c.MultipartForm()
    files := form.File["upload[]"]

    for _, file := range files {
      log.Println(file.Filename)

      // Upload the file to specific dst.
      c.SaveUploadedFile(file, dst)
    }
    c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
  })
  router.Run(":8080")
}
curl -X POST http://localhost:8080/upload \
  -F "upload[]=@/Users/appleboy/test1.zip" \
  -F "upload[]=@/Users/appleboy/test2.zip" \
  -H "Content-Type: multipart/form-data"

路由分组与重定向

分组用于组织 API 版本,本质是共享前缀与中间件的 RouterGroup

func main() {
  router := gin.Default()

  // Simple group: v1
  {
    v1 := router.Group("/v1")
    v1.POST("/login", loginEndpoint)
    v1.POST("/submit", submitEndpoint)
    v1.POST("/read", readEndpoint)
  }

  // Simple group: v2
  {
    v2 := router.Group("/v2")
    v2.POST("/login", loginEndpoint)
    v2.POST("/submit", submitEndpoint)
    v2.POST("/read", readEndpoint)
  }

  router.Run(":8080")
}

重定向支持内部与外部地址,包括从 POST 发起的重定向:

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

// Issuing a HTTP redirect from POST
r.POST("/test", func(c *gin.Context) {
  c.Redirect(http.StatusFound, "/foo")
})

还有一种「路由内跳转」:修改 c.Request.URL.Path 后调用 r.HandleContext(c) 重新进入路由匹配。源码中 HandleContext 会保存旧的 handler 链索引、重置 Context 后再次执行 handleHTTPRequest,注意不要在其中构造循环。

r.GET("/test", func(c *gin.Context) {
    c.Request.URL.Path = "/test2"
    r.HandleContext(c)
})
r.GET("/test2", func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{"hello": "world"})
})

中间件:全局、分组与自定义

空引擎 vs 默认引擎

gin.New() 返回不带任何中间件的引擎,gin.Default() 则在 New() 基础上附加 Logger 与 Recovery(gin.go)。从源码看,Engine 内嵌 RouterGroup,并通过 sync.Pool 复用 Contextgin.goServeHTTPengine.pool.Get()/engine.pool.Put(c)),这是 Gin 高性能的关键设计之一。

r := gin.New()      // 无默认中间件
r := gin.Default()  // 已附加 Logger 和 Recovery

组合使用中间件

func main() {
  // Creates a router without any middleware by default
  r := gin.New()

  // Global middleware
  // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.
  // By default gin.DefaultWriter = os.Stdout
  r.Use(gin.Logger())

  // Recovery middleware recovers from any panics and writes a 500 if there was one.
  r.Use(gin.Recovery())

  // Per route middleware, you can add as many as you desire.
  r.GET("/benchmark", MyBenchLogger(), benchEndpoint)

  // Authorization group
  authorized := r.Group("/")
  // per group middleware! in this case we use the custom created
  // AuthRequired() middleware just in the "authorized" group.
  authorized.Use(AuthRequired())
  {
    authorized.POST("/login", loginEndpoint)
    authorized.POST("/submit", submitEndpoint)
    authorized.POST("/read", readEndpoint)

    // nested group
    testing := authorized.Group("testing")
    // visit 0.0.0.0:8080/testing/analytics
    testing.GET("/analytics", analyticsEndpoint)
  }

  // Listen and serve on 0.0.0.0:8080
  r.Run(":8080")
}

中间件的作用范围分三级:全局(r.Use)、分组(group.Use,可嵌套)、单路由(注册时追加参数)。

编写自定义中间件

自定义中间件就是返回 gin.HandlerFunc 的工厂函数,c.Next() 之前是请求前置逻辑,之后是后置逻辑:

func Logger() gin.HandlerFunc {
  return func(c *gin.Context) {
    t := time.Now()

    // Set example variable
    c.Set("example", "12345")

    // before request
    c.Next()

    // after request
    latency := time.Since(t)
    log.Print(latency)

    // access the status we are sending
    status := c.Writer.Status()
    log.Println(status)
  }
}

func main() {
  r := gin.New()
  r.Use(Logger())

  r.GET("/test", func(c *gin.Context) {
    example := c.MustGet("example").(string)

    // it would print: "12345"
    log.Println(example)
  })

  // Listen and serve on 0.0.0.0:8080
  r.Run(":8080")
}

自定义 Recovery 行为

默认的 gin.Recovery() 恢复 panic 并返回 500;若需要落库、上报或自定义响应,可用 gin.CustomRecovery。源码中该函数位于 recovery.go,旁边还提供 CustomRecoveryWithWriter 用于把恢复日志写到独立输出流:

func main() {
  r := gin.New()
  r.Use(gin.Logger())

  // Recovery middleware recovers from any panics and writes a 500 if there was one.
  r.Use(gin.CustomRecovery(func(c *gin.Context, recovered any) {
    if err, ok := recovered.(string); ok {
      c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
    }
    c.AbortWithStatus(http.StatusInternalServerError)
  }))

  r.GET("/panic", func(c *gin.Context) {
    // panic with a string -- the custom middleware could save this to a database or report it to the user
    panic("foo")
  })

  r.GET("/", func(c *gin.Context) {
    c.String(http.StatusOK, "ohai")
  })

  r.Run(":8080")
}

BasicAuth 中间件

gin.BasicAuth(gin.Accounts{...}) 以分组方式挂载 HTTP Basic 认证,认证通过后中间件会把用户名写入 gin.AuthUserKey

// simulate some private data
var secrets = gin.H{
  "foo":    gin.H{"email": "foo@bar.com", "phone": "123433"},
  "austin": gin.H{"email": "austin@example.com", "phone": "666"},
  "lena":   gin.H{"email": "lena@guapa.com", "phone": "523443"},
}

func main() {
  r := gin.Default()

  // Group using gin.BasicAuth() middleware
  // gin.Accounts is a shortcut for map[string]string
  authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
    "foo":    "bar",
    "austin": "1234",
    "lena":   "hello2",
    "manu":   "4321",
  }))

  // /admin/secrets endpoint
  // hit "localhost:8080/admin/secrets"
  authorized.GET("/secrets", func(c *gin.Context) {
    // get user, it was set by the BasicAuth middleware
    user := c.MustGet(gin.AuthUserKey).(string)
    if secret, ok := secrets[user]; ok {
      c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
    } else {
      c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})
    }
  })

  r.Run(":8080")
}

Basic 认证的底层实现在 auth.go,可通过 auth_test.go 查看其行为验证。

在中间件中开启 Goroutine 的注意点

在 handler 或中间件里启动新 goroutine 时,不能直接使用原始 *gin.Context——请求结束后 Context 会被归还对象池并复用。必须先用 c.Copy() 创建只读副本(context.goCopy() 会复制一份新 Context):

func main() {
  r := gin.Default()

  r.GET("/long_async", func(c *gin.Context) {
    // create copy to be used inside the goroutine
    cCp := c.Copy()
    go func() {
      // simulate a long task with time.Sleep(). 5 seconds
      time.Sleep(5 * time.Second)

      // note that you are using the copied context "cCp", IMPORTANT
      log.Println("Done! in path " + cCp.Request.URL.Path)
    }()
  })

  r.GET("/long_sync", func(c *gin.Context) {
    // simulate a long task with time.Sleep(). 5 seconds
    time.Sleep(5 * time.Second)

    // since we are NOT using a goroutine, we do not have to copy the context
    log.Println("Done! in path " + c.Request.URL.Path)
  })

  r.Run(":8080")
}

日志:输出目标、格式与过滤

写日志到文件

func main() {
  // Disable Console Color, you don't need console color when writing the logs to file.
  gin.DisableConsoleColor()

  // Logging to a file.
  f, _ := os.Create("gin.log")
  gin.DefaultWriter = io.MultiWriter(f)

  // Use the following code if you need to write the logs to file and console at the same time.
  // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)

  router := gin.Default()
  router.GET("/ping", func(c *gin.Context) {
      c.String(http.StatusOK, "pong")
  })

  router.Run(":8080")
}

自定义日志格式

LoggerWithFormatter 接收一个 func(gin.LogFormatterParams) string。从源码 logger.go 可以看到,LogFormatterParams 提供了 RequestTimeStampStatusCodeLatencyClientIPMethodPathErrorMessageBodySizeKeys 等字段,格式化函数对输出有完全控制权:

func main() {
  router := gin.New()

  // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter
  // By default gin.DefaultWriter = os.Stdout
  router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {

    // your custom format
    return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
        param.ClientIP,
        param.TimeStamp.Format(time.RFC1123),
        param.Method,
        param.Path,
        param.Request.Proto,
        param.StatusCode,
        param.Latency,
        param.Request.UserAgent(),
        param.ErrorMessage,
    )
  }))
  router.Use(gin.Recovery())

  router.GET("/ping", func(c *gin.Context) {
    c.String(http.StatusOK, "pong")
  })

  router.Run(":8080")
}

示例输出:

::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" "

跳过特定日志

LoggerConfig 支持两种跳过策略:按路径(SkipPaths)和按自定义逻辑(Skip 函数),字段定义见 logger.go

func main() {
  router := gin.New()

  // skip logging for desired paths by setting SkipPaths in LoggerConfig
  loggerConfig := gin.LoggerConfig{SkipPaths: []string{"/metrics"}}

  // skip logging based on your logic by setting Skip func in LoggerConfig
  loggerConfig.Skip = func(c *gin.Context) bool {
      // as an example skip non server side errors
      return c.Writer.Status() < http.StatusInternalServerError
  }

  router.Use(gin.LoggerWithConfig(loggerConfig))
  router.Use(gin.Recovery())

  // skipped
  router.GET("/metrics", func(c *gin.Context) {
      c.Status(http.StatusNotImplemented)
  })

  // skipped
  router.GET("/ping", func(c *gin.Context) {
      c.String(http.StatusOK, "pong")
  })

  // not skipped
  router.GET("/data", func(c *gin.Context) {
    c.Status(http.StatusNotImplemented)
  })

  router.Run(":8080")
}

控制日志颜色

日志颜色默认依据终端 TTY 检测结果自动决定(源码中 consoleColorMode 有三个取值:autoColor / disableColor / forceColor,见 logger.go):

// 永不着色
func main() {
  gin.DisableConsoleColor()
  router := gin.Default()
  router.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") })
  router.Run(":8080")
}

// 强制着色
func main() {
  gin.ForceConsoleColor()
  router := gin.Default()
  router.GET("/ping", func(c *gin.Context) { c.String(http.StatusOK, "pong") })
  router.Run(":8080")
}

不记录查询字符串

当 API Key 等敏感信息放在 query 中时,可用 SkipQueryString/path?q=1 记录为 /path

func main() {
  router := gin.New()

  // SkipQueryString indicates that the logger should not log the query string.
  // For example, /path?q=1 will be logged as /path
  loggerConfig := gin.LoggerConfig{SkipQueryString: true}

  router.Use(gin.LoggerWithConfig(loggerConfig))
}

自定义路由注册日志格式

默认的路由注册日志形如:

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

如需 JSON 或其他格式,重写全局变量 gin.DebugPrintRouteFunc

import (
  "log"
  "net/http"

  "github.com/gin-gonic/gin"
)

func main() {
  r := gin.Default()
  gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {
    log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers)
  }

  r.POST("/foo", func(c *gin.Context) {
    c.JSON(http.StatusOK, "foo")
  })

  r.GET("/bar", func(c *gin.Context) {
    c.JSON(http.StatusOK, "bar")
  })

  r.GET("/status", func(c *gin.Context) {
    c.JSON(http.StatusOK, "ok")
  })

  // Listen and Server in http://0.0.0.0:8080
  r.Run()
}

请求绑定与校验

模型绑定与校验

Gin 支持 JSON、XML、YAML、TOML 和标准表单(foo=bar&boo=baz)的绑定,校验基于 go-playground/validator/v10binding/binding.goStructValidator 接口与默认实现 defaultValidator)。每个需要绑定的字段必须声明对应来源的 tag,例如从 JSON 绑定就要写 json:"fieldname"

Gin 提供两组绑定方法,语义不同:

类别 方法 行为
Must bind BindBindJSONBindXMLBindQueryBindYAMLBindHeaderBindTOML 底层是 MustBindWith;绑定失败时以 c.AbortWithError(400, err).SetType(ErrorTypeBind) 中止请求,状态码 400、Content-Typetext/plain; charset=utf-8。此后强行改状态码会触发警告 [GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422
Should bind ShouldBindShouldBindJSONShouldBindXMLShouldBindQueryShouldBindYAMLShouldBindHeaderShouldBindTOML 底层是 ShouldBindWith;绑定失败时错误被返回,由开发者自行处理

Bind/ShouldBind 会根据 Content-Type 头自动推断绑定器,其推断逻辑正是 binding/binding.go 中的 Default(method, contentType) 函数:GET 一律走 Form,POST 按 MIME 分发到 JSON/XML/YAML/TOML/ProtoBuf/MsgPack/BSON 等。若明确知道格式,直接用 MustBindWithShouldBindWith 指定绑定器。

字段加 binding:"required" 后为空即报错:

// Binding from JSON
type Login struct {
  User     string `form:"user" json:"user" xml:"user" binding:"required"`
  Password string `form:"password" json:"password" xml:"password" binding:"required"`
}

func main() {
  router := gin.Default()

  // Example for binding JSON ({"user": "manu", "password": "123"})
  router.POST("/loginJSON", func(c *gin.Context) {
    var json Login
    if err := c.ShouldBindJSON(&json); err != nil {
      c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
      return
    }

    if json.User != "manu" || json.Password != "123" {
      c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
      return
    }

    c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
  })

  // Example for binding XML (
  //  <?xml version="1.0" encoding="UTF-8"?>
  //  <root>
  //    <user>manu</user>
  //    <password>123</password>
  //  </root>)
  router.POST("/loginXML", func(c *gin.Context) {
    var xml Login
    if err := c.ShouldBindXML(&xml); err != nil {
      c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
      return
    }

    if xml.User != "manu" || xml.Password != "123" {
      c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
      return
    }

    c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
  })

  // Example for binding a HTML form (user=manu&password=123)
  router.POST("/loginForm", func(c *gin.Context) {
    var form Login
    // This will infer what binder to use depending on the content-type header.
    if err := c.ShouldBind(&form); err != nil {
      c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
      return
    }

    if form.User != "manu" || form.Password != "123" {
      c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
      return
    }

    c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
  })

  router.Run(":8080")
}

示例请求(缺少 password,触发 required 校验失败):

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

跳过校验:把 Password 的 tag 改为 binding:"-" 即可不再对其校验。

注册自定义校验器

通过 binding.Validator.Engine() 取得 validator 实例并注册自定义规则。gtfield=CheckIn 这类字段间比较、time_format 解析时间类型的能力均来自 validator v10:

package main

import (
  "net/http"
  "time"

  "github.com/gin-gonic/gin"
  "github.com/gin-gonic/gin/binding"
  "github.com/go-playground/validator/v10"
)

// Booking contains binded and validated data.
type Booking struct {
  CheckIn  time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`
  CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`
}

var bookableDate validator.Func = func(fl validator.FieldLevel) bool {
  date, ok := fl.Field().Interface().(time.Time)
  if ok {
    today := time.Now()
    if today.After(date) {
      return false
    }
  }
  return true
}

func main() {
  route := gin.Default()

  if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
    v.RegisterValidation("bookabledate", bookableDate)
  }

  route.GET("/bookable", getBookable)
  route.Run(":8085")
}

func getBookable(c *gin.Context) {
  var b Booking
  if err := c.ShouldBindWith(&b, binding.Query); err == nil {
    c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
  } else {
    c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  }
}
$ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17"
{"message":"Booking dates are valid!"}

$ curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09"
{"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"}

$ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10"
{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}

仅绑定 Query String

ShouldBindQuery 只读取 query 参数,忽略 POST body:

package main

import (
  "log"
  "net/http"

  "github.com/gin-gonic/gin"
)

type Person struct {
  Name    string `form:"name"`
  Address string `form:"address"`
}

func main() {
  route := gin.Default()
  route.Any("/testing", startPage)
  route.Run(":8085")
}

func startPage(c *gin.Context) {
  var person Person
  if c.ShouldBindQuery(&person) == nil {
    log.Println("====== Only Bind By Query String ======")
    log.Println(person.Name)
    log.Println(person.Address)
  }
  c.String(http.StatusOK, "Success")
}

绑定 Query 或 POST 数据(含时间格式)

ShouldBind 在 GET 请求下只使用 query 绑定,POST 下先按 Content-Type 判断 JSON/XML,否则回退到表单。时间字段可用 time_format tag 指定解析格式:

package main

import (
  "log"
  "net/http"
  "time"

  "github.com/gin-gonic/gin"
)

type Person struct {
  Name       string    `form:"name"`
  Address    string    `form:"address"`
  Birthday   time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`
  CreateTime time.Time `form:"createTime" time_format:"unixNano"`
  UnixTime   time.Time `form:"unixTime" time_format:"unix"`
  UnixMilliTime   time.Time `form:"unixMilliTime" time_format:"unixmilli"`
  UnixMicroTime   time.Time `form:"unixMicroTime" time_format:"uNiXmIcRo"` // case does not matter for "unix*" time formats
}

func main() {
  route := gin.Default()
  route.GET("/testing", startPage)
  route.Run(":8085")
}

func startPage(c *gin.Context) {
  var person Person
  // If `GET`, only `Form` binding engine (`query`) used.
  // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).
  if c.ShouldBind(&person) == nil {
    log.Println(person.Name)
    log.Println(person.Address)
    log.Println(person.Birthday)
    log.Println(person.CreateTime)
    log.Println(person.UnixTime)
    log.Println(person.UnixMilliTime)
    log.Println(person.UnixMicroTime)
  }

  c.String(http.StatusOK, "Success")
}
curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033&unixMilliTime=1562400033001&unixMicroTime=1562400033000012"

未提供时绑定默认值

form tag 中用 default= 指定缺省值:

package main

import (
  "net/http"

  "github.com/gin-gonic/gin"
)

type Person struct {
  Name      string    `form:"name,default=William"`
  Age       int       `form:"age,default=10"`
  Friends   []string  `form:"friends,default=Will;Bill"`
  Addresses [2]string `form:"addresses,default=foo bar" collection_format:"ssv"`
  LapTimes  []int     `form:"lap_times,default=1;2;3" collection_format:"csv"`
}

func main() {
  g := gin.Default()
  g.POST("/person", func(c *gin.Context) {
    var req Person
    if err := c.ShouldBindQuery(&req); err != nil {
      c.JSON(http.StatusBadRequest, err)
      return
    }
    c.JSON(http.StatusOK, req)
  })
  _ = g.Run("localhost:8080")
}
curl -X POST http://localhost:8080/person
{"Name":"William","Age":10,"Friends":["Will","Bill"],"Colors":["red","blue"],"LapTimes":[1,2,3]}

注意默认集合值的分隔规则:tag 选项以逗号分隔,因此默认值中不能用逗号multicsv 格式需用分号分隔默认值,分号本身则不能出现在默认值内。

数组的集合格式

Format 说明 示例
multi (默认) 多个参数实例而非单个多值参数 key=foo&key=bar&key=baz
csv 逗号分隔值 foo,bar,baz
ssv 空格分隔值 foo bar baz
tsv 制表符分隔值 "foo\tbar\tbaz"
pipes 竖线分隔值 foo|bar|baz
package main

import (
  "log"
  "time"
  "github.com/gin-gonic/gin"
)

type Person struct {
  Name       string    `form:"name"`
  Addresses  []string  `form:"addresses" collection_format:"csv"`
  Birthday   time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`
  CreateTime time.Time `form:"createTime" time_format:"unixNano"`
  UnixTime   time.Time `form:"unixTime" time_format:"unix"`
}

func main() {
  route := gin.Default()
  route.GET("/testing", startPage)
  route.Run(":8085")
}
func startPage(c *gin.Context) {
  var person Person
  // If `GET`, only `Form` binding engine (`query`) used.
  // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).
  if c.ShouldBind(&person) == nil {
    log.Println(person.Name)
    log.Println(person.Addresses)
    log.Println(person.Birthday)
    log.Println(person.CreateTime)
    log.Println(person.UnixTime)
  }
  c.String(200, "Success")
}
curl -X GET "localhost:8085/testing?name=appleboy&addresses=foo,bar&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"

绑定 URI 参数

路径参数可通过 uri tag 绑定到结构体并参与校验(如 uuid):

package main

import (
  "net/http"

  "github.com/gin-gonic/gin"
)

type Person struct {
  ID string `uri:"id" binding:"required,uuid"`
  Name string `uri:"name" binding:"required"`
}

func main() {
  route := gin.Default()
  route.GET("/:name/:id", func(c *gin.Context) {
    var person Person
    if err := c.ShouldBindUri(&person); err != nil {
      c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})
      return
    }
    c.JSON(http.StatusOK, gin.H{"name": person.Name, "uuid": person.ID})
  })
  route.Run(":8088")
}
curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3
curl -v localhost:8088/thinkerou/not-uuid

绑定自定义 Unmarshaler

方式一:实现标准库 encoding.TextUnmarshaler,并在 uri/form tag 中加 parser=encoding.TextUnmarshaler

package main

import (
  "encoding"
  "strings"

  "github.com/gin-gonic/gin"
)

type Birthday string

func (b *Birthday) UnmarshalText(text []byte) error {
  *b = Birthday(strings.Replace(string(text), "-", "/", -1))
  return nil
}

var _ encoding.TextUnmarshaler = (*Birthday)(nil) //assert Birthday implements encoding.TextUnmarshaler

func main() {
  route := gin.Default()
  var request struct {
    Birthday         Birthday   `form:"birthday,parser=encoding.TextUnmarshaler"`
    Birthdays        []Birthday `form:"birthdays,parser=encoding.TextUnmarshaler" collection_format:"csv"`
    BirthdaysDefault []Birthday `form:"birthdaysDef,default=2020-09-01;2020-09-02,parser=encoding.TextUnmarshaler" collection_format:"csv"`
  }
  route.GET("/test", func(ctx *gin.Context) {
    _ = ctx.BindQuery(&request)
    ctx.JSON(200, request)
  })
  _ = route.Run(":8088")
}
curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02'

结果:

{"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]}

规则:若类型未实现该接口,parser 指定会被忽略;若 UnmarshalText 返回错误,Gin 会终止绑定并把错误返回给客户端。

方式二:实现 Gin 专有的 binding.BindUnmarshaler 接口(即实现 UnmarshalParam(param string) error),此时无需 parser tag:

package main

import (
  "strings"

  "github.com/gin-gonic/gin"
  "github.com/gin-gonic/gin/binding"
)

type Birthday string

func (b *Birthday) UnmarshalParam(param string) error {
  *b = Birthday(strings.Replace(param, "-", "/", -1))
  return nil
}

var _ binding.BindUnmarshaler = (*Birthday)(nil) //assert Birthday implements binding.BindUnmarshaler

func main() {
  route := gin.Default()
  var request struct {
    Birthday         Birthday   `form:"birthday"`
    Birthdays        []Birthday `form:"birthdays" collection_format:"csv"`
    BirthdaysDefault []Birthday `form:"birthdaysDef,default=2020-09-01;2020-09-02" collection_format:"csv"`
  }
  route.GET("/test", func(ctx *gin.Context) {
    _ = ctx.BindQuery(&request)
    ctx.JSON(200, request)
  })
  _ = route.Run(":8088")
}

优先级说明:若类型同时实现两个接口,Gin 默认使用 BindUnmarshaler,除非显式指定 parser=encoding.TextUnmarshalerUnmarshalParam 返回错误时同样终止绑定。

绑定 Header

package main

import (
  "fmt"
  "net/http"

  "github.com/gin-gonic/gin"
)

type testHeader struct {
  Rate   int    `header:"Rate"`
  Domain string `header:"Domain"`
}

func main() {
  r := gin.Default()
  r.GET("/", func(c *gin.Context) {
    h := testHeader{}

    if err := c.ShouldBindHeader(&h); err != nil {
      c.JSON(http.StatusOK, err)
    }

    fmt.Printf("%#v\n", h)
    c.JSON(http.StatusOK, gin.H{"Rate": h.Rate, "Domain": h.Domain})
  })

  r.Run()

  // client
  // curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/
  // output
  // {"Domain":"music","Rate":300}
}

绑定 HTML 复选框

表单中多个同名 checkbox 输入绑定到切片,注意 form tag 使用 colors[]

type myForm struct {
    Colors []string `form:"colors[]"`
}

func formHandler(c *gin.Context) {
    var fakeForm myForm
    c.ShouldBind(&fakeForm)
    c.JSON(http.StatusOK, gin.H{"color": fakeForm.Colors})
}
<form action="/" method="POST">
  <p>Check some colors</p>
  <label for="red">Red</label>
  <input type="checkbox" name="colors[]" value="red" id="red" />
  <label for="green">Green</label>
  <input type="checkbox" name="colors[]" value="green" id="green" />
  <label for="blue">Blue</label>
  <input type="checkbox" name="colors[]" value="blue" id="blue" />
  <input type="submit" />
</form>

结果:

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

Multipart/Urlencoded 绑定到含文件字段的结构体

multipart.FileHeader 类型字段可直接参与表单绑定,实现「文件 + 字段」一次绑定:

type ProfileForm struct {
  Name   string                `form:"name" binding:"required"`
  Avatar *multipart.FileHeader `form:"avatar" binding:"required"`

  // or for multiple files
  // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"`
}

func main() {
  router := gin.Default()
  router.POST("/profile", func(c *gin.Context) {
    // you can bind multipart form with explicit binding declaration:
    // c.ShouldBindWith(&form, binding.Form)
    // or you can simply use autobinding with ShouldBind method:
    var form ProfileForm
    // in this case proper binding will be automatically selected
    if err := c.ShouldBind(&form); err != nil {
      c.String(http.StatusBadRequest, "bad request")
      return
    }

    err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename)
    if err != nil {
      c.String(http.StatusInternalServerError, "unknown error")
      return
    }

    // db.Save(&form)

    c.String(http.StatusOK, "ok")
  })
  router.Run(":8080")
}
curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile

绑定嵌套结构体

Gin 支持嵌套 struct、指针字段与匿名结构体的 form 绑定:

type StructA struct {
    FieldA string `form:"field_a"`
}

type StructB struct {
    NestedStruct StructA
    FieldB string `form:"field_b"`
}

type StructC struct {
    NestedStructPointer *StructA
    FieldC string `form:"field_c"`
}

type StructD struct {
    NestedAnonyStruct struct {
        FieldX string `form:"field_x"`
    }
    FieldD string `form:"field_d"`
}

func GetDataB(c *gin.Context) {
    var b StructB
    c.Bind(&b)
    c.JSON(http.StatusOK, gin.H{
        "a": b.NestedStruct,
        "b": b.FieldB,
    })
}

func GetDataC(c *gin.Context) {
    var b StructC
    c.Bind(&b)
    c.JSON(http.StatusOK, gin.H{
        "a": b.NestedStructPointer,
        "c": b.FieldC,
    })
}

func GetDataD(c *gin.Context) {
    var b StructD
    c.Bind(&b)
    c.JSON(http.StatusOK, gin.H{
        "x": b.NestedAnonyStruct,
        "d": b.FieldD,
    })
}

func main() {
    r := gin.Default()
    r.GET("/getb", GetDataB)
    r.GET("/getc", GetDataC)
    r.GET("/getd", GetDataD)

    r.Run()
}
$ curl "http://localhost:8080/getb?field_a=hello&field_b=world"
{"a":{"FieldA":"hello"},"b":"world"}
$ curl "http://localhost:8080/getc?field_a=hello&field_c=world"
{"a":{"FieldA":"hello"},"c":"world"}
$ curl "http://localhost:8080/getd?field_x=hello&field_d=world"
{"d":"world","x":{"FieldX":"hello"}}

将同一 Body 绑定到不同结构体

c.Request.Body 是流,普通绑定方法消费后无法复用(第二次调用必然遇到 EOF)。解决方案是 c.ShouldBindBodyWith——它先把 body 读入 Context 缓存再绑定,并可用不同格式反复尝试:

type formA struct {
  Foo string `json:"foo" xml:"foo" binding:"required"`
}

type formB struct {
  Bar string `json:"bar" xml:"bar" binding:"required"`
}

func SomeHandler(c *gin.Context) {
  objA := formA{}
  objB := formB{}
  // This reads c.Request.Body and stores the result into the context.
  if errA := c.ShouldBindBodyWith(&objA, binding.Form); errA == nil {
    c.String(http.StatusOK, `the body should be formA`)
  // At this time, it reuses body stored in the context.
  } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {
    c.String(http.StatusOK, `the body should be formB JSON`)
  // And it can accepts other formats
  } else if errB2 := c.ShouldBindBodyWithXML(&objB); errB2 == nil {
    c.String(http.StatusOK, `the body should be formB XML`)
  } else {
    ...
  }
}

要点(源码中 context.goShouldBindBodyWith 会先调用 c.Request.GetBody 逻辑缓存 body):

  1. 该方法把 body 存入 context,存在轻微性能开销,能一次绑定时不要使用;
  2. 只有需要重复/多格式解析的 body 类格式(JSONXMLMsgPackProtoBuf)才需要它;QueryFormFormPostFormMultipart 可多次调用 c.ShouldBind() 而无性能损失。

还有快捷方法:ShouldBindBodyWithJSONShouldBindBodyWithXMLShouldBindBodyWithYAMLShouldBindBodyWithTOML

自定义 tag 的自定义绑定器

对无法修改 tag 的外部类型(例如只有 url tag 的结构体),可自定义 binding.Binding 实现,用 binding.MapFormWithTag 指定 tag 名,最后统一走 binding.Validator 校验:

const (
  customerTag = "url"
  defaultMemory = 32 << 20
)

type customerBinding struct {}

func (customerBinding) Name() string {
  return "form"
}

func (customerBinding) Bind(req *http.Request, obj any) error {
  if err := req.ParseForm(); err != nil {
    return err
  }
  if err := req.ParseMultipartForm(defaultMemory); err != nil {
    if err != http.ErrNotMultipart {
      return err
    }
  }
  if err := binding.MapFormWithTag(obj, req.Form, customerTag); err != nil {
    return err
  }
  return validate(obj)
}

func validate(obj any) error {
  if binding.Validator == nil {
    return nil
  }
  return binding.Validator.ValidateStruct(obj)
}

// Now we can do this!!!
// FormA is an external type that we can't modify it's tag
type FormA struct {
  FieldA string `url:"field_a"`
}

func ListHandler(s *Service) func(ctx *gin.Context) {
  return func(ctx *gin.Context) {
    var urlBinding = customerBinding{}
    var opt FormA
    err := ctx.MustBindWith(&opt, urlBinding)
    if err != nil {
      ...
    }
    ...
  }
}

自定义绑定器需实现 Name()Bind(*http.Request, any) 两个方法,接口定义见 binding/binding.go

响应渲染

JSON、XML、YAML、TOML 与 ProtoBuf

gin.Hmap[string]any 的别名;结构体字段遵循 json tag 重命名:

func main() {
  r := gin.Default()

  // gin.H is a shortcut for map[string]any
  r.GET("/someJSON", func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  })

  r.GET("/moreJSON", func(c *gin.Context) {
    // You can also use a struct
    var msg struct {
      Name    string `json:"user"`
      Message string
      Number  int
    }
    msg.Name = "Lena"
    msg.Message = "hey"
    msg.Number = 123
    // Note that msg.Name becomes "user" in the JSON
    // Will output  :   {"user": "Lena", "Message": "hey", "Number": 123}
    c.JSON(http.StatusOK, msg)
  })

  r.GET("/someXML", func(c *gin.Context) {
    c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  })

  r.GET("/someYAML", func(c *gin.Context) {
    c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  })

  r.GET("/someTOML", func(c *gin.Context) {
    c.TOML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
  })

  r.GET("/someProtoBuf", func(c *gin.Context) {
    reps := []int64{int64(1), int64(2)}
    label := "test"
    // The specific definition of protobuf is written in the testdata/protoexample file.
    data := &protoexample.Test{
      Label: &label,
      Reps:  reps,
    }
    // Note that data becomes binary data in the response
    // Will output protoexample.Test protobuf serialized data
    c.ProtoBuf(http.StatusOK, data)
  })

  r.Run(":8080")
}

示例中的 protobuf 消息定义参见 testdata/protoexample/ 目录下的 test.prototest.pb.go

SecureJSON

SecureJSON 防止 JSON 劫持:若数据是数组,自动在响应体前加前缀,默认为 while(1);(对应 gin.gosecureJSONPrefix: "while(1);" 的初始化值),可用 r.SecureJsonPrefix(")]}',\n") 覆盖:

func main() {
  r := gin.Default()

  // You can also use your own secure json prefix
  // r.SecureJsonPrefix(")]}',\n")

  r.GET("/someJSON", func(c *gin.Context) {
    names := []string{"lena", "austin", "foo"}

    // Will output  :   while(1);["lena","austin","foo"]
    c.SecureJSON(http.StatusOK, names)
  })

  r.Run(":8080")
}

JSONP

请求带 callback 查询参数时,响应体自动包裹为 callback(...)

func main() {
  r := gin.Default()

  r.GET("/JSONP", func(c *gin.Context) {
    data := gin.H{
      "foo": "bar",
    }

    //callback is x
    // Will output  :   x({\"foo\":\"bar\"})
    c.JSONP(http.StatusOK, data)
  })

  r.Run(":8080")

  // client
  // curl http://127.0.0.1:8080/JSONP?callback=x
}

AsciiJSON

只输出 ASCII 字符,非 ASCII 内容统一转义:

func main() {
  r := gin.Default()

  r.GET("/someJSON", func(c *gin.Context) {
    data := gin.H{
      "lang": "GO语言",
      "tag":  "<br>",
    }

    // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}
    c.AsciiJSON(http.StatusOK, data)
  })

  r.Run(":8080")
}

PureJSON

默认 c.JSON 会把 <>& 等 HTML 敏感字符转义为 Unicode 实体(如 <\u003c);c.PureJSON 则原样输出这些字符,适合响应中确实需要保留字面字符的场景:

func main() {
  r := gin.Default()

  // Serves unicode entities
  r.GET("/json", func(c *gin.Context) {
    c.JSON(http.StatusOK, gin.H{
      "html": "<b>Hello, world!</b>",
    })
  })

  // Serves literal characters
  r.GET("/purejson", func(c *gin.Context) {
    c.PureJSON(http.StatusOK, gin.H{
      "html": "<b>Hello, world!</b>",
    })
  })

  r.Run(":8080")
}

静态文件、文件数据与 Reader 数据

func main() {
  router := gin.Default()
  router.Static("/assets", "./assets")
  router.StaticFS("/more_static", http.Dir("my_file_system"))
  router.StaticFile("/favicon.ico", "./resources/favicon.ico")
  router.StaticFileFS("/more_favicon.ico", "more_favicon.ico", http.Dir("my_file_system"))

  // Listen and serve on 0.0.0.0:8080
  router.Run(":8080")
}

返回本地文件与文件系统文件:

func main() {
  router := gin.Default()

  router.GET("/local/file", func(c *gin.Context) {
    c.File("local/file.go")
  })

  var fs http.FileSystem = // ...
  router.GET("/fs/file", func(c *gin.Context) {
    c.FileFromFS("fs/file.go", fs)
  })
}

从 reader 流式输出(例如代理上游响应),可附带额外头:

func main() {
  router := gin.Default()
  router.GET("/someDataFromReader", func(c *gin.Context) {
    response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")
    if err != nil || response.StatusCode != http.StatusOK {
      c.Status(http.StatusServiceUnavailable)
      return
    }

    reader := response.Body
    defer reader.Close()
    contentLength := response.ContentLength
    contentType := response.Header.Get("Content-Type")

    extraHeaders := map[string]string{
      "Content-Disposition": `attachment; filename="gopher.png"`,
    }

    c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)
  })
  router.Run(":8080")
}

HTML 渲染

LoadHTMLGlob() / LoadHTMLFiles() / LoadHTMLFS() 加载模板;调试模式下这些方法使用 render.HTMLDebug(每次渲染重新解析),生产模式用 render.HTMLProduction(解析一次),切换逻辑见 gin.go

//go:embed templates/*
var templates embed.FS

func main() {
  router := gin.Default()
  router.LoadHTMLGlob("templates/*")
  //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
  //router.LoadHTMLFS(http.Dir("templates"), "template1.html", "template2.html")
  //or
  //router.LoadHTMLFS(http.FS(templates), "templates/template1.html", "templates/template2.html")
  router.GET("/index", func(c *gin.Context) {
    c.HTML(http.StatusOK, "index.tmpl", gin.H{
      "title": "Main website",
    })
  })
  router.Run(":8080")
}

templates/index.tmpl

<html>
  <h1>{{ .title }}</h1>
</html>

同名模板在不同目录:用 ** 通配加载,并用 define 显式命名模板:

func main() {
  router := gin.Default()
  router.LoadHTMLGlob("templates/**/*")
  router.GET("/posts/index", func(c *gin.Context) {
    c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
      "title": "Posts",
    })
  })
  router.GET("/users/index", func(c *gin.Context) {
    c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
      "title": "Users",
    })
  })
  router.Run(":8080")
}
{{ define "posts/index.tmpl" }}
<html>
  <h1>{{ .title }}</h1>
  <p>Using posts/index.tmpl</p>
</html>
{{ end }}
{{ define "users/index.tmpl" }}
<html>
  <h1>{{ .title }}</h1>
  <p>Using users/index.tmpl</p>
</html>
{{ end }}

自定义渲染器:直接传入自己解析好的 *template.Template

import "html/template"

func main() {
  router := gin.Default()
  html := template.Must(template.ParseFiles("file1", "file2"))
  router.SetHTMLTemplate(html)
  router.Run(":8080")
}

自定义定界符(注意:Delims 必须在加载模板之前调用):

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

自定义模板函数:通过 SetFuncMap 注入模板可用的函数。仓库自带测试模板 testdata/template/raw.tmpl,可直接用于本地验证:

import (
  "fmt"
  "html/template"
  "net/http"
  "time"

  "github.com/gin-gonic/gin"
)

func formatAsDate(t time.Time) string {
  year, month, day := t.Date()
  return fmt.Sprintf("%d/%02d/%02d", year, month, day)
}

func main() {
  router := gin.Default()
  router.Delims("{[{", "}]}")
  router.SetFuncMap(template.FuncMap{
      "formatAsDate": formatAsDate,
  })
  router.LoadHTMLFiles("./testdata/template/raw.tmpl")

  router.GET("/raw", func(c *gin.Context) {
      c.HTML(http.StatusOK, "raw.tmpl", gin.H{
          "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
      })
  })

  router.Run(":8080")
}
Date: {[{.now | formatAsDate}]}

输出:

Date: 2017/07/01

多模板与单二进制打包

Gin 默认只允许一个 html.Template 渲染器;需要 block template 等更高级能力时,可考虑社区的 gin-contrib/multitemplate 渲染器。

用标准库 embed 可把模板与静态资源打进单个二进制文件:

package main

import (
  "embed"
  "html/template"
  "net/http"

  "github.com/gin-gonic/gin"
)

//go:embed assets/* templates/*
var f embed.FS

func main() {
  router := gin.Default()
  templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl"))
  router.SetHTMLTemplate(templ)

  // example: /public/assets/images/example.png
  router.StaticFS("/public", http.FS(f))

  router.GET("/", func(c *gin.Context) {
    c.HTML(http.StatusOK, "index.tmpl", gin.H{
      "title": "Main website",
    })
  })

  router.GET("/foo", func(c *gin.Context) {
    c.HTML(http.StatusOK, "bar.tmpl", gin.H{
      "title": "Foo website",
    })
  })

  router.GET("favicon.ico", func(c *gin.Context) {
    file, _ := f.ReadFile("assets/favicon.ico")
    c.Data(
      http.StatusOK,
      "image/x-icon",
      file,
    )
  })

  router.Run(":8080")
}

服务器配置

自定义 HTTP 配置

gin.Engine 本身实现了 http.Handler,因此可以直接交给 http.ListenAndServe 或自定义 http.Server,从而获得超时、最大 header 等控制:

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

  s := &http.Server{
    Addr:           ":8080",
    Handler:        router,
    ReadTimeout:    10 * time.Second,
    WriteTimeout:   10 * time.Second,
    MaxHeaderBytes: 1 << 20,
  }
  s.ListenAndServe()
}

运行时替换 JSON codec(无需编译标签)

不想用构建标签时,Gin 支持在运行时替换 JSON 编解码实现:实现 json.Core 接口,然后给全局变量 json.API 赋值即可。该接口定义于 codec/json/api.go

package main

import (
  "io"

  "github.com/gin-gonic/gin"
  "github.com/gin-gonic/gin/codec/json"
  jsoniter "github.com/json-iterator/go"
)

var customConfig = jsoniter.Config{
  EscapeHTML:             true,
  SortMapKeys:            true,
  ValidateJsonRawMessage: true,
}.Froze()

// implement api.JsonApi
type customJsonApi struct {
}

func (j customJsonApi) Marshal(v any) ([]byte, error) {
  return customConfig.Marshal(v)
}

func (j customJsonApi) Unmarshal(data []byte, v any) error {
  return customConfig.Unmarshal(data, v)
}

func (j customJsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {
  return customConfig.MarshalIndent(v, prefix, indent)
}

func (j customJsonApi) NewEncoder(writer io.Writer) json.Encoder {
  return customConfig.NewEncoder(writer)
}

func (j customJsonApi) NewDecoder(reader io.Reader) json.Decoder {
  return customConfig.NewDecoder(reader)
}

func main() {
  //Replace the default json api
  json.API = customJsonApi{}

  //Start your gin engine
  router := gin.Default()
  router.Run(":8080")
}

Encoder 需支持 SetEscapeHTML/EncodeDecoder 需支持 UseNumber/DisallowUnknownFields/Decode(见 codec/json/api.go)。仓库自带的 go_json.gojsoniter.gosonic.go 就是该接口的参考实现。

支持 Let's Encrypt

一行代码即可启动自动 HTTPS(gin-gonic/autotls 封装了 autocert):

package main

import (
  "log"
  "net/http"

  "github.com/gin-gonic/autotls"
  "github.com/gin-gonic/gin"
)

func main() {
  r := gin.Default()

  // Ping handler
  r.GET("/ping", func(c *gin.Context) {
    c.String(http.StatusOK, "pong")
  })

  log.Fatal(autotls.Run(r, "example1.com", "example2.com"))
}

自定义 autocert 管理器(指定域名白名单、证书缓存目录):

package main

import (
  "log"
  "net/http"

  "github.com/gin-gonic/autotls"
  "github.com/gin-gonic/gin"
  "golang.org/x/crypto/acme/autocert"
)

func main() {
  r := gin.Default()

  // Ping handler
  r.GET("/ping", func(c *gin.Context) {
    c.String(http.StatusOK, "pong")
  })

  m := autocert.Manager{
    Prompt:     autocert.AcceptTOS,
    HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),
    Cache:      autocert.DirCache("/var/www/.cache"),
  }

  log.Fatal(autotls.RunWithManager(r, &m))
}

若已有自己的证书,直接用 RunTLS(addr, certFile, keyFile) 即可,仓库自带测试证书 testdata/certificate/cert.pemtestdata/certificate/key.pem 可作本地验证。

同一进程运行多个服务

每个服务独立 gin.New() 并挂载各自的 http.Server,用 errgroup 并发启动:

package main

import (
  "log"
  "net/http"
  "time"

  "github.com/gin-gonic/gin"
  "golang.org/x/sync/errgroup"
)

var (
  g errgroup.Group
)

func router01() http.Handler {
  e := gin.New()
  e.Use(gin.Recovery())
  e.GET("/", func(c *gin.Context) {
    c.JSON(
      http.StatusOK,
      gin.H{
        "code":  http.StatusOK,
        "error": "Welcome server 01",
      },
    )
  })

  return e
}

func router02() http.Handler {
  e := gin.New()
  e.Use(gin.Recovery())
  e.GET("/", func(c *gin.Context) {
    c.JSON(
      http.StatusOK,
      gin.H{
        "code":  http.StatusOK,
        "error": "Welcome server 02",
      },
    )
  })

  return e
}

func main() {
  server01 := &http.Server{
    Addr:         ":8080",
    Handler:      router01(),
    ReadTimeout:  5 * time.Second,
    WriteTimeout: 10 * time.Second,
  }

  server02 := &http.Server{
    Addr:         ":8081",
    Handler:      router02(),
    ReadTimeout:  5 * time.Second,
    WriteTimeout: 10 * time.Second,
  }

  g.Go(func() error {
    err := server01.ListenAndServe()
    if err != nil && err != http.ErrServerClosed {
      log.Fatal(err)
    }
    return err
  })

  g.Go(func() error {
    err := server02.ListenAndServe()
    if err != nil && err != http.ErrServerClosed {
      log.Fatal(err)
    }
    return err
  })

  if err := g.Wait(); err != nil {
    log.Fatal(err)
  }
}

优雅停机与重启

第三方方案fvbock/endless 可替换 ListenAndServe,支持子进程重启(endless.ListenAndServe(":4242", router));类似的还有 grace(零停机重启)、graceful(优雅关闭)、manners(礼貌关闭)。

手动实现(Go 1.8+ 自带能力,推荐):监听 SIGINT/SIGTERM,给 http.Server.Shutdown 一个带超时的 context,等待进行中的请求完成:

package main

import (
  "context"
  "errors"
  "log"
  "net/http"
  "os"
  "os/signal"
  "syscall"
  "time"

  "github.com/gin-gonic/gin"
)

func main() {
  router := gin.Default()
  router.GET("/", func(c *gin.Context) {
    time.Sleep(5 * time.Second)
    c.String(http.StatusOK, "Welcome Gin Server")
  })

  srv := &http.Server{
    Addr:    ":8080",
    Handler: router,
  }

  // Initializing the server in a goroutine so that
  // it won't block the graceful shutdown handling below
  go func() {
    if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
      log.Printf("listen: %s\n", err)
    }
  }()

  // Wait for interrupt signal to gracefully shutdown the server with
  // a timeout of 5 seconds.
  quit := make(chan os.Signal)
  // kill (no param) default send syscall.SIGTERM
  // kill -2 is syscall.SIGINT
  // kill -9 is syscall.SIGKILL but can't be caught, so don't need to add it
  signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
  <-quit
  log.Println("Shutting down server...")

  // The context is used to inform the server it has 5 seconds to finish
  // the request it is currently handling
  ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
  defer cancel()

  if err := srv.Shutdown(ctx); err != nil {
    log.Fatal("Server forced to shutdown:", err)
  }

  log.Println("Server exiting")
}

HTTP/2 Server Push

http.Pushergo1.8+ 支持,且必须在 HTTPS 下工作:

package main

import (
  "html/template"
  "log"
  "net/http"

  "github.com/gin-gonic/gin"
)

var html = template.Must(template.New("https").Parse(`
<html>
<head>
  <title>Https Test</title>
  <script src="/assets/app.js"></script>
</head>
<body>
  <h1 style="color
登录后查看全文
热门项目推荐
相关项目推荐

项目优选

收起
kernelkernel
deepin linux kernel
C
33
18
ops-transformerops-transformer
本项目是CANN提供的transformer类大模型算子库,实现网络在NPU上加速计算。
C++
1.12 K
2.72 K
kernelkernel
openEuler内核是openEuler操作系统的核心,既是系统性能与稳定性的基石,也是连接处理器、设备与服务的桥梁。
C
528
588
ops-nnops-nn
本项目是CANN提供的神经网络类计算算子库,实现网络在NPU上加速计算。
C++
906
1.83 K
pytorchpytorch
作为 Ascend for PyTorch 社区的核心组件,TorchNPU 是昇腾专为 PyTorch 打造的深度学习适配插件,使 PyTorch 框架能够直接调用昇腾 NPU,为开发者提供昇腾 AI 处理器的超强算力。
Python
854
1.34 K
docsdocs
暂无描述
Markdown
891
5.78 K
jiuwenswarmjiuwenswarm
JiuwenSwarm 是一款基于openJiuwen开发的智能AI Agent,它能够将大语言模型的强大能力,通过你日常使用的各类通讯应用,直接延伸至你的指尖。
Python
3.53 K
1.01 K
ops-mathops-math
本项目是CANN提供的数学类基础计算算子库,实现网络在NPU上加速计算。
C++
1.34 K
1.45 K
cann-learning-hubcann-learning-hub
CANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。
Jupyter Notebook
987
506
AscendNPU-IRAscendNPU-IR
AscendNPU-IR是基于MLIR(Multi-Level Intermediate Representation)构建的,面向昇腾亲和算子编译时使用的中间表示,提供昇腾完备表达能力,通过编译优化提升昇腾AI处理器计算效率,支持通过生态框架使能昇腾AI处理器与深度调优
C++
540
384