add chinese docs (#1588)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by long-road · committed by thinkerou · parent 64457fb · Browse files · 1 file·+1940 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+1940 added−0 removed
- other:+1940 added−0 removed
Provenance
- Commit
6053156- Tree
5b3e184- Author
long-road <13412081338@163.com>- Committer
thinkerou <thinkerou@gmail.com>- Parent
64457fb
1 file changed+1940 added−0 removed
added:README_ZH.md+1940 added
1+# Gin Web 框架中文文档2+3+<img align="right" width="159px" src="https://raw.githubusercontent.com/gin-gonic/logo/master/color.png">4+5+[](https://travis-ci.org/gin-gonic/gin)6+[](https://codecov.io/gh/gin-gonic/gin)7+[](https://goreportcard.com/report/github.com/gin-gonic/gin)8+[](https://godoc.org/github.com/gin-gonic/gin)9+[](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)10+[](https://sourcegraph.com/github.com/gin-gonic/gin?badge)11+[](https://www.codetriage.com/gin-gonic/gin)12+[](https://github.com/gin-gonic/gin/releases)13+14+Gin 是一个 Go (Golang) 语言框架。 它是一个拥有更好性能的 martini-like API 框架, 比 [httprouter](https://github.com/julienschmidt/httprouter) 的速度快了40倍. 如果你是性能和高效的追求者, 那么你会爱上 Gin.15+16+17+18+## Contents19+20+- [安装](#安装)21+- [前提条件](#前提条件)22+- [快速启动](#快速启动)23+- [性能测试](#性能测试)24+- [Gin v1 稳定版](#gin-v1-稳定版)25+- [使用 jsoniter 构建](#使用-jsoniter-构建)26+- [API 示例](#api-示例)27+ - [GET,POST,PUT,PATCH,DELETE,OPTIONS 使用](#get-post-put-patch-delete-options-使用)28+ - [路由参数](#路由参数)29+ - [查询字符串参数](#查询字符串参数)30+ - [Multipart Urlencoded 表单](#multipart-urlencoded-表单)31+ - [另一个实列 query + post form](#另一个实列:-query-+-post-form)32+ - [映射参数 表单参数](#映射参数-表单参数)33+ - [上传文件](#上传文件)34+ - [路由组](#路由组)35+ - [默认初始化 Gin](#默认初始化-gin)36+ - [中间件使用](#中间件使用)37+ - [如何记录日志](#如何记录日志)38+ - [模型绑定和验证](#模型绑定和验证)39+ - [自定义验证器](#自定义验证器)40+ - [只绑定查询字符串](#只绑定查询字符串)41+ - [绑定查询字符串或发布数据](#绑定查询字符串或发布数据)42+ - [绑定 HTML 复选框](#绑定-html-复选框)43+ - [Multipart Urlencoded 绑定](#multipart-urlencoded-绑定)44+ - [XML JSON YAML ProtoBuf 渲染](#xml-json-yaml-protobuf-渲染)45+ - [SecureJSON](#SecureJSON)46+ - [静态文件服务](#静态文件服务)47+ - [从读者服务数据](#从读者服务数据)48+ - [HTML 渲染](#html-渲染)49+ - [多模板](#多模板)50+ - [重定向](#重定向)51+ - [自定义中间件](#自定义中间件)52+ - [使用 BasicAuth() 中间件](#使用-basicauth()-中间件)53+ - [Goroutines](#goroutines)54+ - [自定义 HTTP 配置](#自定义-http-配置)55+ - [Let's Encrypt 支持](#lets-encrypt-支持)56+ - [使用 Gin 运行多个服务](使用-gin-运行多个服务)57+ - [优雅重启或停止](#优雅重启或停止)58+ - [使用模板构建单个二进制文件](#使用模板构建单个二进制文件)59+ - [使用自定义结构绑定表单数据请求](#使用自定义结构绑定表单数据请求)60+ - [尝试将body绑定到不同的结构中](#尝试将-body-绑定到不同的结构中)61+ - [http2 server 推送](#http2-server-推送)62+ - [定义路由日志的格式](#定义路由日志的格式)63+- [测试](#测试)64+- [用户](#用户)65+66+## 安装67+68+要安装 Gin 软件包,需要先安装 Go 并设置 Go 工作区。69+70+1. 下载并安装 gin:71+72+```sh73+$ go get -u github.com/gin-gonic/gin74+```75+76+2. 将 gin 引入到代码中:77+78+```go79+import "github.com/gin-gonic/gin"80+```81+82+3. (可选)如果使用诸如`http.StatusOK`之类的常量,则需要引入 `net / http` 包。83+84+```go85+import "net/http"86+```87+88+### 使用 [Govendor](https://github.com/kardianos/govendor) 工具创建项目89+90+1. `go get` govendor91+92+```sh93+$ go get github.com/kardianos/govendor94+```95+2.创建项目并且 `cd` 到项目目录中96+97+```sh98+$ mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"99+```100+101+3. 使用 govendor 初始化项目,并且引入gin102+103+```sh104+$ govendor init105+$ govendor fetch github.com/gin-gonic/gin@v1.3106+```107+108+4. 复制一个启动文件模板到项目目录中109+110+```sh111+$ curl https://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go > main.go112+```113+114+5.启动项目115+116+```sh117+$ go run main.go118+```119+120+## 前提条件121+122+新版本的 Gin 需要 Go 1.6 或者更高版本并且很快就会升级到 Go 1.7.123+124+## 快速启动125+ 126+```sh127+# assume the following codes in example.go file128+$ cat example.go129+```130+131+```go132+package main133+134+import "github.com/gin-gonic/gin"135+136+func main() {137+ r := gin.Default()138+ r.GET("/ping", func(c *gin.Context) {139+ c.JSON(200, gin.H{140+ "message": "pong",141+ })142+ })143+ r.Run() // listen and serve on 0.0.0.0:8080144+}145+```146+147+```148+# run example.go and visit 0.0.0.0:8080/ping on browser149+$ go run example.go150+```151+152+## 性能测试153+154+Gin 使用自定义版本的 [HttpRouter](https://github.com/julienschmidt/httprouter)155+156+[所有性能测试](/BENCHMARKS.md)157+158+Benchmark name | (1) | (2) | (3) | (4)159+--------------------------------------------|-----------:|------------:|-----------:|---------:160+**BenchmarkGin_GithubAll** | **30000** | **48375** | **0** | **0**161+BenchmarkAce_GithubAll | 10000 | 134059 | 13792 | 167162+BenchmarkBear_GithubAll | 5000 | 534445 | 86448 | 943163+BenchmarkBeego_GithubAll | 3000 | 592444 | 74705 | 812164+BenchmarkBone_GithubAll | 200 | 6957308 | 698784 | 8453165+BenchmarkDenco_GithubAll | 10000 | 158819 | 20224 | 167166+BenchmarkEcho_GithubAll | 10000 | 154700 | 6496 | 203167+BenchmarkGocraftWeb_GithubAll | 3000 | 570806 | 131656 | 1686168+BenchmarkGoji_GithubAll | 2000 | 818034 | 56112 | 334169+BenchmarkGojiv2_GithubAll | 2000 | 1213973 | 274768 | 3712170+BenchmarkGoJsonRest_GithubAll | 2000 | 785796 | 134371 | 2737171+BenchmarkGoRestful_GithubAll | 300 | 5238188 | 689672 | 4519172+BenchmarkGorillaMux_GithubAll | 100 | 10257726 | 211840 | 2272173+BenchmarkHttpRouter_GithubAll | 20000 | 105414 | 13792 | 167174+BenchmarkHttpTreeMux_GithubAll | 10000 | 319934 | 65856 | 671175+BenchmarkKocha_GithubAll | 10000 | 209442 | 23304 | 843176+BenchmarkLARS_GithubAll | 20000 | 62565 | 0 | 0177+BenchmarkMacaron_GithubAll | 2000 | 1161270 | 204194 | 2000178+BenchmarkMartini_GithubAll | 200 | 9991713 | 226549 | 2325179+BenchmarkPat_GithubAll | 200 | 5590793 | 1499568 | 27435180+BenchmarkPossum_GithubAll | 10000 | 319768 | 84448 | 609181+BenchmarkR2router_GithubAll | 10000 | 305134 | 77328 | 979182+BenchmarkRivet_GithubAll | 10000 | 132134 | 16272 | 167183+BenchmarkTango_GithubAll | 3000 | 552754 | 63826 | 1618184+BenchmarkTigerTonic_GithubAll | 1000 | 1439483 | 239104 | 5374185+BenchmarkTraffic_GithubAll | 100 | 11383067 | 2659329 | 21848186+BenchmarkVulcan_GithubAll | 5000 | 394253 | 19894 | 609187+188+- (1): 在不断的时间内实现总重复,更高意味着更自信的结果189+- (2): 单次重复持续时间(ns / op),越低越好190+- (3): 堆内存(B / op),越低越好191+- (4): 每次重复的平均分配(allocs / op)越低越好192+193+## Gin v1 稳定版194+195+- [x] 零分配路由器。196+- [x] 仍然是最快的http路由器和框架。197+- [x] 完整的单元测试套件198+- [x] 对战测试199+- [x] API冻结,新版本不会破坏您的代码。200+201+## 使用 [jsoniter](https://github.com/json-iterator/go) 构建202+203+Gin使用`encoding / json`作为默认的json包,但您可以通过其他标签的构建更改为[jsoniter](https://github.com/json-iterator/go)。204+205+```sh206+$ go build -tags=jsoniter .207+```208+209+## API 示例210+211+### GET, POST, PUT, PATCH, DELETE , OPTIONS 使用212+213+```go214+func main() {215+ // Disable Console Color216+ // gin.DisableConsoleColor()217+218+ // Creates a gin router with default middleware:219+ // logger and recovery (crash-free) middleware220+ router := gin.Default()221+222+ router.GET("/someGet", getting)223+ router.POST("/somePost", posting)224+ router.PUT("/somePut", putting)225+ router.DELETE("/someDelete", deleting)226+ router.PATCH("/somePatch", patching)227+ router.HEAD("/someHead", head)228+ router.OPTIONS("/someOptions", options)229+230+ // By default it serves on :8080 unless a231+ // PORT environment variable was defined.232+ router.Run()233+ // router.Run(":3000") for a hard coded port234+}235+```236+237+### 路由参数238+239+```go240+func main() {241+ router := gin.Default()242+243+ // This handler will match /user/john but will not match /user/ or /user244+ router.GET("/user/:name", func(c *gin.Context) {245+ name := c.Param("name")246+ c.String(http.StatusOK, "Hello %s", name)247+ })248+249+ // However, this one will match /user/john/ and also /user/john/send250+ // If no other routers match /user/john, it will redirect to /user/john/251+ router.GET("/user/:name/*action", func(c *gin.Context) {252+ name := c.Param("name")253+ action := c.Param("action")254+ message := name + " is " + action255+ c.String(http.StatusOK, message)256+ })257+258+ router.Run(":8080")259+}260+```261+262+### 查询字符串参数263+264+```go265+func main() {266+ router := gin.Default()267+268+ // Query string parameters are parsed using the existing underlying request object.269+ // The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe270+ router.GET("/welcome", func(c *gin.Context) {271+ firstname := c.DefaultQuery("firstname", "Guest")272+ lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")273+274+ c.String(http.StatusOK, "Hello %s %s", firstname, lastname)275+ })276+ router.Run(":8080")277+}278+```279+280+### Multipart Urlencoded 表单281+282+```go283+func main() {284+ router := gin.Default()285+286+ router.POST("/form_post", func(c *gin.Context) {287+ message := c.PostForm("message")288+ nick := c.DefaultPostForm("nick", "anonymous")289+290+ c.JSON(200, gin.H{291+ "status": "posted",292+ "message": message,293+ "nick": nick,294+ })295+ })296+ router.Run(":8080")297+}298+```299+300+### 另一个实列 query + post form301+302+```303+POST /post?id=1234&page=1 HTTP/1.1304+Content-Type: application/x-www-form-urlencoded305+306+name=manu&message=this_is_great307+```308+309+```go310+func main() {311+ router := gin.Default()312+313+ router.POST("/post", func(c *gin.Context) {314+315+ id := c.Query("id")316+ page := c.DefaultQuery("page", "0")317+ name := c.PostForm("name")318+ message := c.PostForm("message")319+320+ fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)321+ })322+ router.Run(":8080")323+}324+```325+326+```327+id: 1234; page: 1; name: manu; message: this_is_great328+```329+330+### 映射参数 表单参数331+332+```333+POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1334+Content-Type: application/x-www-form-urlencoded335+336+names[first]=thinkerou&names[second]=tianou337+```338+339+```go340+func main() {341+ router := gin.Default()342+343+ router.POST("/post", func(c *gin.Context) {344+345+ ids := c.QueryMap("ids")346+ names := c.PostFormMap("names")347+348+ fmt.Printf("ids: %v; names: %v", ids, names)349+ })350+ router.Run(":8080")351+}352+```353+354+```355+ids: map[b:hello a:1234], names: map[second:tianou first:thinkerou]356+```357+358+### 上传文件359+360+#### 单个文件上传361+362+参考问题[#774](https://github.com/gin-gonic/gin/issues/774)和详细[示例代码](examples / upload-file / single)。363+364+```go365+func main() {366+ router := gin.Default()367+ // Set a lower memory limit for multipart forms (default is 32 MiB)368+ // router.MaxMultipartMemory = 8 << 20 // 8 MiB369+ router.POST("/upload", func(c *gin.Context) {370+ // single file371+ file, _ := c.FormFile("file")372+ log.Println(file.Filename)373+374+ // Upload the file to specific dst.375+ // c.SaveUploadedFile(file, dst)376+377+ c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))378+ })379+ router.Run(":8080")380+}381+```382+383+如何 `curl`:384+385+```bash386+curl -X POST http://localhost:8080/upload \387+ -F "file=@/Users/appleboy/test.zip" \388+ -H "Content-Type: multipart/form-data"389+```390+391+#### 多文件上传392+393+查看详细信息[示例代码](examples / upload-file / multiple)。394+395+```go396+func main() {397+ router := gin.Default()398+ // Set a lower memory limit for multipart forms (default is 32 MiB)399+ // router.MaxMultipartMemory = 8 << 20 // 8 MiB400+ router.POST("/upload", func(c *gin.Context) {401+ // Multipart form402+ form, _ := c.MultipartForm()403+ files := form.File["upload[]"]404+405+ for _, file := range files {406+ log.Println(file.Filename)407+408+ // Upload the file to specific dst.409+ // c.SaveUploadedFile(file, dst)410+ }411+ c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))412+ })413+ router.Run(":8080")414+}415+```416+417+如何 `curl`:418+419+```bash420+curl -X POST http://localhost:8080/upload \421+ -F "upload[]=@/Users/appleboy/test1.zip" \422+ -F "upload[]=@/Users/appleboy/test2.zip" \423+ -H "Content-Type: multipart/form-data"424+```425+426+### 路由组427+428+```go429+func main() {430+ router := gin.Default()431+432+ // Simple group: v1433+ v1 := router.Group("/v1")434+ {435+ v1.POST("/login", loginEndpoint)436+ v1.POST("/submit", submitEndpoint)437+ v1.POST("/read", readEndpoint)438+ }439+440+ // Simple group: v2441+ v2 := router.Group("/v2")442+ {443+ v2.POST("/login", loginEndpoint)444+ v2.POST("/submit", submitEndpoint)445+ v2.POST("/read", readEndpoint)446+ }447+448+ router.Run(":8080")449+}450+```451+452+### 默认初始化 Gin453+454+用455+456+```go457+r := gin.New()458+```459+460+代替461+462+```go463+// Default With the Logger and Recovery middleware already attached464+r := gin.Default()465+```466+467+468+### 中间件使用469+```go470+func main() {471+ // Creates a router without any middleware by default472+ r := gin.New()473+474+ // Global middleware475+ // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.476+ // By default gin.DefaultWriter = os.Stdout477+ r.Use(gin.Logger())478+479+ // Recovery middleware recovers from any panics and writes a 500 if there was one.480+ r.Use(gin.Recovery())481+482+ // Per route middleware, you can add as many as you desire.483+ r.GET("/benchmark", MyBenchLogger(), benchEndpoint)484+485+ // Authorization group486+ // authorized := r.Group("/", AuthRequired())487+ // exactly the same as:488+ authorized := r.Group("/")489+ // per group middleware! in this case we use the custom created490+ // AuthRequired() middleware just in the "authorized" group.491+ authorized.Use(AuthRequired())492+ {493+ authorized.POST("/login", loginEndpoint)494+ authorized.POST("/submit", submitEndpoint)495+ authorized.POST("/read", readEndpoint)496+497+ // nested group498+ testing := authorized.Group("testing")499+ testing.GET("/analytics", analyticsEndpoint)500+ }501+502+ // Listen and serve on 0.0.0.0:8080503+ r.Run(":8080")504+}505+```506+507+### 如何记录日志508+```go509+func main() {510+ // Disable Console Color, you don't need console color when writing the logs to file.511+ gin.DisableConsoleColor()512+513+ // Logging to a file.514+ f, _ := os.Create("gin.log")515+ gin.DefaultWriter = io.MultiWriter(f)516+517+ // Use the following code if you need to write the logs to file and console at the same time.518+ // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)519+520+ router := gin.Default()521+ router.GET("/ping", func(c *gin.Context) {522+ c.String(200, "pong")523+ })524+525+ router.Run(":8080")526+}527+```528+529+### 模型绑定和验证530+531+要将请求主体绑定到类型中,请使用模型绑定。我们目前支持JSON,XML和标准表单值的绑定(foo = bar&boo = baz)。532+533+Gin使用[** go-playground / validator.v8 **](https://github.com/go-playground/validator)进行验证。检查有关标签用法的完整文档[此处](http://godoc.org/gopkg.in/go-playground/validator.v8#hdr-Baked_In_Validators_and_Tags)。534+535+请注意,您需要在要绑定的所有字段上设置相应的绑定标记。例如,从JSON绑定时,设置`json:“fieldname”`。536+537+此外,Gin提供了两组绑定方法:538+- **类型** - 必须绑定539+ - **方法** - `Bind`,`BindJSON`,`BindXML`,`BindQuery`540+ - **行为** - 这些方法在引擎盖下使用`MustBindWith`。如果存在绑定错误,则使用`c.AbortWithError(400,err).SetType(ErrorTypeBind)`中止请求。这将响应状态代码设置为400,并将`Content-Type`标头设置为`text / plain;字符集= UTF-8`。请注意,如果您在此之后尝试设置响应代码,则会发出警告“[GIN-debug] [警告]标题已经写入。想用422`覆盖状态代码400。如果您希望更好地控制行为,请考虑使用`ShouldBind`等效方法。541+- **类型** - 应该绑定542+ - **方法** - `ShouldBind`,`ShouldBindJSON`,`ShouldBindXML`,`ShouldBindQuery`543+ - **行为** - 这些方法在引擎盖下使用`ShouldBindWith`。如果存在绑定错误,则返回错误,开发人员有责任正确处理请求和错误。544+545+使用Bind方法时,Gin会尝试根据Content-Type标头推断出绑定器。如果你确定你绑定了什么,你可以使用 `MustBindWith` 或 `ShouldBindWith`。546+547+您还可以指定需要特定字段。如果字段用 `binding:“必需”` 来装饰,并且在绑定时具有空值,则会返回错误。548+549+```go550+// Binding from JSON551+type Login struct {552+ User string `form:"user" json:"user" xml:"user" binding:"required"`553+ Password string `form:"password" json:"password" xml:"password" binding:"required"`554+}555+556+func main() {557+ router := gin.Default()558+559+ // Example for binding JSON ({"user": "manu", "password": "123"})560+ router.POST("/loginJSON", func(c *gin.Context) {561+ var json Login562+ if err := c.ShouldBindJSON(&json); err != nil {563+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})564+ return565+ }566+ 567+ if json.User != "manu" || json.Password != "123" {568+ c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})569+ return570+ } 571+ 572+ c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})573+ })574+575+ // Example for binding XML (576+ // <?xml version="1.0" encoding="UTF-8"?>577+ // <root>578+ // <user>user</user>579+ // <password>123</user>580+ // </root>)581+ router.POST("/loginXML", func(c *gin.Context) {582+ var xml Login583+ if err := c.ShouldBindXML(&xml); err != nil {584+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})585+ return586+ }587+ 588+ if xml.User != "manu" || xml.Password != "123" {589+ c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})590+ return591+ } 592+ 593+ c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})594+ })595+596+ // Example for binding a HTML form (user=manu&password=123)597+ router.POST("/loginForm", func(c *gin.Context) {598+ var form Login599+ // This will infer what binder to use depending on the content-type header.600+ if err := c.ShouldBind(&form); err != nil {601+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})602+ return603+ }604+ 605+ if form.User != "manu" || form.Password != "123" {606+ c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})607+ return608+ } 609+ 610+ c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})611+ })612+613+ // Listen and serve on 0.0.0.0:8080614+ router.Run(":8080")615+}616+```617+618+**简单请求**619+```shell620+$ curl -v -X POST \621+ http://localhost:8080/loginJSON \622+ -H 'content-type: application/json' \623+ -d '{ "user": "manu" }'624+> POST /loginJSON HTTP/1.1625+> Host: localhost:8080626+> User-Agent: curl/7.51.0627+> Accept: */*628+> content-type: application/json629+> Content-Length: 18630+>631+* upload completely sent off: 18 out of 18 bytes632+< HTTP/1.1 400 Bad Request633+< Content-Type: application/json; charset=utf-8634+< Date: Fri, 04 Aug 2017 03:51:31 GMT635+< Content-Length: 100636+<637+{"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}638+```639+640+**跳过验证**641+642+使用上面 的`curl` 命令运行上面的例子时,它返回错误。 因为这个例子使用 `binding:'需要``````。 如果使用 `binding:“ - ``````,那么在再次运行上面的例子时它不会返回错误。643+644+### 自定义验证器645+646+也可以注册自定义验证器。 请参阅[示例代码](examples / custom-validation / server.go)。647+648+[embedmd]:#(examples / custom-validation / server.go go)649+```go650+package main651+652+import (653+ "net/http"654+ "reflect"655+ "time"656+657+ "github.com/gin-gonic/gin"658+ "github.com/gin-gonic/gin/binding"659+ "gopkg.in/go-playground/validator.v8"660+)661+662+// Booking contains binded and validated data.663+type Booking struct {664+ CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`665+ CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`666+}667+668+func bookableDate(669+ v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,670+ field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,671+) bool {672+ if date, ok := field.Interface().(time.Time); ok {673+ today := time.Now()674+ if today.Year() > date.Year() || today.YearDay() > date.YearDay() {675+ return false676+ }677+ }678+ return true679+}680+681+func main() {682+ route := gin.Default()683+684+ if v, ok := binding.Validator.Engine().(*validator.Validate); ok {685+ v.RegisterValidation("bookabledate", bookableDate)686+ }687+688+ route.GET("/bookable", getBookable)689+ route.Run(":8085")690+}691+692+func getBookable(c *gin.Context) {693+ var b Booking694+ if err := c.ShouldBindWith(&b, binding.Query); err == nil {695+ c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})696+ } else {697+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})698+ }699+}700+```701+702+```console703+$ curl "localhost:8085/bookable?check_in=2018-04-16&check_out=2018-04-17"704+{"message":"Booking dates are valid!"}705+706+$ curl "localhost:8085/bookable?check_in=2018-03-08&check_out=2018-03-09"707+{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}708+```709+710+[结构级验证](https://github.com/go-playground/validator/releases/tag/v8.7)也可以这种方式注册。711+请参阅[struct-lvl-validation示例](examples / struct-lvl-validations)以了解更多信息。712+713+### 只绑定查询字符串714+715+`ShouldBindQuery` 函数只绑定查询参数而不是后期数据。 请参阅[详细信息](https://github.com/gin-gonic/gin/issues/742#issuecomment-315953017)。716+717+```go718+package main719+720+import (721+ "log"722+723+ "github.com/gin-gonic/gin"724+)725+726+type Person struct {727+ Name string `form:"name"`728+ Address string `form:"address"`729+}730+731+func main() {732+ route := gin.Default()733+ route.Any("/testing", startPage)734+ route.Run(":8085")735+}736+737+func startPage(c *gin.Context) {738+ var person Person739+ if c.ShouldBindQuery(&person) == nil {740+ log.Println("====== Only Bind By Query String ======")741+ log.Println(person.Name)742+ log.Println(person.Address)743+ }744+ c.String(200, "Success")745+}746+747+```748+749+### 绑定查询字符串或发布数据750+751+请参阅[详细信息](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292)。752+753+```go754+package main755+756+import (757+ "log"758+ "time"759+760+ "github.com/gin-gonic/gin"761+)762+763+type Person struct {764+ Name string `form:"name"`765+ Address string `form:"address"`766+ Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`767+}768+769+func main() {770+ route := gin.Default()771+ route.GET("/testing", startPage)772+ route.Run(":8085")773+}774+775+func startPage(c *gin.Context) {776+ var person Person777+ // If `GET`, only `Form` binding engine (`query`) used.778+ // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).779+ // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48780+ if c.ShouldBind(&person) == nil {781+ log.Println(person.Name)782+ log.Println(person.Address)783+ log.Println(person.Birthday)784+ }785+786+ c.String(200, "Success")787+}788+```789+790+测试:791+```sh792+$ curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15"793+```794+795+### 绑定 HTML 复选框796+797+参见[详细信息](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)798+799+main.go800+801+```go802+...803+804+type myForm struct {805+ Colors []string `form:"colors[]"`806+}807+808+...809+810+func formHandler(c *gin.Context) {811+ var fakeForm myForm812+ c.ShouldBind(&fakeForm)813+ c.JSON(200, gin.H{"color": fakeForm.Colors})814+}815+816+...817+818+```819+820+form.html821+822+```html823+<form action="/" method="POST">824+ <p>Check some colors</p>825+ <label for="red">Red</label>826+ <input type="checkbox" name="colors[]" value="red" id="red" />827+ <label for="green">Green</label>828+ <input type="checkbox" name="colors[]" value="green" id="green" />829+ <label for="blue">Blue</label>830+ <input type="checkbox" name="colors[]" value="blue" id="blue" />831+ <input type="submit" />832+</form>833+```834+835+result:836+837+```838+{"color":["red","green","blue"]}839+```840+841+### Multipart Urlencoded 绑定842+843+```go844+package main845+846+import (847+ "github.com/gin-gonic/gin"848+)849+850+type LoginForm struct {851+ User string `form:"user" binding:"required"`852+ Password string `form:"password" binding:"required"`853+}854+855+func main() {856+ router := gin.Default()857+ router.POST("/login", func(c *gin.Context) {858+ // you can bind multipart form with explicit binding declaration:859+ // c.ShouldBindWith(&form, binding.Form)860+ // or you can simply use autobinding with ShouldBind method:861+ var form LoginForm862+ // in this case proper binding will be automatically selected863+ if c.ShouldBind(&form) == nil {864+ if form.User == "user" && form.Password == "password" {865+ c.JSON(200, gin.H{"status": "you are logged in"})866+ } else {867+ c.JSON(401, gin.H{"status": "unauthorized"})868+ }869+ }870+ })871+ router.Run(":8080")872+}873+```874+875+Test it with:876+```sh877+$ curl -v --form user=user --form password=password http://localhost:8080/login878+```879+880+### XML JSON YAML ProtoBuf 渲染881+882+```go883+func main() {884+ r := gin.Default()885+886+ // gin.H is a shortcut for map[string]interface{}887+ r.GET("/someJSON", func(c *gin.Context) {888+ c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})889+ })890+891+ r.GET("/moreJSON", func(c *gin.Context) {892+ // You also can use a struct893+ var msg struct {894+ Name string `json:"user"`895+ Message string896+ Number int897+ }898+ msg.Name = "Lena"899+ msg.Message = "hey"900+ msg.Number = 123901+ // Note that msg.Name becomes "user" in the JSON902+ // Will output : {"user": "Lena", "Message": "hey", "Number": 123}903+ c.JSON(http.StatusOK, msg)904+ })905+906+ r.GET("/someXML", func(c *gin.Context) {907+ c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})908+ })909+910+ r.GET("/someYAML", func(c *gin.Context) {911+ c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})912+ })913+914+ r.GET("/someProtoBuf", func(c *gin.Context) {915+ reps := []int64{int64(1), int64(2)}916+ label := "test"917+ // The specific definition of protobuf is written in the testdata/protoexample file.918+ data := &protoexample.Test{919+ Label: &label,920+ Reps: reps,921+ }922+ // Note that data becomes binary data in the response923+ // Will output protoexample.Test protobuf serialized data924+ c.ProtoBuf(http.StatusOK, data)925+ })926+927+ // Listen and serve on 0.0.0.0:8080928+ r.Run(":8080")929+}930+```931+932+#### SecureJSON933+934+使用 SecureJSON 来防止 json 劫持。 如果给定的结构是数组值,则默认预 置`“while(1),”` 到响应体。935+936+```go937+func main() {938+ r := gin.Default()939+940+ // You can also use your own secure json prefix941+ // r.SecureJsonPrefix(")]}',\n")942+943+ r.GET("/someJSON", func(c *gin.Context) {944+ names := []string{"lena", "austin", "foo"}945+946+ // Will output : while(1);["lena","austin","foo"]947+ c.SecureJSON(http.StatusOK, names)948+ })949+950+ // Listen and serve on 0.0.0.0:8080951+ r.Run(":8080")952+}953+```954+#### JSONP955+956+使用 JSONP 从不同域中的服务器请求数据。 如果查询参数回调存在,则将回调添加到响应正文。957+958+```go959+func main() {960+ r := gin.Default()961+962+ r.GET("/JSONP?callback=x", func(c *gin.Context) {963+ data := map[string]interface{}{964+ "foo": "bar",965+ }966+ 967+ //callback is x968+ // Will output : x({\"foo\":\"bar\"})969+ c.JSONP(http.StatusOK, data)970+ })971+972+ // Listen and serve on 0.0.0.0:8080973+ r.Run(":8080")974+}975+```976+977+#### AsciiJSON978+979+使用 Ascii JSON 生成具有转义的非 ASCII 字符的仅 ASCII JSON。980+981+```go982+func main() {983+ r := gin.Default()984+985+ r.GET("/someJSON", func(c *gin.Context) {986+ data := map[string]interface{}{987+ "lang": "GO语言",988+ "tag": "<br>",989+ }990+991+ // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}992+ c.AsciiJSON(http.StatusOK, data)993+ })994+995+ // Listen and serve on 0.0.0.0:8080996+ r.Run(":8080")997+}998+```999+1000+#### PureJSON1001+1002+通常,JSON 用其 unicod e实体替换特殊 HTML 字符,例如 `<` 变为 `\ u003c`。 如果要按字面意思对这些字符进行编码,则可以使用 PureJSON。1003+Go 1.6 及更低版本无法使用此功能。1004+1005+```go1006+func main() {1007+ r := gin.Default()1008+ 1009+ // Serves unicode entities1010+ r.GET("/json", func(c *gin.Context) {1011+ c.JSON(200, gin.H{1012+ "html": "<b>Hello, world!</b>",1013+ })1014+ })1015+ 1016+ // Serves literal characters1017+ r.GET("/purejson", func(c *gin.Context) {1018+ c.PureJSON(200, gin.H{1019+ "html": "<b>Hello, world!</b>",1020+ })1021+ })1022+ 1023+ // listen and serve on 0.0.0.0:80801024+ r.Run(":8080)1025+}1026+```1027+1028+### 静态文件服务1029+1030+```go1031+func main() {1032+ router := gin.Default()1033+ router.Static("/assets", "./assets")1034+ router.StaticFS("/more_static", http.Dir("my_file_system"))1035+ router.StaticFile("/favicon.ico", "./resources/favicon.ico")1036+1037+ // Listen and serve on 0.0.0.0:80801038+ router.Run(":8080")1039+}1040+```1041+1042+### 从 reader 读取数据1043+1044+```go1045+func main() {1046+ router := gin.Default()1047+ router.GET("/someDataFromReader", func(c *gin.Context) {1048+ response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")1049+ if err != nil || response.StatusCode != http.StatusOK {1050+ c.Status(http.StatusServiceUnavailable)1051+ return1052+ }1053+1054+ reader := response.Body1055+ contentLength := response.ContentLength1056+ contentType := response.Header.Get("Content-Type")1057+1058+ extraHeaders := map[string]string{1059+ "Content-Disposition": `attachment; filename="gopher.png"`,1060+ }1061+1062+ c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)1063+ })1064+ router.Run(":8080")1065+}1066+```1067+1068+### HTML 渲染1069+1070+使用LoadHTMLGlob()或LoadHTMLFiles()1071+1072+```go1073+func main() {1074+ router := gin.Default()1075+ router.LoadHTMLGlob("templates/*")1076+ //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")1077+ router.GET("/index", func(c *gin.Context) {1078+ c.HTML(http.StatusOK, "index.tmpl", gin.H{1079+ "title": "Main website",1080+ })1081+ })1082+ router.Run(":8080")1083+}1084+```1085+1086+templates/index.tmpl1087+1088+```html1089+<html>1090+ <h1>1091+ {{ .title }}1092+ </h1>1093+</html>1094+```1095+1096+在不同目录中使用具有相同名称的模板1097+1098+```go1099+func main() {1100+ router := gin.Default()1101+ router.LoadHTMLGlob("templates/**/*")1102+ router.GET("/posts/index", func(c *gin.Context) {1103+ c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{1104+ "title": "Posts",1105+ })1106+ })1107+ router.GET("/users/index", func(c *gin.Context) {1108+ c.HTML(http.StatusOK, "users/index.tmpl", gin.H{1109+ "title": "Users",1110+ })1111+ })1112+ router.Run(":8080")1113+}1114+```1115+1116+templates/posts/index.tmpl1117+1118+```html1119+{{ define "posts/index.tmpl" }}1120+<html><h1>1121+ {{ .title }}1122+</h1>1123+<p>Using posts/index.tmpl</p>1124+</html>1125+{{ end }}1126+```1127+1128+templates/users/index.tmpl1129+1130+```html1131+{{ define "users/index.tmpl" }}1132+<html><h1>1133+ {{ .title }}1134+</h1>1135+<p>Using users/index.tmpl</p>1136+</html>1137+{{ end }}1138+```1139+1140+#### 自定义模板渲染器1141+1142+您还可以使用自己的 html 模板渲染1143+1144+```go1145+import "html/template"1146+1147+func main() {1148+ router := gin.Default()1149+ html := template.Must(template.ParseFiles("file1", "file2"))1150+ router.SetHTMLTemplate(html)1151+ router.Run(":8080")1152+}1153+```1154+1155+#### 自定义分隔符1156+1157+您可以使用自定义分隔1158+1159+```go1160+ r := gin.Default()1161+ r.Delims("{[{", "}]}")1162+ r.LoadHTMLGlob("/path/to/templates"))1163+```1164+1165+#### 自定义模板功能1166+1167+查看详细信息[示例代码](示例/模板)。1168+1169+main.go1170+1171+```go1172+import (1173+ "fmt"1174+ "html/template"1175+ "net/http"1176+ "time"1177+1178+ "github.com/gin-gonic/gin"1179+)1180+1181+func formatAsDate(t time.Time) string {1182+ year, month, day := t.Date()1183+ return fmt.Sprintf("%d%02d/%02d", year, month, day)1184+}1185+1186+func main() {1187+ router := gin.Default()1188+ router.Delims("{[{", "}]}")1189+ router.SetFuncMap(template.FuncMap{1190+ "formatAsDate": formatAsDate,1191+ })1192+ router.LoadHTMLFiles("./testdata/template/raw.tmpl")1193+1194+ router.GET("/raw", func(c *gin.Context) {1195+ c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{1196+ "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),1197+ })1198+ })1199+1200+ router.Run(":8080")1201+}1202+1203+```1204+1205+raw.tmpl1206+1207+```html1208+日期: {[{.now | formatAsDate}]}1209+```1210+1211+结果:1212+```1213+Date: 2017/07/011214+```1215+1216+### 多模板1217+1218+Gin 允许默认只使用一个 html 模板。 检查[多模板渲染](https://github.com/gin-contrib/multitemplate)以使用 go 1.6 `block template` 等功能。1219+1220+### 重定向1221+1222+Issuing a HTTP redirect is easy. Both internal and external locations are supported.1223+1224+```go1225+r.GET("/test", func(c *gin.Context) {1226+ c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")1227+})1228+```1229+1230+1231+发出路由器重定向,使用如下的“HandleContext”。1232+1233+``` go1234+r.GET("/test", func(c *gin.Context) {1235+ c.Request.URL.Path = "/test2"1236+ r.HandleContext(c)1237+})1238+r.GET("/test2", func(c *gin.Context) {1239+ c.JSON(200, gin.H{"hello": "world"})1240+})1241+```1242+1243+1244+### 自定义中间件1245+1246+```go1247+func Logger() gin.HandlerFunc {1248+ return func(c *gin.Context) {1249+ t := time.Now()1250+1251+ // Set example variable1252+ c.Set("example", "12345")1253+1254+ // before request1255+1256+ c.Next()1257+1258+ // after request1259+ latency := time.Since(t)1260+ log.Print(latency)1261+1262+ // access the status we are sending1263+ status := c.Writer.Status()1264+ log.Println(status)1265+ }1266+}1267+1268+func main() {1269+ r := gin.New()1270+ r.Use(Logger())1271+1272+ r.GET("/test", func(c *gin.Context) {1273+ example := c.MustGet("example").(string)1274+1275+ // it would print: "12345"1276+ log.Println(example)1277+ })1278+1279+ // Listen and serve on 0.0.0.0:80801280+ r.Run(":8080")1281+}1282+```1283+1284+### BasicAuth() 中间件1285+1286+```go1287+// simulate some private data1288+var secrets = gin.H{1289+ "foo": gin.H{"email": "foo@bar.com", "phone": "123433"},1290+ "austin": gin.H{"email": "austin@example.com", "phone": "666"},1291+ "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},1292+}1293+1294+func main() {1295+ r := gin.Default()1296+1297+ // Group using gin.BasicAuth() middleware1298+ // gin.Accounts is a shortcut for map[string]string1299+ authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{1300+ "foo": "bar",1301+ "austin": "1234",1302+ "lena": "hello2",1303+ "manu": "4321",1304+ }))1305+1306+ // /admin/secrets endpoint1307+ // hit "localhost:8080/admin/secrets1308+ authorized.GET("/secrets", func(c *gin.Context) {1309+ // get user, it was set by the BasicAuth middleware1310+ user := c.MustGet(gin.AuthUserKey).(string)1311+ if secret, ok := secrets[user]; ok {1312+ c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})1313+ } else {1314+ c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})1315+ }1316+ })1317+1318+ // Listen and serve on 0.0.0.0:80801319+ r.Run(":8080")1320+}1321+```1322+1323+### Goroutines1324+1325+当在中间件或处理程序中启动新的 Goroutines 时,你不应该**使用其中的原始上下文,你必须使用只读副本。1326+1327+```go1328+func main() {1329+ r := gin.Default()1330+1331+ r.GET("/long_async", func(c *gin.Context) {1332+ // create copy to be used inside the goroutine1333+ cCp := c.Copy()1334+ go func() {1335+ // simulate a long task with time.Sleep(). 5 seconds1336+ time.Sleep(5 * time.Second)1337+1338+ // note that you are using the copied context "cCp", IMPORTANT1339+ log.Println("Done! in path " + cCp.Request.URL.Path)1340+ }()1341+ })1342+1343+ r.GET("/long_sync", func(c *gin.Context) {1344+ // simulate a long task with time.Sleep(). 5 seconds1345+ time.Sleep(5 * time.Second)1346+1347+ // since we are NOT using a goroutine, we do not have to copy the context1348+ log.Println("Done! in path " + c.Request.URL.Path)1349+ })1350+1351+ // Listen and serve on 0.0.0.0:80801352+ r.Run(":8080")1353+}1354+```1355+1356+### 自定义 HTTP 配置1357+1358+直接使用`http.ListenAndServe()`,如下所示:1359+1360+```go1361+func main() {1362+ router := gin.Default()1363+ http.ListenAndServe(":8080", router)1364+}1365+```1366+or1367+1368+```go1369+func main() {1370+ router := gin.Default()1371+1372+ s := &http.Server{1373+ Addr: ":8080",1374+ Handler: router,1375+ ReadTimeout: 10 * time.Second,1376+ WriteTimeout: 10 * time.Second,1377+ MaxHeaderBytes: 1 << 20,1378+ }1379+ s.ListenAndServe()1380+}1381+```1382+1383+### Let's Encrypt 支持1384+1385+单行 LetsEncrypt HTTPS 服务器的示例。1386+1387+[embedmd]:# (examples/auto-tls/example1/main.go go)1388+```go1389+package main1390+1391+import (1392+ "log"1393+1394+ "github.com/gin-gonic/autotls"1395+ "github.com/gin-gonic/gin"1396+)1397+1398+func main() {1399+ r := gin.Default()1400+1401+ // Ping handler1402+ r.GET("/ping", func(c *gin.Context) {1403+ c.String(200, "pong")1404+ })1405+1406+ log.Fatal(autotls.Run(r, "example1.com", "example2.com"))1407+}1408+```1409+1410+自定义autocert管理器的示例。1411+1412+[embedmd]:# (examples/auto-tls/example2/main.go go)1413+```go1414+package main1415+1416+import (1417+ "log"1418+1419+ "github.com/gin-gonic/autotls"1420+ "github.com/gin-gonic/gin"1421+ "golang.org/x/crypto/acme/autocert"1422+)1423+1424+func main() {1425+ r := gin.Default()1426+1427+ // Ping handler1428+ r.GET("/ping", func(c *gin.Context) {1429+ c.String(200, "pong")1430+ })1431+1432+ m := autocert.Manager{1433+ Prompt: autocert.AcceptTOS,1434+ HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),1435+ Cache: autocert.DirCache("/var/www/.cache"),1436+ }1437+1438+ log.Fatal(autotls.RunWithManager(r, &m))1439+}1440+```1441+1442+### 使用 Gin 运行多个服务1443+1444+请参阅[问题](https://github.com/gin-gonic/gin/issues/346)并尝试以下示例:1445+1446+[embedmd]:# (examples/multiple-service/main.go go)1447+```go1448+package main1449+1450+import (1451+ "log"1452+ "net/http"1453+ "time"1454+1455+ "github.com/gin-gonic/gin"1456+ "golang.org/x/sync/errgroup"1457+)1458+1459+var (1460+ g errgroup.Group1461+)1462+1463+func router01() http.Handler {1464+ e := gin.New()1465+ e.Use(gin.Recovery())1466+ e.GET("/", func(c *gin.Context) {1467+ c.JSON(1468+ http.StatusOK,1469+ gin.H{1470+ "code": http.StatusOK,1471+ "error": "Welcome server 01",1472+ },1473+ )1474+ })1475+1476+ return e1477+}1478+1479+func router02() http.Handler {1480+ e := gin.New()1481+ e.Use(gin.Recovery())1482+ e.GET("/", func(c *gin.Context) {1483+ c.JSON(1484+ http.StatusOK,1485+ gin.H{1486+ "code": http.StatusOK,1487+ "error": "Welcome server 02",1488+ },1489+ )1490+ })1491+1492+ return e1493+}1494+1495+func main() {1496+ server01 := &http.Server{1497+ Addr: ":8080",1498+ Handler: router01(),1499+ ReadTimeout: 5 * time.Second,1500+ WriteTimeout: 10 * time.Second,1501+ }1502+1503+ server02 := &http.Server{1504+ Addr: ":8081",1505+ Handler: router02(),1506+ ReadTimeout: 5 * time.Second,1507+ WriteTimeout: 10 * time.Second,1508+ }1509+1510+ g.Go(func() error {1511+ return server01.ListenAndServe()1512+ })1513+1514+ g.Go(func() error {1515+ return server02.ListenAndServe()1516+ })1517+1518+ if err := g.Wait(); err != nil {1519+ log.Fatal(err)1520+ }1521+}1522+```1523+1524+### 优雅重启或停止1525+1526+您想要优雅地重启或停止您的Web服务器吗?1527+有一些方法可以做到这一点。1528+1529+我们可以使用[fvbock / endless](https://github.com/fvbock/endless)来替换默认的`ListenAndServe`。 有关更多详细信息,请参阅问题[#296](https://github.com/gin-gonic/gin/issues/296)。1530+1531+```go1532+router := gin.Default()1533+router.GET("/", handler)1534+// [...]1535+endless.ListenAndServe(":4242", router)1536+```1537+1538+另一种替代方案:1539+1540+* [manners](https://github.com/braintree/manners):礼貌的Go HTTP服务器,可以正常关闭。1541+* [graceful](https://github.com/tylerb/graceful):Graceful是一个Go包,可以正常关闭http.Handler服务器。1542+* [grace](https://github.com/facebookgo/grace):Go服务器的平滑重启和零停机时间部署。1543+1544+如果您使用的是Go 1.8,则可能不需要使用此库! 考虑使用http.Server的内置[Shutdown()](https://golang.org/pkg/net/http/#Server.Shutdown)方法进行正常关机。 请参阅gin的完整[graceful-shutdown](./ examples / graceful-shutdown)示例。1545+1546+[embedmd]:# (examples/graceful-shutdown/graceful-shutdown/server.go go)1547+```go1548+// +build go1.81549+1550+package main1551+1552+import (1553+ "context"1554+ "log"1555+ "net/http"1556+ "os"1557+ "os/signal"1558+ "time"1559+1560+ "github.com/gin-gonic/gin"1561+)1562+1563+func main() {1564+ router := gin.Default()1565+ router.GET("/", func(c *gin.Context) {1566+ time.Sleep(5 * time.Second)1567+ c.String(http.StatusOK, "Welcome Gin Server")1568+ })1569+1570+ srv := &http.Server{1571+ Addr: ":8080",1572+ Handler: router,1573+ }1574+1575+ go func() {1576+ // service connections1577+ if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {1578+ log.Fatalf("listen: %s\n", err)1579+ }1580+ }()1581+1582+ // Wait for interrupt signal to gracefully shutdown the server with1583+ // a timeout of 5 seconds.1584+ quit := make(chan os.Signal)1585+ signal.Notify(quit, os.Interrupt)1586+ <-quit1587+ log.Println("Shutdown Server ...")1588+1589+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)1590+ defer cancel()1591+ if err := srv.Shutdown(ctx); err != nil {1592+ log.Fatal("Server Shutdown:", err)1593+ }1594+ log.Println("Server exiting")1595+}1596+```1597+1598+### 使用模板构建单个二进制文件1599+1600+您可以使用[go-assets] []将服务器构建到包含模板的单个二进制文件中。1601+1602+[go-assets]:https://github.com/jessevdk/go-assets1603+1604+```go1605+func main() {1606+ r := gin.New()1607+1608+ t, err := loadTemplate()1609+ if err != nil {1610+ panic(err)1611+ }1612+ r.SetHTMLTemplate(t)1613+1614+ r.GET("/", func(c *gin.Context) {1615+ c.HTML(http.StatusOK, "/html/index.tmpl",nil)1616+ })1617+ r.Run(":8080")1618+}1619+1620+// loadTemplate loads templates embedded by go-assets-builder1621+func loadTemplate() (*template.Template, error) {1622+ t := template.New("")1623+ for name, file := range Assets.Files {1624+ if file.IsDir() || !strings.HasSuffix(name, ".tmpl") {1625+ continue1626+ }1627+ h, err := ioutil.ReadAll(file)1628+ if err != nil {1629+ return nil, err1630+ }1631+ t, err = t.New(name).Parse(string(h))1632+ if err != nil {1633+ return nil, err1634+ }1635+ }1636+ return t, nil1637+}1638+```1639+1640+请参阅`examples / assets-in-binary`目录中的完整示例。1641+1642+### Bind form-data request with custom struct1643+1644+以下示例使用自定义结构:1645+1646+```go1647+type StructA struct {1648+ FieldA string `form:"field_a"`1649+}1650+1651+type StructB struct {1652+ NestedStruct StructA1653+ FieldB string `form:"field_b"`1654+}1655+1656+type StructC struct {1657+ NestedStructPointer *StructA1658+ FieldC string `form:"field_c"`1659+}1660+1661+type StructD struct {1662+ NestedAnonyStruct struct {1663+ FieldX string `form:"field_x"`1664+ }1665+ FieldD string `form:"field_d"`1666+}1667+1668+func GetDataB(c *gin.Context) {1669+ var b StructB1670+ c.Bind(&b)1671+ c.JSON(200, gin.H{1672+ "a": b.NestedStruct,1673+ "b": b.FieldB,1674+ })1675+}1676+1677+func GetDataC(c *gin.Context) {1678+ var b StructC1679+ c.Bind(&b)1680+ c.JSON(200, gin.H{1681+ "a": b.NestedStructPointer,1682+ "c": b.FieldC,1683+ })1684+}1685+1686+func GetDataD(c *gin.Context) {1687+ var b StructD1688+ c.Bind(&b)1689+ c.JSON(200, gin.H{1690+ "x": b.NestedAnonyStruct,1691+ "d": b.FieldD,1692+ })1693+}1694+1695+func main() {1696+ r := gin.Default()1697+ r.GET("/getb", GetDataB)1698+ r.GET("/getc", GetDataC)1699+ r.GET("/getd", GetDataD)1700+1701+ r.Run()1702+}1703+```1704+1705+使用命令`curl`命令结果:1706+1707+```1708+$ curl "http://localhost:8080/getb?field_a=hello&field_b=world"1709+{"a":{"FieldA":"hello"},"b":"world"}1710+$ curl "http://localhost:8080/getc?field_a=hello&field_c=world"1711+{"a":{"FieldA":"hello"},"c":"world"}1712+$ curl "http://localhost:8080/getd?field_x=hello&field_d=world"1713+{"d":"world","x":{"FieldX":"hello"}}1714+```1715+1716+**注意**:不支持以下样式结构:1717+1718+```go1719+type StructX struct {1720+ X struct {} `form:"name_x"` // HERE have form1721+}1722+1723+type StructY struct {1724+ Y StructX `form:"name_y"` // HERE have form1725+}1726+1727+type StructZ struct {1728+ Z *StructZ `form:"name_z"` // HERE have form1729+}1730+```1731+1732+总之,只支持现在没有`form`的嵌套自定义结构。1733+1734+### 尝试将 body 绑定到不同的结构中1735+1736+绑定请求体的常规方法使用`c.Request.Body`和它们1737+不能多次调用。1738+1739+```go1740+type formA struct {1741+ Foo string `json:"foo" xml:"foo" binding:"required"`1742+}1743+1744+type formB struct {1745+ Bar string `json:"bar" xml:"bar" binding:"required"`1746+}1747+1748+func SomeHandler(c *gin.Context) {1749+ objA := formA{}1750+ objB := formB{}1751+ // This c.ShouldBind consumes c.Request.Body and it cannot be reused.1752+ if errA := c.ShouldBind(&objA); errA == nil {1753+ c.String(http.StatusOK, `the body should be formA`)1754+ // Always an error is occurred by this because c.Request.Body is EOF now.1755+ } else if errB := c.ShouldBind(&objB); errB == nil {1756+ c.String(http.StatusOK, `the body should be formB`)1757+ } else {1758+ ...1759+ }1760+}1761+```1762+1763+为此,您可以使用`c.ShouldBindBodyWith`.1764+1765+```go1766+func SomeHandler(c *gin.Context) {1767+ objA := formA{}1768+ objB := formB{}1769+ // This reads c.Request.Body and stores the result into the context.1770+ if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil {1771+ c.String(http.StatusOK, `the body should be formA`)1772+ // At this time, it reuses body stored in the context.1773+ } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {1774+ c.String(http.StatusOK, `the body should be formB JSON`)1775+ // And it can accepts other formats1776+ } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {1777+ c.String(http.StatusOK, `the body should be formB XML`)1778+ } else {1779+ ...1780+ }1781+}1782+```1783+1784+1785+482/50001786+*`c.ShouldBindBodyWith`在绑定之前将body存储到上下文中。 这有1787+对性能有轻微影响,所以如果你这样做,你不应该使用这种方法1788+足以立刻调用绑定。1789+*只有某些格式需要此功能 - “JSON”,“XML”,“MsgPack”,1790+`ProtoBuf`。 对于其他格式,`Query`,`Form`,`FormPost`,`FormMultipart`,1791+可以被`c.ShouldBind()`多次调用而不会造成任何损害1792+表现(见[#1341](https://github.com/gin-gonic/gin/pull/1341))。1793+1794+### http2 server 推送1795+1796+1797+http.Pusher仅支持** go1.8 + **。 有关详细信息,请参阅[golang blog](https://blog.golang.org/h2push)。1798+1799+[embedmd]:# (examples/http-pusher/main.go go)1800+```go1801+package main1802+1803+import (1804+ "html/template"1805+ "log"1806+1807+ "github.com/gin-gonic/gin"1808+)1809+1810+var html = template.Must(template.New("https").Parse(`1811+<html>1812+<head>1813+ <title>Https Test</title>1814+ <script src="/assets/app.js"></script>1815+</head>1816+<body>1817+ <h1 style="color:red;">Welcome, Ginner!</h1>1818+</body>1819+</html>1820+`))1821+1822+func main() {1823+ r := gin.Default()1824+ r.Static("/assets", "./assets")1825+ r.SetHTMLTemplate(html)1826+1827+ r.GET("/", func(c *gin.Context) {1828+ if pusher := c.Writer.Pusher(); pusher != nil {1829+ // use pusher.Push() to do server push1830+ if err := pusher.Push("/assets/app.js", nil); err != nil {1831+ log.Printf("Failed to push: %v", err)1832+ }1833+ }1834+ c.HTML(200, "https", gin.H{1835+ "status": "success",1836+ })1837+ })1838+1839+ // Listen and Server in https://127.0.0.1:80801840+ r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")1841+}1842+```1843+1844+### 定义路由日志的格式1845+1846+路由的默认日志是:1847+```1848+[GIN-debug] POST /foo --> main.main.func1 (3 handlers)1849+[GIN-debug] GET /bar --> main.main.func2 (3 handlers)1850+[GIN-debug] GET /status --> main.main.func3 (3 handlers)1851+```1852+1853+如果要以给定格式记录此信息(例如JSON,键值或其他内容),则可以使用`gin.DebugPrintRouteFunc`定义此格式。1854+在下面的示例中,我们使用标准日志包记录所有路由,但您可以使用其他适合您需求的日志工具。1855+```go1856+import (1857+ "log"1858+ "net/http"1859+1860+ "github.com/gin-gonic/gin"1861+)1862+1863+func main() {1864+ r := gin.Default()1865+ gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {1866+ log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers)1867+ }1868+1869+ r.POST("/foo", func(c *gin.Context) {1870+ c.JSON(http.StatusOK, "foo")1871+ })1872+1873+ r.GET("/bar", func(c *gin.Context) {1874+ c.JSON(http.StatusOK, "bar")1875+ })1876+1877+ r.GET("/status", func(c *gin.Context) {1878+ c.JSON(http.StatusOK, "ok")1879+ })1880+1881+ // Listen and Server in http://0.0.0.0:80801882+ r.Run()1883+}1884+```1885+1886+1887+## 测试1888+1889+`net / http / httptest`包是HTTP测试的首选方式。1890+1891+```go1892+package main1893+1894+func setupRouter() *gin.Engine {1895+ r := gin.Default()1896+ r.GET("/ping", func(c *gin.Context) {1897+ c.String(200, "pong")1898+ })1899+ return r1900+}1901+1902+func main() {1903+ r := setupRouter()1904+ r.Run(":8080")1905+}1906+```1907+1908+测试上面的代码示例:1909+1910+```go1911+package main1912+1913+import (1914+ "net/http"1915+ "net/http/httptest"1916+ "testing"1917+1918+ "github.com/stretchr/testify/assert"1919+)1920+1921+func TestPingRoute(t *testing.T) {1922+ router := setupRouter()1923+1924+ w := httptest.NewRecorder()1925+ req, _ := http.NewRequest("GET", "/ping", nil)1926+ router.ServeHTTP(w, req)1927+1928+ assert.Equal(t, 200, w.Code)1929+ assert.Equal(t, "pong", w.Body.String())1930+}1931+```1932+1933+## 用户1934+1935+1936+使用[Gin](https://github.com/gin-gonic/gin)Web框架的令人敬畏的项目列表。1937+1938+* [drone](https://github.com/drone/drone):drone,用Go编写。1939+* [gorush](https://github.com/appleboy/gorush):用Go编写的推送通知服务器。1940+* [fnproject](https://github.com/fnproject/fn):容器本机,云无关的无服务器平台。