Gin文档翻译

    科技2026-08-30  1

    Gin web 框架

    文章目录

    Gin web 框架安装简单使用性能测试Gin v1 稳定版使用[jsoniter](https://github.com/json-iterator/go)API 示例使用GET, POST, PUT, PATCH, DELETE and OPTIONS路径参数查询字符串参数(querystring parameters)Multipart/Urlencoded Form(表单)其他示例:query + post form(表单)将字符串参数(querystring)或 提交表单(postform) 转换为Map上传文件单文件多文件 分组路由使用没有中间件的空白Gin使用中间件自定义恢复行为如何将日志写入到文件自定义日志格式样例输出 控制日志输出的颜色模型绑定与校验样例请求跳过认证 定制化认证器仅绑定 QueryString绑定QueryString或Post数据绑定URI绑定Header绑定HTML的多选框Multipart/Urlencoded数据绑定XML, JSON, YAML 和 ProtoBuf 渲染SecureJSONJSONPAsciiJSON 静态文件从文件中读取数据从Reader读取数据 翻译HTML自定义模版翻译器自定义分隔符自定义模版函数 多模版重定向自定义中间件使用BaseAuth()中间件中间件的Goroutines自定义Http配置支持 Let'sEncrypt使用Gin启动多个服务正常关机、重启第三方组件手动关闭 使用模板构建一个二进制文件将表单数据请求与自定义结构绑定尝试将主体绑定到不同的结构体http2 服务端推送功能声明路由的日志格式设置、获取Cookie测试

    Gin 是Golang编写的web框架。它具有类似于martini的API接口,同时比httprouter快40倍的性能。如果你需要较好的性能和友好的开发方式,你会喜欢上Gin。

    安装

    如果想要安装Gin依赖,你需要安装Go并正确的设置工作空间。

    已经安装Go(1.11以上版本,并且启用Go Mod),你可以下面的指令加入依赖: $ go get -u github.com/gin-gonic/gin 在你的代码中引入: import "github/gin-gonic/gin" (可选的)引入net/http。在使用诸如http.StatusOk的时候,他是必须引入的: import "net/http"

    简单使用

    # 假设example.go文件中,存在以下代码 $ cat example.go package main import "github.com/gin-gonic/gin" func main() { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "pong", }) }) r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") } # 运行example.go文件,并且在浏览器上浏览0.0.0.0:8080/ping (对于windows :“localhost:8080/ping”) $ go run example.go

    性能测试

    Gin 使用了定制版的https://github.com/julienschmidt/httprouter

    全部性能测试

    Benchmark name(1)(2)(3)(4)Benchmark Gin_GithubAll4355027364 ns/op0 B/op0 allocs/opBenchmark Ace_GithubAll4054329670 ns/op0 B/op0 allocs/opBenchmark Aero_GithubAll5763220648 ns/op0 B/opBenchmark Bear_GithubAll9234216179 ns/op86448 B/op943 allocs/opBenchmark Beego_GithubAll7407243496 ns/op71456 B/op609 allocs/opBenchmark Bone_GithubAll4202922835 ns/op720160 B/op8620 allocs/opBenchmark Chi_GithubAll7620238331 ns/op87696 B/op609 allocs/opBenchmark Denco_GithubAll1835564494 ns/op20224 B/op167 allocs/opBenchmark Echo_GithubAll3125138479 ns/op0 B/op0 allocs/opBenchmark GocraftWeb_GithubAll4117300062 ns/op131656 B/op1686 allocs/opBenchmark Goji_GithubAll3274416158 ns/op56112 B/op334 allocs/opBenchmark Gojiv2_GithubAll1402870518 ns/op352720 B/op4321 allocs/opBenchmark GoJsonRest_GithubAll2976401507 ns/op134371 B/op2737 allocs/opBenchmark GoRestful_GithubAll4102913158 ns/op910144 B/op2938 allocs/opBenchmark GorillaMux_GithubAll3463384987 ns/op251650 B/op1994 allocs/opBenchmark GowwwRouter_GithubAll10000143025 ns/op72144 B/op501 allocs/opBenchmark HttpRouter_GithubAll5593821360 ns/op0 B/op0 allocs/opBenchmark HttpTreeMux_GithubAll10000153944 ns/op65856 B/op671 allocs/opBenchmark Kocha_GithubAll10000106315 ns/op23304 B/op843 allocs/opBenchmark LARS_GithubAll4777925084 ns/op0 B/op0 allocs/opBenchmark Macaron_GithubAll3266371907 ns/op149409 B/op1624 allocs/opBenchmark Martini_GithubAll3313444706 ns/op226551 B/op2325 allocs/opBenchmark Pat_GithubAll2734381818 ns/op1483152 B/op26963 allocs/opBenchmark Possum_GithubAll10000164367 ns/op84448 B/op609 allocs/opBenchmark R2router_GithubAll10000160220 ns/op77328 B/op979 allocs/opBenchmark Rivet_GithubAll1462582453 ns/op16272 B/op167 allocs/opBenchmark Tango_GithubAll6255279611 ns/op63826 B/op1618 allocs/opBenchmark TigerTonic_GithubAll2008687874 ns/op193856 B/op4474 allocs/opBenchmark Traffic_GithubAll3553478508 ns/op820744 B/op14114 allocs/opBenchmark Vulcan_GithubAll6885193333 ns/op19894 B/op609 allocs/op (1): 恒定时间的重复操作,数值越高,性能越高。(2): 定量的重复操作,时间越低,性能越高。(3): 占用内存量,数值越低,性能越高。(4): 每次重复操作的平均之间,数值越低,性能越高。

    Gin v1 稳定版

    零内存(Zero allocation, 内存控制对于web服务来说非常重要,性能影响非常大)路由。 是最快的路由、框架。 完整的单元测试组件。 经历过正规校验。 固定的API,版本更替不会导致代码修改。

    使用jsoniter

    json iterator 是一个性能很高的json处理组件

    Gin 使用encoding/json作为默认json解析工具,但是你可以通过其他tag改变为jsoniter。

    $ go build -tags=jsoniter .

    API 示例

    你可以在Gin 示例仓库 找到一些可以运行的示例。

    使用GET, POST, PUT, PATCH, DELETE and OPTIONS

    func main() { // 使用默认中间件创建gin路由器 // 日志、恢复中间件, // 日志中间件用于记录请求等日志信息。 // 恢复中间件用户在发生以外的时候,返回500状态码, // 避免请求阻塞等意外情况发生 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) // 默认情况下,服务将会监听8080端口,或者使用PORT环境变量 router.Run() // router.Run(":3000") 可以指定监听端口 }

    路径参数

    func main() { router := gin.Default() // 匹配 /user/john // 不匹配 /user 或 /john router.GET("/user/:name", func(c *gin.Context) { name := c.Param("name") c.String(http.StatusOK, "Hello %s", name) }) // 匹配 /user/john 和 /user/john/send // 如果其他路由都不匹配 /user/john, 这个请求才会被定向到这个路由 // 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) }) // 每个请求的上下文中都会保存定义的路由 router.POST("/user/:name/*action", func(c *gin.Context) { c.FullPath() == "/user/:name/*action" // true }) router.Run(":8080") }

    查询字符串参数(querystring parameters)

    func main() { router := gin.Default() // 查询字符串参数使用现有的基础请求对象进行解析。 // 响应下列请求的url为: /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(200, gin.H{ "status": "posted", "message": message, "nick": nick, }) }) router.Run(":8080") }

    其他示例:query + post form(表单)

    请求

    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

    将字符串参数(querystring)或 提交表单(postform) 转换为Map

    请求

    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]

    上传文件

    单文件

    参考问题#774 和详细示例

    系统不应该信任(直接使用)文件的文件名。 详情参考:Content-Disposition on MDN 、#1693

    文件名始终是可选的,并且不能被应用程序直接使用:路径信息应被删除,并且应完成向服务器文件系统规则的转换。

    func main() { router := gin.Default() // 为组合表单(multipart)设置低内存(默认32MiB) router.MaxMultipartMemory = 8 << 20 // 8 MiB router.POST("/upload", func(c *gin.Context) { // 单文件 file, _ := c.FormFile("file") log.Println(file.Filename) // 上传到指定的目的地 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"

    多文件

    查看更详细的示例代码

    func main() { router := gin.Default() // 为组合表单(multipart)设置低内存(默认32MiB) router.MaxMultipartMemory = 8 << 20 // 8 MiB router.POST("/upload", func(c *gin.Context) { // 多表单 form, _ := c.MultipartForm() files := form.File["upload[]"] for _, file := range files { log.Println(file.Filename) // 上传到指定位置 c.SaveUploadedFile(file, dst) } c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files))) }) router.Run(":8080") }

    使用curl

    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"

    分组路由

    func main() { router := gin.Default() // 分组示例:v1 v1 := router.Group("/v1") { v1.POST("/login", loginEndpoint) v1.POST("/submit", submitEndpoint) v1.POST("/read", readEndpoint) } // 分组示例:v2 v2 := router.Group("/v2") { v2.POST("/login", loginEndpoint) v2.POST("/submit", submitEndpoint) v2.POST("/read", readEndpoint) } router.Run(":8080") }

    使用没有中间件的空白Gin

    将:

    // 默认使用日志和恢复中间件 r := gin.Default()

    替换为:

    r := gin.New()

    使用中间件

    func main() { // 创建一个默认不带任何中间件的路由器 r := gin.New() // 全局中间件 // 即使设置GIN_MODE=release,日志中间件也会将日志写入到gin.DefaultWriter。 // 默认情况下,gin.DefaultWriter = os.Stdout r.Use(gin.Logger()) // 恢复中间件将会从任何异常种复原,并且返回500状态码 r.Use(gin.Recovery()) // 对于每个路由中间件,您可以根据需要添加任意数量。 r.GET("/benchmark", MyBenchLogger(), benchEndpoint) // 权限、认证路由组 // authorized := r.Group("/", AuthRequired()) // 如下 authorized := r.Group("/") // 组级别中间件,可以定制化创建 // AuthRequired()中间件仅会存在于认证路由组 authorized.Use(AuthRequired()) { authorized.POST("/login", loginEndpoint) authorized.POST("/submit", submitEndpoint) authorized.POST("/read", readEndpoint) // 嵌套组 testing := authorized.Group("testing") testing.GET("/analytics", analyticsEndpoint) } // 监听端口:8080 r.Run(":8080") }

    自定义恢复行为

    func main() { // 创建一个默认不带任何中间件的路由器 r := gin.New() // 全局中间件 // 即使设置GIN_MODE=release,日志中间件也会将日志写入到gin.DefaultWriter。 // 默认情况下,gin.DefaultWriter = os.Stdout r.Use(gin.Logger()) // 恢复中间件将会从任何异常种复原,并且返回500状态码 r.Use(gin.CustomRecovery(func(c *gin.Context, recovered interface{}) { 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") }) // Listen and serve on 0.0.0.0:8080 r.Run(":8080") }

    如何将日志写入到文件

    func main() { // 关闭控制台颜色,在日志写入到文件的时候不需要开启控制台颜色。 gin.DisableConsoleColor() // 将日志记录到文件 f, _ := os.Create("gin.log") gin.DefaultWriter = io.MultiWriter(f) // 如果你希望将日志同时输出到文件和控制台,使用下列代码 // gin.DefaultWriter = io.MultiWriter(f, os.Stdout) router := gin.Default() router.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) router.Run(":8080") }

    自定义日志格式

    func main() { router := gin.New() // 格式化日志中间件会将日志写入到gin.DefaultWriter // 默认情况下 gin.DefaultWriter = os.Stdout router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string { // 你自定义的格式 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(200, "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" "

    控制日志输出的颜色

    默认情况下,控制台上输出的日志应根据检测到的TTY进行着色。

    无颜色的日志

    func main() { // 关闭日志颜色 gin.DisableConsoleColor() // 创建默认gin路由器 // 日志和恢复中间件 router := gin.Default() router.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) router.Run(":8080") }

    存在颜色的日志

    func main() { // 强制使用颜色 gin.ForceConsoleColor() // 创建默认gin路由器 // 日志和恢复中间件 router := gin.Default() router.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) router.Run(":8080") }

    模型绑定与校验

    如果要将请求体绑定到一种类型,可以使用模型绑定。Gin当前支持绑定json、XML、YAML和标准的表单数据(foo=bar&boo=baz)。

    Gin 使用go-playground/validator/v10进行校验。查看使用文档

    请注意,您需要在要绑定的所有字段上设置相应的绑定标签(tag)。例如,当需要绑定json类型的数据,进行如下设置json:"filedname"。

    Gin提供了两种方式绑定数据

    类型:强制绑定(Must bind) 方法:Bind、BindJSON、BindXML、BindQuery、BindYAML、BindHeader行为: 这些方法的底层会调用mustBindWith。如果发生了绑定异常,请求(request)将会直接失败,并返回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 witch 422。 如果你希望控制绑定的更多行为,可以考虑使用ShouldBind。 类型:弱绑定(Should bind) 方法:ShouldBind、ShouldBindJSON、ShouldBindXML、ShouldBindQuery、ShouldBindYAML、ShouldBindHeader行为:这些方法的底层回调用ShouldBindJSON。如果发生了绑定异常,该异常会返回给开发人员,开发者可以适当地处理请求和错误。

    当使用绑定方法时,Gin会尝试从请求头中的Content-Type值推断绑定依赖。如果你确定需要绑定什么数据,可以使用ShouldBind或者MustBind。

    你可以指定那些字段是必须的。如果一个字段声明了:binding:"required",并且在解析的时候,没有该字段,将会返回一个error。

    // 从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() // 样例:JOSN绑定 ({"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"}) }) // 样例:XML绑定 ( // <?xml version="1.0" encoding="UTF-8"?> // <root> // <user>user</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"}) }) // 例如:绑定HTML表单(form)(user=manu&password=123) router.POST("/loginForm", func(c *gin.Context) { var form Login // 将会从请求头中content-type推断绑定类型 //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"}) }) // 监听8080端口 router.Run(":8080") }

    样例请求

    $ 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"}

    跳过认证

    使用上面的curl命令运行上面的示例时,它返回错误。因为该示例对密码使用binding:"required"。如果对密码使用binding:"-",则在再次运行以上示例时不会返回错误。

    定制化认证器

    注册自定义验证器。详情请查示例代码

    package main import ( "net/http" "time" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" "github.com/go-playground/validator/v10" ) // Booking 包含绑定和验证数据 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"}%

    结构体等级的校验 可以通过同样的方式进行注册。更多信息请查看结构体校验 。

    仅绑定 QueryString

    ShouldBindQuery 方法仅绑定查询参数。详情请看详细信息

    package main import ( "log" "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(200, "Success") }

    绑定QueryString或Post数据

    详细请看详细信息

    package main import ( "log" "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"` } func main() { route := gin.Default() route.GET("/testing", startPage) route.Run(":8085") } func startPage(c *gin.Context) { var person Person // 如果为Get方法,仅处理Form数据 // 如果为Post方法,首先检查`content-type`,如果是JSON或者XML将会是使用表单数据 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) } c.String(200, "Success") }

    使用如下代码进行测试

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

    绑定URI

    详情请看详细信息

    package main import "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(400, gin.H{"msg": err}) return } c.JSON(200, 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

    绑定Header

    package main import ( "fmt" "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(200, err) } fmt.Printf("%#v\n", h) c.JSON(200, gin.H{"Rate": h.Rate, "Domain": h.Domain}) }) r.Run() // 客户端 // curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/ // 输出 // {"Domain":"music","Rate":300} }

    绑定HTML的多选框

    查看详细信息

    main.go

    ... type myForm struct { Colors []string `form:"colors[]"` } ... func formHandler(c *gin.Context) { var fakeForm myForm c.ShouldBind(&fakeForm) c.JSON(200, gin.H{"color": fakeForm.Colors}) } ...

    form.html

    <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数据绑定

    type ProfileForm struct { Name string `form:"name" binding:"required"` Avatar *multipart.FileHeader `form:"avatar" binding:"required"` // 或者多文件 // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"` } func main() { router := gin.Default() router.POST("/profile", func(c *gin.Context) { //您可以使用显式绑定声明来绑定多部分表单: // c.ShouldBindWith(&form, binding.Form) // 或者配合ShouldBind使用autobinding方法 var form ProfileForm // 在这种情况下,将自动选择适当的绑定 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

    XML, JSON, YAML 和 ProtoBuf 渲染

    func main() { r := gin.Default() // gin.H is a shortcut for map[string]interface{} // gin.H 是map[string]interface{}快捷方式(等效) 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) { // 你也可以使用一个结构体 var msg struct { Name string `json:"user"` Message string Number int } msg.Name = "Lena" msg.Message = "hey" msg.Number = 123 // 注意: msg.Name 在JSON文件中将会变为 "user" // 输出: {"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("/someProtoBuf", func(c *gin.Context) { reps := []int64{int64(1), int64(2)} label := "test" // protobuf的特定定义写在testdata / protoexample文件中。 data := &protoexample.Test{ Label: &label, Reps: reps, } // 注意: data 将会在应答中变为二进制数据 // 输出: protoexample.Test protobuf serialized data c.ProtoBuf(http.StatusOK, data) }) // 服务运行并监听: 0.0.0.0:8080 r.Run(":8080") }

    SecureJSON

    使用SecureJSON防止json劫持。如果给定的结构是数组值,则默认值在响应主体前加上“ while(1)”。

    func main() { r := gin.Default() // 你可以使用你自定义的JSON安全前缀 // r.SecureJsonPrefix(")]}',\n") r.GET("/someJSON", func(c *gin.Context) { names := []string{"lena", "austin", "foo"} // 输出: while(1);["lena","austin","foo"] c.SecureJSON(http.StatusOK, names) }) // 服务运行并监听: 0.0.0.0:8080 r.Run(":8080") }

    JSONP

    使用JSONP从其他域中的服务器请求数据。如果查询参数回调存在,则将回调添加到响应主体。

    func main() { r := gin.Default() r.GET("/JSONP", func(c *gin.Context) { data := gin.H{ "foo": "bar", } // 回调为:x // 输出 : x({\"foo\":\"bar\"}) c.JSONP(http.StatusOK, data) }) // 服务运行并监听: 0.0.0.0:8080 r.Run(":8080") // 客户端 // curl http://127.0.0.1:8080/JSONP?callback=x }

    AsciiJSON

    通常,JSON用其unicode实体替换特殊的HTML字符,例如<变成\ u003c。如果要按字面意义编码此类字符,则可以改用PureJSON。此功能在Go 1.6及更低版本中不可用。

    func main() { r := gin.Default() // 服务unicode实体 r.GET("/json", func(c *gin.Context) { c.JSON(200, gin.H{ "html": "<b>Hello, world!</b>", }) }) // 提供文字字符 r.GET("/purejson", func(c *gin.Context) { c.PureJSON(200, gin.H{ "html": "<b>Hello, world!</b>", }) }) // 服务运行并监听:0.0.0.0:8080 r.Run(":8080") }

    静态文件

    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") // 服务运行并监听: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()

    func main() { router := gin.Default() router.LoadHTMLGlob("templates/*") //router.LoadHTMLFiles("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>

    使用不同文件夹下的相同名的模版

    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") }

    templates/posts/index.tmpl

    {{ define "posts/index.tmpl" }} <html><h1> {{ .title }} </h1> <p>Using posts/index.tmpl</p> </html> {{ end }}

    templates/users/index.tmpl

    {{ define "users/index.tmpl" }} <html><h1> {{ .title }} </h1> <p>Using users/index.tmpl</p> </html> {{ end }}

    自定义模版翻译器

    你可以使用自己的html模版翻译器

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

    自定义分隔符

    例如使用如下分隔符

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

    自定义模版函数

    详情请看[示例代码](See the detail example code.)

    main.go

    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") }

    raw.tmpl

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

    结果

    Date: 2017/07/01

    多模版

    Gin默认仅允许使用html.Template. 检查多模板渲染是否使用诸如go 1.6块模板之类的功能.

    重定向

    发起重定向很简单,内部和外部都可以使用。

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

    Post请求重定向。Issue:#444

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

    发起路由重定向,仿照下方示例使用HandleContext()

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

    自定义中间件

    func Logger() gin.HandlerFunc { return func(c *gin.Context) { t := time.Now() // 设置变量:example c.Set("example", "12345") // 请求之前 c.Next() // 请求之后 latency := time.Since(t) log.Print(latency) // 访问我们正在发送的状态 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) // 将会打印12345 log.Println(example) }) // 服务启动并监听8080端口 r.Run(":8080") }

    使用BaseAuth()中间件

    // 模拟一些私有的数据 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 使用 gin.BasicAuth() 中间件 // gin.Accounts 的类型是 map[string]string authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{ "foo": "bar", "austin": "1234", "lena": "hello2", "manu": "4321", })) // /admin/secrets 终点 // 隐藏 "localhost:8080/admin/secrets authorized.GET("/secrets", func(c *gin.Context) { // 获取用户, 有BaseAuth中间件控制 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 :("}) } }) // 服务运行并监听8080端口 r.Run(":8080") }

    中间件的Goroutines

    在中间件或处理程序中启动新的Goroutines时,不应使用其内部的原始上下文,而必须使用只读副本

    func main() { r := gin.Default() r.GET("/long_async", func(c *gin.Context) { // 创建要在goroutine中使用的副本 cCp := c.Copy() go func() { // 用time.Sleep()模拟一个长任务。 5秒 time.Sleep(5 * time.Second) // 请注意,您正在使用复制的上下文“ cCp”,重要 log.Println("Done! in path " + cCp.Request.URL.Path) }() }) r.GET("/long_sync", func(c *gin.Context) { // 用time.Sleep()模拟一个长任务,5秒 time.Sleep(5 * time.Second) // 因为我们没有使用goroutine,所以我们不必复制上下文 log.Println("Done! in path " + c.Request.URL.Path) }) // 服务启动并监听8080端口 r.Run(":8080") }

    自定义Http配置

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

    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() }

    支持 Let’sEncrypt

    1行LetsEncrypt HTTPS服务器的示例。

    package main import ( "log" "github.com/gin-gonic/autotls" "github.com/gin-gonic/gin" ) func main() { r := gin.Default() // 监听ping路径 r.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) log.Fatal(autotls.Run(r, "example1.com", "example2.com")) }

    自定义自动证书管理器的示例

    package main import ( "log" "github.com/gin-gonic/autotls" "github.com/gin-gonic/gin" "golang.org/x/crypto/acme/autocert" ) func main() { r := gin.Default() // 监听ping路径 r.GET("/ping", func(c *gin.Context) { c.String(200, "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)) }

    使用Gin启动多个服务

    查看相关问题,并尝试以下代码

    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。具体信息请查看:问题#296

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

    备选方案

    manners: 优雅的关闭Http服务graceful: Graceful是Go软件包,可用于正常关闭http.Handler服务器。grace: 为Go服务器实现平稳重启和零停机部署。

    手动关闭

    如果使用的是Go 1.8或更高版本,则可能不需要使用这些库。考虑使用http.Server的内置Shutdown()方法进行正常关闭。下面的示例描述了它的用法,我们在这里有更多使用gin的示例。

    // +build go1.8 package main import ( "context" "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 && err != http.ErrServerClosed { log.Fatalf("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 catch, so don't need 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") }

    使用模板构建一个二进制文件

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

    func main() { r := gin.New() t, err := loadTemplate() if err != nil { panic(err) } r.SetHTMLTemplate(t) r.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "/html/index.tmpl",nil) }) r.Run(":8080") } // loadTemplate加载go-assets-builder嵌入的模板 func loadTemplate() (*template.Template, error) { t := template.New("") for name, file := range Assets.Files { defer file.Close() if file.IsDir() || !strings.HasSuffix(name, ".tmpl") { continue } h, err := ioutil.ReadAll(file) if err != nil { return nil, err } t, err = t.New(name).Parse(string(h)) if err != nil { return nil, err } } return t, nil }

    请参阅https://github.com/gin-gonic/examples/tree/master/assets-in-binary目录中的完整示例。

    将表单数据请求与自定义结构绑定

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

    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(200, gin.H{ "a": b.NestedStruct, "b": b.FieldB, }) } func GetDataC(c *gin.Context) { var b StructC c.Bind(&b) c.JSON(200, gin.H{ "a": b.NestedStructPointer, "c": b.FieldC, }) } func GetDataD(c *gin.Context) { var b StructD c.Bind(&b) c.JSON(200, 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() }

    Using the command curl command result: 使用指令curl的结果如下:

    $ 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"}}

    尝试将主体绑定到不同的结构体

    绑定请求正文的常规方法消耗c.Request.Body,不能多次调用它们。

    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{} // 此c.ShouldBind消耗c.Request.Body,并且无法重用 if errA := c.ShouldBind(&objA); errA == nil { c.String(http.StatusOK, `the body should be formA`) // 由于c.Request.Body现在是EOF,因此总是会发生错误 } else if errB := c.ShouldBind(&objB); errB == nil { c.String(http.StatusOK, `the body should be formB`) } else { ... } }

    为此,您可以使用c.ShouldBindBodyWith。

    func SomeHandler(c *gin.Context) { objA := formA{} objB := formB{} // 这将读取c.Request.Body并将结果存储到上下文中。 if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil { c.String(http.StatusOK, `the body should be formA`) // 此时,它会重用存储在上下文中的请求体。 } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil { c.String(http.StatusOK, `the body should be formB JSON`) // 它可以接受其他格式 } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil { c.String(http.StatusOK, `the body should be formB XML`) } else { ... } } c.ShouldBindBodyWith在绑定之前将主体存储到上下文中。这对性能有轻微影响,因此,如果足以一次调用绑定,则不应使用此方法。仅某些格式需要此功能JSON,XML,MsgPack,ProtoBuf。对于其他格式,c.ShouldBind()可以多次调用Query,Form,FormPost,FormMultipart,而不会对性能造成任何损害(请参阅#1341)。

    http2 服务端推送功能

    http.Pusher功能在go.18版本后才开始支持,有关详细信息,请参见golang 博客

    package main import ( "html/template" "log" "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:red;">Welcome, Ginner!</h1> </body> </html> `)) func main() { r := gin.Default() r.Static("/assets", "./assets") r.SetHTMLTemplate(html) r.GET("/", func(c *gin.Context) { if pusher := c.Writer.Pusher(); pusher != nil { // use pusher.Push() to do server push if err := pusher.Push("/assets/app.js", nil); err != nil { log.Printf("Failed to push: %v", err) } } c.HTML(200, "https", gin.H{ "status": "success", }) }) // 服务运行并监听8080端口 r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key") }

    声明路由的日志格式

    默认的日志格式为:

    [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)

    你可以使用gin.DebugPrintRouteFunc来声明指定的日志格式信息(例如:json、键值对或其他)进行日志打印。在下面的示例中,我们使用标准日志包记录所有路由,但是您可以使用其他适合您需求的日志工具。

    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") }) // 服务运行并监听8080端口 r.Run() }

    设置、获取Cookie

    import ( "fmt" "github.com/gin-gonic/gin" ) func main() { router := gin.Default() router.GET("/cookie", func(c *gin.Context) { cookie, err := c.Cookie("gin_cookie") if err != nil { cookie = "NotSet" c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true) } fmt.Printf("Cookie value: %s \n", cookie) }) router.Run() }

    测试

    net/http/httptest软件包是HTTP测试的首选方法。

    package main func setupRouter() *gin.Engine { r := gin.Default() r.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) return r } func main() { r := setupRouter() r.Run(":8080") }

    上方代码的测试用例

    package main import ( "net/http" "net/http/httptest" "testing" "github.com/stretchr/testify/assert" ) func TestPingRoute(t *testing.T) { router := setupRouter() w := httptest.NewRecorder() req, _ := http.NewRequest("GET", "/ping", nil) router.ServeHTTP(w, req) assert.Equal(t, 200, w.Code) assert.Equal(t, "pong", w.Body.String()) }
    Processed: 0.011, SQL: 9