Gin 文档翻译

A-Donga · · 3775 次点击 · 开始浏览    置顶
这是一个创建于 的主题,其中的信息可能已经有所发展或是发生改变。

# Gin web 框架 Gin 是Golang编写的web框架。它具有类似于`martini`的API接口,同时比`httprouter`快40倍的性能。如果你需要较好的性能和友好的开发方式,你会喜欢上`Gin`。 ## 安装 如果想要安装Gin依赖,你需要安装Go并正确的设置工作空间。 1. 已经安装Go(1.11以上版本,并且启用Go Mod),你可以下面的指令加入依赖: ``` $ go get -u github.com/gin-gonic/gin ``` 2. 在你的代码中引入: ```go import "github/gin-gonic/gin" ``` 3. (可选的)引入`net/http`。在使用诸如`http.StatusOk`的时候,他是必须引入的: ```go import "net/http" ``` ## 简单使用 ``` # 假设example.go文件中,存在以下代码 $ cat example.go ``` ```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` [全部性能测试](https://github.com/gin-gonic/gin/blob/master/BENCHMARKS.md) | Benchmark name | (1) | (2) | (3) | (4) | | :--|--:|--:|--:|--:| | Benchmark Gin_GithubAll | 43550 | 27364 ns/op | 0 B/op | 0 allocs/op | | Benchmark Ace_GithubAll | 40543 | 29670 ns/op | 0 B/op | 0 allocs/op | | Benchmark Aero_GithubAll | 57632 | 20648 ns/op | 0 B/op | |0 allocs/op | | Benchmark Bear_GithubAll | 9234 | 216179 ns/op | 86448 B/op | 943 allocs/op | | Benchmark Beego_GithubAll | 7407 | 243496 ns/op | 71456 B/op | 609 allocs/op | | Benchmark Bone_GithubAll | 420 | 2922835 ns/op | 720160 B/op | 8620 allocs/op | | Benchmark Chi_GithubAll | 7620 | 238331 ns/op | 87696 B/op | 609 allocs/op | | Benchmark Denco_GithubAll | 18355 | 64494 ns/op | 20224 B/op | 167 allocs/op | | Benchmark Echo_GithubAll | 31251 | 38479 ns/op | 0 B/op | 0 allocs/op | | Benchmark GocraftWeb_GithubAll | 4117 | 300062 ns/op | 131656 B/op | 1686 allocs/op | | Benchmark Goji_GithubAll | 3274 | 416158 ns/op | 56112 B/op | 334 allocs/op | | Benchmark Gojiv2_GithubAll | 1402 | 870518 ns/op | 352720 B/op | 4321 allocs/op | | Benchmark GoJsonRest_GithubAll | 2976 | 401507 ns/op | 134371 B/op | 2737 allocs/op | | Benchmark GoRestful_GithubAll | 410 | 2913158 ns/op | 910144 B/op | 2938 allocs/op | | Benchmark GorillaMux_GithubAll | 346 | 3384987 ns/op | 251650 B/op | 1994 allocs/op | | Benchmark GowwwRouter_GithubAll | 10000 | 143025 ns/op | 72144 B/op | 501 allocs/op | | Benchmark HttpRouter_GithubAll | 55938 | 21360 ns/op | 0 B/op | 0 allocs/op | | Benchmark HttpTreeMux_GithubAll | 10000 | 153944 ns/op | 65856 B/op | 671 allocs/op | | Benchmark Kocha_GithubAll | 10000 | 106315 ns/op | 23304 B/op | 843 allocs/op | | Benchmark LARS_GithubAll | 47779 | 25084 ns/op | 0 B/op | 0 allocs/op | | Benchmark Macaron_GithubAll | 3266 | 371907 ns/op | 149409 B/op | 1624 allocs/op | | Benchmark Martini_GithubAll | 331 | 3444706 ns/op | 226551 B/op | 2325 allocs/op | | Benchmark Pat_GithubAll | 273 | 4381818 ns/op | 1483152 B/op | 26963 allocs/op | | Benchmark Possum_GithubAll | 10000 | 164367 ns/op | 84448 B/op | 609 allocs/op | | Benchmark R2router_GithubAll | 10000 | 160220 ns/op | 77328 B/op | 979 allocs/op | | Benchmark Rivet_GithubAll | 14625 | 82453 ns/op | 16272 B/op | 167 allocs/op | | Benchmark Tango_GithubAll | 6255 | 279611 ns/op | 63826 B/op | 1618 allocs/op | | Benchmark TigerTonic_GithubAll | 2008 | 687874 ns/op | 193856 B/op | 4474 allocs/op | | Benchmark Traffic_GithubAll | 355 | 3478508 ns/op | 820744 B/op | 14114 allocs/op | | Benchmark Vulcan_GithubAll | 6885 | 193333 ns/op | 19894 B/op | 609 allocs/op | - (1): 恒定时间的重复操作,数值越高,性能越高。 - (2): 定量的重复操作,时间越低,性能越高。 - (3): 占用内存量,数值越低,性能越高。 - (4): 每次重复操作的平均之间,数值越低,性能越高。 ## Gin v1 稳定版 - [x] 零内存(Zero allocation, 内存控制对于web服务来说非常重要,性能影响非常大)路由。 - [x] 是最快的路由、框架。 - [x] 完整的单元测试组件。 - [x] 经历过正规校验。 - [x] 固定的API,版本更替不会导致代码修改。 ## 使用[jsoniter](https://github.com/json-iterator/go) > json iterator 是一个性能很高的json处理组件 Gin 使用`encoding/json`作为默认json解析工具,但是你可以通过其他`tag`改变为`jsoniter`。 ``` $ go build -tags=jsoniter . ``` ## API 示例 你可以在[Gin 示例仓库](https://github.com/gin-gonic/examples) 找到一些可以运行的示例。 ### 使用GET, POST, PUT, PATCH, DELETE and OPTIONS ```go 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") 可以指定监听端口 } ``` ### 路径参数 ```go 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) ```go 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(表单) ```go 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 ``` 目标服务 ```go 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](https://github.com/gin-gonic/gin/issues/774) 和详细[示例](https://github.com/gin-gonic/examples/tree/master/upload-file/single) 系统不应该信任(直接使用)文件的文件名。 详情参考:[Content-Disposition on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Directives) 、[#1693](https://github.com/gin-gonic/gin/issues/1693) >文件名始终是可选的,并且不能被应用程序直接使用:路径信息应被删除,并且应完成向服务器文件系统规则的转换。 ```go 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" ``` #### 多文件 查看更详细的[示例代码](https://github.com/gin-gonic/examples/tree/master/upload-file/multiple) ```go 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" ``` ### 分组路由 ```go 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 将: ```go // 默认使用日志和恢复中间件 r := gin.Default() ``` 替换为: ```go r := gin.New() ``` ### 使用中间件 ```go 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") } ``` ### 自定义恢复行为 ```go 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") } ``` ### 如何将日志写入到文件 ```go 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") } ``` ### 自定义日志格式 ```go 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进行着色。 无颜色的日志 ```go func main() { // 关闭日志颜色 gin.DisableConsoleColor() // 创建默认gin路由器 // 日志和恢复中间件 router := gin.Default() router.GET("/ping", func(c *gin.Context) { c.String(200, "pong") }) router.Run(":8080") } ``` 存在颜色的日志 ```go 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](https://github.com/go-playground/validator)进行校验。[查看使用文档](https://godoc.org/github.com/go-playground/validator#hdr-Baked_In_Validators_and_Tags) 请注意,您需要在要绑定的所有字段上设置相应的绑定标签(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。 ```go // 从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:"-"`,则在再次运行以上示例时不会返回错误。 ### 定制化认证器 注册自定义验证器。详情请查[示例代码](注册自定义验证器。详情请查[https://github.com/gin-gonic/examples/tree/master/custom-validation/server.go]) ```go 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"}% ``` [结构体等级的校验](https://github.com/go-playground/validator/releases/tag/v8.7) 可以通过同样的方式进行注册。更多信息请查看[结构体校验](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) 。 ### 仅绑定 QueryString `ShouldBindQuery` 方法仅绑定查询参数。详情请看[详细信息](https://github.com/gin-gonic/gin/issues/742#issuecomment-315953017) ```go 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数据 详细请看[详细信息](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292) ```go 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 详情请看[详细信息](https://github.com/gin-gonic/gin/issues/846) ```go 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 ```go 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的多选框 查看[详细信息](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092) main.go ```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 ```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> ``` 结果: ```json {"color":["red","green","blue"]} ``` ### Multipart/Urlencoded数据绑定 ```go 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 渲染 ```go 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)”。 ```go 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从其他域中的服务器请求数据。如果查询参数回调存在,则将回调添加到响应主体。 ```go 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及更低版本中不可用。 ```go 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") } ``` ### 静态文件 ```go 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") } ``` ### 从文件中读取数据 ```go 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读取数据 ```go 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() ```go 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 ```gotemplate <html> <h1> {{ .title }} </h1> </html> ``` 使用不同文件夹下的相同名的模版 ```go 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 ```gotemplate {{ define "posts/index.tmpl" }} <html><h1> {{ .title }} </h1> <p>Using posts/index.tmpl</p> </html> {{ end }} ``` templates/users/index.tmpl ```gotemplate {{ define "users/index.tmpl" }} <html><h1> {{ .title }} </h1> <p>Using users/index.tmpl</p> </html> {{ end }} ``` #### 自定义模版翻译器 你可以使用自己的`html模版`翻译器 ```go import "html/template" func main() { router := gin.Default() html := template.Must(template.ParseFiles("file1", "file2")) router.SetHTMLTemplate(html) router.Run(":8080") } ``` #### 自定义分隔符 例如使用如下分隔符 ```go r := gin.Default() r.Delims("{[{", "}]}") r.LoadHTMLGlob("/path/to/templates") ``` #### 自定义模版函数 详情请看[示例代码](See the detail example code.) main.go ```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 ```gotemplate Date: {[{.now | formatAsDate}]} ``` 结果 ``` Date: 2017/07/01 ``` ### 多模版 Gin默认仅允许使用html.Template. 检查多模板渲染是否使用诸如go 1.6块模板之类的功能. ### 重定向 发起重定向很简单,内部和外部都可以使用。 ```go r.GET("/test", func(c *gin.Context) { c.Redirect(http.StatusMovedPermanently, "http://www.google.com/") }) ``` Post请求重定向。Issue:[#444](https://github.com/gin-gonic/gin/issues/444) ```go r.POST("/test", func(c *gin.Context) { c.Redirect(http.StatusFound, "/foo") }) ``` 发起路由重定向,仿照下方示例使用`HandleContext()` ```go 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"}) }) ``` ### 自定义中间件 ```go 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()中间件 ```go // 模拟一些私有的数据 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时,不应使用其内部的原始上下文,而必须使用只读副本 ```go 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(),如下 ```go func main() { router := gin.Default() http.ListenAndServe(":8080", router) } ``` 或者 ```go 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服务器的示例。 ```go 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")) } ``` 自定义自动证书管理器的示例 ```go 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启动多个服务 查看[相关问题](https://github.com/gin-gonic/gin/issues/346),并尝试以下代码 ```go 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](https://github.com/fvbock/endless)替换掉默认的ListenAndServe。具体信息请查看:问题[#296](https://github.com/gin-gonic/gin/issues/296) ```go router := gin.Default() router.GET("/", handler) // [...] endless.ListenAndServe(":4242", router) ``` 备选方案 - [manners](https://github.com/braintree/manners): 优雅的关闭Http服务 - [graceful](https://github.com/tylerb/graceful): Graceful是Go软件包,可用于正常关闭http.Handler服务器。 - [grace](https://github.com/facebookgo/grace): 为Go服务器实现平稳重启和零停机部署。 #### 手动关闭 如果使用的是Go 1.8或更高版本,则可能不需要使用这些库。考虑使用http.Server的内置Shutdown()方法进行正常关闭。下面的示例描述了它的用法,我们在这里有更多使用gin的示例。 ```go // +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](https://github.com/jessevdk/go-assets) 将服务器构建为包含模板的单个二进制文件。 ```go 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目录中的完整示例。 ### 将表单数据请求与自定义结构绑定 以下示例使用自定义结构: ```go 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`,不能多次调用它们。 ```go 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。 ```go 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](https://github.com/gin-gonic/gin/pull/1341))。 ### http2 服务端推送功能 http.Pusher功能在**go.18**版本后才开始支持,有关详细信息,请参见[golang](https://blog.golang.org/h2push) 博客 ```go 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、键值对或其他)进行日志打印。在下面的示例中,我们使用标准日志包记录所有路由,但是您可以使用其他适合您需求的日志工具。 ```go 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 ```go 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测试的首选方法。 ```go 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") } ``` 上方代码的测试用例 ```go 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()) } ``` 翻译人:A-Donga

有疑问加站长微信联系(非本文作者)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

3775 次点击  ∙  1 赞  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传