Skip to content
Myr

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

1 file+1940 added−0 removed

added:README_ZH.md+1940 added
1# Gin Web 框架中文文档23<img align="right" width="159px" src="https://raw.githubusercontent.com/gin-gonic/logo/master/color.png">45[![Build Status](https://travis-ci.org/gin-gonic/gin.svg)](https://travis-ci.org/gin-gonic/gin)6[![codecov](https://codecov.io/gh/gin-gonic/gin/branch/master/graph/badge.svg)](https://codecov.io/gh/gin-gonic/gin)7[![Go Report Card](https://goreportcard.com/badge/github.com/gin-gonic/gin)](https://goreportcard.com/report/github.com/gin-gonic/gin)8[![GoDoc](https://godoc.org/github.com/gin-gonic/gin?status.svg)](https://godoc.org/github.com/gin-gonic/gin)9[![Join the chat at https://gitter.im/gin-gonic/gin](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)10[![Sourcegraph](https://sourcegraph.com/github.com/gin-gonic/gin/-/badge.svg)](https://sourcegraph.com/github.com/gin-gonic/gin?badge)11[![Open Source Helpers](https://www.codetriage.com/gin-gonic/gin/badges/users.svg)](https://www.codetriage.com/gin-gonic/gin)12[![Release](https://img.shields.io/github/release/gin-gonic/gin.svg?style=flat-square)](https://github.com/gin-gonic/gin/releases)1314Gin 是一个 Go (Golang) 语言框架。 它是一个拥有更好性能的 martini-like API 框架, 比 [httprouter](https://github.com/julienschmidt/httprouter) 的速度快了40倍. 如果你是性能和高效的追求者, 那么你会爱上 Gin.1516![Gin console logger](https://gin-gonic.github.io/gin/other/console.png)1718## Contents1920- [安装](#安装)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- [用户](#用户)6566## 安装6768要安装 Gin 软件包,需要先安装 Go 并设置 Go 工作区。69701. 下载并安装 gin:7172```sh73$ go get -u github.com/gin-gonic/gin74```75762. 将 gin 引入到代码中:7778```go79import "github.com/gin-gonic/gin"80```81823. (可选)如果使用诸如`http.StatusOK`之类的常量,则需要引入 `net / http` 包。8384```go85import "net/http"86```8788### 使用 [Govendor](https://github.com/kardianos/govendor) 工具创建项目89901. `go get` govendor9192```sh93$ go get github.com/kardianos/govendor94```952.创建项目并且 `cd` 到项目目录中9697```sh98$ mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"99```1001013. 使用 govendor 初始化项目,并且引入gin102103```sh104$ govendor init105$ govendor fetch github.com/gin-gonic/gin@v1.3106```1071084. 复制一个启动文件模板到项目目录中109110```sh111$ curl https://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go > main.go112```1131145.启动项目115116```sh117$ go run main.go118```119120## 前提条件121122新版本的 Gin 需要 Go 1.6 或者更高版本并且很快就会升级到 Go 1.7.123124## 快速启动125 126```sh127# assume the following codes in example.go file128$ cat example.go129```130131```go132package main133134import "github.com/gin-gonic/gin"135136func 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```146147```148# run example.go and visit 0.0.0.0:8080/ping on browser149$ go run example.go150```151152## 性能测试153154Gin 使用自定义版本的 [HttpRouter](https://github.com/julienschmidt/httprouter)155156[所有性能测试](/BENCHMARKS.md)157158Benchmark name | (1) | (2) | (3) | (4)159--------------------------------------------|-----------:|------------:|-----------:|---------:160**BenchmarkGin_GithubAll** | **30000** | **48375** | **0** | **0**161BenchmarkAce_GithubAll | 10000 | 134059 | 13792 | 167162BenchmarkBear_GithubAll | 5000 | 534445 | 86448 | 943163BenchmarkBeego_GithubAll | 3000 | 592444 | 74705 | 812164BenchmarkBone_GithubAll | 200 | 6957308 | 698784 | 8453165BenchmarkDenco_GithubAll | 10000 | 158819 | 20224 | 167166BenchmarkEcho_GithubAll | 10000 | 154700 | 6496 | 203167BenchmarkGocraftWeb_GithubAll | 3000 | 570806 | 131656 | 1686168BenchmarkGoji_GithubAll | 2000 | 818034 | 56112 | 334169BenchmarkGojiv2_GithubAll | 2000 | 1213973 | 274768 | 3712170BenchmarkGoJsonRest_GithubAll | 2000 | 785796 | 134371 | 2737171BenchmarkGoRestful_GithubAll | 300 | 5238188 | 689672 | 4519172BenchmarkGorillaMux_GithubAll | 100 | 10257726 | 211840 | 2272173BenchmarkHttpRouter_GithubAll | 20000 | 105414 | 13792 | 167174BenchmarkHttpTreeMux_GithubAll | 10000 | 319934 | 65856 | 671175BenchmarkKocha_GithubAll | 10000 | 209442 | 23304 | 843176BenchmarkLARS_GithubAll | 20000 | 62565 | 0 | 0177BenchmarkMacaron_GithubAll | 2000 | 1161270 | 204194 | 2000178BenchmarkMartini_GithubAll | 200 | 9991713 | 226549 | 2325179BenchmarkPat_GithubAll | 200 | 5590793 | 1499568 | 27435180BenchmarkPossum_GithubAll | 10000 | 319768 | 84448 | 609181BenchmarkR2router_GithubAll | 10000 | 305134 | 77328 | 979182BenchmarkRivet_GithubAll | 10000 | 132134 | 16272 | 167183BenchmarkTango_GithubAll | 3000 | 552754 | 63826 | 1618184BenchmarkTigerTonic_GithubAll | 1000 | 1439483 | 239104 | 5374185BenchmarkTraffic_GithubAll | 100 | 11383067 | 2659329 | 21848186BenchmarkVulcan_GithubAll | 5000 | 394253 | 19894 | 609187188- (1): 在不断的时间内实现总重复,更高意味着更自信的结果189- (2): 单次重复持续时间(ns / op),越低越好190- (3): 堆内存(B / op),越低越好191- (4): 每次重复的平均分配(allocs / op)越低越好192193## Gin v1 稳定版194195- [x] 零分配路由器。196- [x] 仍然是最快的http路由器和框架。197- [x] 完整的单元测试套件198- [x] 对战测试199- [x] API冻结,新版本不会破坏您的代码。200201## 使用 [jsoniter](https://github.com/json-iterator/go) 构建202203Gin使用`encoding / json`作为默认的json包,但您可以通过其他标签的构建更改为[jsoniter](https://github.com/json-iterator/go)。204205```sh206$ go build -tags=jsoniter .207```208209## API 示例210211### GET, POST, PUT, PATCH, DELETE , OPTIONS 使用212213```go214func main() {215 // Disable Console Color216 // gin.DisableConsoleColor()217218 // Creates a gin router with default middleware:219 // logger and recovery (crash-free) middleware220 router := gin.Default()221222 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)229230 // 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```236237### 路由参数238239```go240func main() {241 router := gin.Default()242243 // 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 })248249 // 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 })257258 router.Run(":8080")259}260```261262### 查询字符串参数263264```go265func main() {266 router := gin.Default()267268 // 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")273274 c.String(http.StatusOK, "Hello %s %s", firstname, lastname)275 })276 router.Run(":8080")277}278```279280### Multipart Urlencoded 表单281282```go283func main() {284 router := gin.Default()285286 router.POST("/form_post", func(c *gin.Context) {287 message := c.PostForm("message")288 nick := c.DefaultPostForm("nick", "anonymous")289290 c.JSON(200, gin.H{291 "status": "posted",292 "message": message,293 "nick": nick,294 })295 })296 router.Run(":8080")297}298```299300### 另一个实列 query + post form301302```303POST /post?id=1234&page=1 HTTP/1.1304Content-Type: application/x-www-form-urlencoded305306name=manu&message=this_is_great307```308309```go310func main() {311 router := gin.Default()312313 router.POST("/post", func(c *gin.Context) {314315 id := c.Query("id")316 page := c.DefaultQuery("page", "0")317 name := c.PostForm("name")318 message := c.PostForm("message")319320 fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)321 })322 router.Run(":8080")323}324```325326```327id: 1234; page: 1; name: manu; message: this_is_great328```329330### 映射参数 表单参数331332```333POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1334Content-Type: application/x-www-form-urlencoded335336names[first]=thinkerou&names[second]=tianou337```338339```go340func main() {341 router := gin.Default()342343 router.POST("/post", func(c *gin.Context) {344345 ids := c.QueryMap("ids")346 names := c.PostFormMap("names")347348 fmt.Printf("ids: %v; names: %v", ids, names)349 })350 router.Run(":8080")351}352```353354```355ids: map[b:hello a:1234], names: map[second:tianou first:thinkerou]356```357358### 上传文件359360#### 单个文件上传361362参考问题[#774](https://github.com/gin-gonic/gin/issues/774)和详细[示例代码](examples / upload-file / single)。363364```go365func 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)373374 // Upload the file to specific dst.375 // c.SaveUploadedFile(file, dst)376377 c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))378 })379 router.Run(":8080")380}381```382383如何 `curl`:384385```bash386curl -X POST http://localhost:8080/upload \387 -F "file=@/Users/appleboy/test.zip" \388 -H "Content-Type: multipart/form-data"389```390391#### 多文件上传392393查看详细信息[示例代码](examples / upload-file / multiple)。394395```go396func 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[]"]404405 for _, file := range files {406 log.Println(file.Filename)407408 // 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```416417如何 `curl`:418419```bash420curl -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```425426### 路由组427428```go429func main() {430 router := gin.Default()431432 // Simple group: v1433 v1 := router.Group("/v1")434 {435 v1.POST("/login", loginEndpoint)436 v1.POST("/submit", submitEndpoint)437 v1.POST("/read", readEndpoint)438 }439440 // Simple group: v2441 v2 := router.Group("/v2")442 {443 v2.POST("/login", loginEndpoint)444 v2.POST("/submit", submitEndpoint)445 v2.POST("/read", readEndpoint)446 }447448 router.Run(":8080")449}450```451452### 默认初始化 Gin453454用455456```go457r := gin.New()458```459460代替461462```go463// Default With the Logger and Recovery middleware already attached464r := gin.Default()465```466467468### 中间件使用469```go470func main() {471 // Creates a router without any middleware by default472 r := gin.New()473474 // 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())478479 // Recovery middleware recovers from any panics and writes a 500 if there was one.480 r.Use(gin.Recovery())481482 // Per route middleware, you can add as many as you desire.483 r.GET("/benchmark", MyBenchLogger(), benchEndpoint)484485 // 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)496497 // nested group498 testing := authorized.Group("testing")499 testing.GET("/analytics", analyticsEndpoint)500 }501502 // Listen and serve on 0.0.0.0:8080503 r.Run(":8080")504}505```506507### 如何记录日志508```go509func main() {510 // Disable Console Color, you don't need console color when writing the logs to file.511 gin.DisableConsoleColor()512513 // Logging to a file.514 f, _ := os.Create("gin.log")515 gin.DefaultWriter = io.MultiWriter(f)516517 // 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)519520 router := gin.Default()521 router.GET("/ping", func(c *gin.Context) {522 c.String(200, "pong")523 })524525    router.Run(":8080")526}527```528529### 模型绑定和验证530531要将请求主体绑定到类型中,请使用模型绑定。我们目前支持JSON,XML和标准表单值的绑定(foo = bar&boo = baz)。532533Gin使用[** 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)。534535请注意,您需要在要绑定的所有字段上设置相应的绑定标记。例如,从JSON绑定时,设置`json:“fieldname”`。536537此外,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`。如果存在绑定错误,则返回错误,开发人员有责任正确处理请求和错误。544545使用Bind方法时,Gin会尝试根据Content-Type标头推断出绑定器。如果你确定你绑定了什么,你可以使用 `MustBindWith` 或 `ShouldBindWith`。546547您还可以指定需要特定字段。如果字段用 `binding:“必需”` 来装饰,并且在绑定时具有空值,则会返回错误。548549```go550// Binding from JSON551type 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}555556func main() {557 router := gin.Default()558559 // 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 })574575 // 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 })595596 // 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 })612613 // Listen and serve on 0.0.0.0:8080614 router.Run(":8080")615}616```617618**简单请求**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```639640**跳过验证**641642使用上面 的`curl` 命令运行上面的例子时,它返回错误。 因为这个例子使用 `binding:'需要``````。 如果使用 `binding:“ - ``````,那么在再次运行上面的例子时它不会返回错误。643644### 自定义验证器645646也可以注册自定义验证器。 请参阅[示例代码](examples / custom-validation / server.go)。647648[embedmd]:#(examples / custom-validation / server.go go)649```go650package main651652import (653 "net/http"654 "reflect"655 "time"656657 "github.com/gin-gonic/gin"658 "github.com/gin-gonic/gin/binding"659 "gopkg.in/go-playground/validator.v8"660)661662// Booking contains binded and validated data.663type 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}667668func 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}680681func main() {682 route := gin.Default()683684 if v, ok := binding.Validator.Engine().(*validator.Validate); ok {685 v.RegisterValidation("bookabledate", bookableDate)686 }687688 route.GET("/bookable", getBookable)689 route.Run(":8085")690}691692func 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```701702```console703$ curl "localhost:8085/bookable?check_in=2018-04-16&check_out=2018-04-17"704{"message":"Booking dates are valid!"}705706$ 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```709710[结构级验证](https://github.com/go-playground/validator/releases/tag/v8.7)也可以这种方式注册。711请参阅[struct-lvl-validation示例](examples / struct-lvl-validations)以了解更多信息。712713### 只绑定查询字符串714715`ShouldBindQuery` 函数只绑定查询参数而不是后期数据。 请参阅[详细信息](https://github.com/gin-gonic/gin/issues/742#issuecomment-315953017)。716717```go718package main719720import (721 "log"722723 "github.com/gin-gonic/gin"724)725726type Person struct {727 Name string `form:"name"`728 Address string `form:"address"`729}730731func main() {732 route := gin.Default()733 route.Any("/testing", startPage)734 route.Run(":8085")735}736737func 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}746747```748749### 绑定查询字符串或发布数据750751请参阅[详细信息](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292)。752753```go754package main755756import (757 "log"758 "time"759760 "github.com/gin-gonic/gin"761)762763type 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}768769func main() {770 route := gin.Default()771 route.GET("/testing", startPage)772 route.Run(":8085")773}774775func 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 }785786 c.String(200, "Success")787}788```789790测试:791```sh792$ curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15"793```794795### 绑定 HTML 复选框796797参见[详细信息](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)798799main.go800801```go802...803804type myForm struct {805 Colors []string `form:"colors[]"`806}807808...809810func formHandler(c *gin.Context) {811 var fakeForm myForm812 c.ShouldBind(&fakeForm)813 c.JSON(200, gin.H{"color": fakeForm.Colors})814}815816...817818```819820form.html821822```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```834835result:836837```838{"color":["red","green","blue"]}839```840841### Multipart Urlencoded 绑定842843```go844package main845846import (847 "github.com/gin-gonic/gin"848)849850type LoginForm struct {851 User string `form:"user" binding:"required"`852 Password string `form:"password" binding:"required"`853}854855func 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```874875Test it with:876```sh877$ curl -v --form user=user --form password=password http://localhost:8080/login878```879880### XML JSON YAML ProtoBuf 渲染881882```go883func main() {884 r := gin.Default()885886 // 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 })890891 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 })905906 r.GET("/someXML", func(c *gin.Context) {907 c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})908 })909910 r.GET("/someYAML", func(c *gin.Context) {911 c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})912 })913914 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 })926927 // Listen and serve on 0.0.0.0:8080928 r.Run(":8080")929}930```931932#### SecureJSON933934使用 SecureJSON 来防止 json 劫持。 如果给定的结构是数组值,则默认预 置`“while(1),”` 到响应体。935936```go937func main() {938 r := gin.Default()939940 // You can also use your own secure json prefix941 // r.SecureJsonPrefix(")]}',\n")942943 r.GET("/someJSON", func(c *gin.Context) {944 names := []string{"lena", "austin", "foo"}945946 // Will output : while(1);["lena","austin","foo"]947 c.SecureJSON(http.StatusOK, names)948 })949950 // Listen and serve on 0.0.0.0:8080951 r.Run(":8080")952}953```954#### JSONP955956使用 JSONP 从不同域中的服务器请求数据。 如果查询参数回调存在,则将回调添加到响应正文。957958```go959func main() {960 r := gin.Default()961962 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 })971972 // Listen and serve on 0.0.0.0:8080973 r.Run(":8080")974}975```976977#### AsciiJSON978979使用 Ascii JSON 生成具有转义的非 ASCII 字符的仅 ASCII JSON。980981```go982func main() {983 r := gin.Default()984985 r.GET("/someJSON", func(c *gin.Context) {986 data := map[string]interface{}{987 "lang": "GO语言",988 "tag": "<br>",989 }990991 // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}992 c.AsciiJSON(http.StatusOK, data)993 })994995 // Listen and serve on 0.0.0.0:8080996 r.Run(":8080")997}998```9991000#### PureJSON10011002通常,JSON 用其 unicod e实体替换特殊 HTML 字符,例如 `<` 变为 `\ u003c`。 如果要按字面意思对这些字符进行编码,则可以使用 PureJSON。1003Go 1.6 及更低版本无法使用此功能。10041005```go1006func 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```10271028### 静态文件服务10291030```go1031func 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")10361037 // Listen and serve on 0.0.0.0:80801038 router.Run(":8080")1039}1040```10411042### 从 reader 读取数据10431044```go1045func 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 }10531054 reader := response.Body1055 contentLength := response.ContentLength1056 contentType := response.Header.Get("Content-Type")10571058 extraHeaders := map[string]string{1059 "Content-Disposition": `attachment; filename="gopher.png"`,1060 }10611062 c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)1063 })1064 router.Run(":8080")1065}1066```10671068### HTML 渲染10691070使用LoadHTMLGlob()或LoadHTMLFiles()10711072```go1073func 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```10851086templates/index.tmpl10871088```html1089<html>1090 <h1>1091 {{ .title }}1092 </h1>1093</html>1094```10951096在不同目录中使用具有相同名称的模板10971098```go1099func 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```11151116templates/posts/index.tmpl11171118```html1119{{ define "posts/index.tmpl" }}1120<html><h1>1121 {{ .title }}1122</h1>1123<p>Using posts/index.tmpl</p>1124</html>1125{{ end }}1126```11271128templates/users/index.tmpl11291130```html1131{{ define "users/index.tmpl" }}1132<html><h1>1133 {{ .title }}1134</h1>1135<p>Using users/index.tmpl</p>1136</html>1137{{ end }}1138```11391140#### 自定义模板渲染器11411142您还可以使用自己的 html 模板渲染11431144```go1145import "html/template"11461147func main() {1148 router := gin.Default()1149 html := template.Must(template.ParseFiles("file1", "file2"))1150 router.SetHTMLTemplate(html)1151 router.Run(":8080")1152}1153```11541155#### 自定义分隔符11561157您可以使用自定义分隔11581159```go1160 r := gin.Default()1161 r.Delims("{[{", "}]}")1162 r.LoadHTMLGlob("/path/to/templates"))1163```11641165#### 自定义模板功能11661167查看详细信息[示例代码](示例/模板)。11681169main.go11701171```go1172import (1173 "fmt"1174 "html/template"1175 "net/http"1176 "time"11771178 "github.com/gin-gonic/gin"1179)11801181func formatAsDate(t time.Time) string {1182 year, month, day := t.Date()1183 return fmt.Sprintf("%d%02d/%02d", year, month, day)1184}11851186func main() {1187 router := gin.Default()1188 router.Delims("{[{", "}]}")1189 router.SetFuncMap(template.FuncMap{1190 "formatAsDate": formatAsDate,1191 })1192 router.LoadHTMLFiles("./testdata/template/raw.tmpl")11931194 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 })11991200 router.Run(":8080")1201}12021203```12041205raw.tmpl12061207```html1208日期: {[{.now | formatAsDate}]}1209```12101211结果:1212```1213Date: 2017/07/011214```12151216### 多模板12171218Gin 允许默认只使用一个 html 模板。 检查[多模板渲染](https://github.com/gin-contrib/multitemplate)以使用 go 1.6 `block template` 等功能。12191220### 重定向12211222Issuing a HTTP redirect is easy. Both internal and external locations are supported.12231224```go1225r.GET("/test", func(c *gin.Context) {1226 c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")1227})1228```122912301231发出路由器重定向,使用如下的“HandleContext”。12321233``` go1234r.GET("/test", func(c *gin.Context) {1235 c.Request.URL.Path = "/test2"1236 r.HandleContext(c)1237})1238r.GET("/test2", func(c *gin.Context) {1239 c.JSON(200, gin.H{"hello": "world"})1240})1241```124212431244### 自定义中间件12451246```go1247func Logger() gin.HandlerFunc {1248 return func(c *gin.Context) {1249 t := time.Now()12501251 // Set example variable1252 c.Set("example", "12345")12531254 // before request12551256 c.Next()12571258 // after request1259 latency := time.Since(t)1260 log.Print(latency)12611262 // access the status we are sending1263 status := c.Writer.Status()1264 log.Println(status)1265 }1266}12671268func main() {1269 r := gin.New()1270 r.Use(Logger())12711272 r.GET("/test", func(c *gin.Context) {1273 example := c.MustGet("example").(string)12741275 // it would print: "12345"1276 log.Println(example)1277 })12781279 // Listen and serve on 0.0.0.0:80801280 r.Run(":8080")1281}1282```12831284### BasicAuth() 中间件12851286```go1287// simulate some private data1288var 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}12931294func main() {1295 r := gin.Default()12961297 // 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 }))13051306 // /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 })13171318 // Listen and serve on 0.0.0.0:80801319 r.Run(":8080")1320}1321```13221323### Goroutines13241325当在中间件或处理程序中启动新的 Goroutines 时,你不应该**使用其中的原始上下文,你必须使用只读副本。13261327```go1328func main() {1329 r := gin.Default()13301331 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)13371338 // note that you are using the copied context "cCp", IMPORTANT1339 log.Println("Done! in path " + cCp.Request.URL.Path)1340 }()1341 })13421343 r.GET("/long_sync", func(c *gin.Context) {1344 // simulate a long task with time.Sleep(). 5 seconds1345 time.Sleep(5 * time.Second)13461347 // 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 })13501351 // Listen and serve on 0.0.0.0:80801352 r.Run(":8080")1353}1354```13551356### 自定义 HTTP 配置13571358直接使用`http.ListenAndServe()`,如下所示:13591360```go1361func main() {1362 router := gin.Default()1363 http.ListenAndServe(":8080", router)1364}1365```1366or13671368```go1369func main() {1370 router := gin.Default()13711372 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```13821383### Let's Encrypt 支持13841385单行 LetsEncrypt HTTPS 服务器的示例。13861387[embedmd]:# (examples/auto-tls/example1/main.go go)1388```go1389package main13901391import (1392 "log"13931394 "github.com/gin-gonic/autotls"1395 "github.com/gin-gonic/gin"1396)13971398func main() {1399 r := gin.Default()14001401 // Ping handler1402 r.GET("/ping", func(c *gin.Context) {1403 c.String(200, "pong")1404 })14051406 log.Fatal(autotls.Run(r, "example1.com", "example2.com"))1407}1408```14091410自定义autocert管理器的示例。14111412[embedmd]:# (examples/auto-tls/example2/main.go go)1413```go1414package main14151416import (1417 "log"14181419 "github.com/gin-gonic/autotls"1420 "github.com/gin-gonic/gin"1421 "golang.org/x/crypto/acme/autocert"1422)14231424func main() {1425 r := gin.Default()14261427 // Ping handler1428 r.GET("/ping", func(c *gin.Context) {1429 c.String(200, "pong")1430 })14311432 m := autocert.Manager{1433 Prompt: autocert.AcceptTOS,1434 HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),1435 Cache: autocert.DirCache("/var/www/.cache"),1436 }14371438 log.Fatal(autotls.RunWithManager(r, &m))1439}1440```14411442### 使用 Gin 运行多个服务14431444请参阅[问题](https://github.com/gin-gonic/gin/issues/346)并尝试以下示例:14451446[embedmd]:# (examples/multiple-service/main.go go)1447```go1448package main14491450import (1451 "log"1452 "net/http"1453 "time"14541455 "github.com/gin-gonic/gin"1456 "golang.org/x/sync/errgroup"1457)14581459var (1460 g errgroup.Group1461)14621463func 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 })14751476 return e1477}14781479func 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 })14911492 return e1493}14941495func main() {1496 server01 := &http.Server{1497 Addr: ":8080",1498 Handler: router01(),1499 ReadTimeout: 5 * time.Second,1500 WriteTimeout: 10 * time.Second,1501 }15021503 server02 := &http.Server{1504 Addr: ":8081",1505 Handler: router02(),1506 ReadTimeout: 5 * time.Second,1507 WriteTimeout: 10 * time.Second,1508 }15091510 g.Go(func() error {1511 return server01.ListenAndServe()1512 })15131514 g.Go(func() error {1515 return server02.ListenAndServe()1516 })15171518 if err := g.Wait(); err != nil {1519 log.Fatal(err)1520 }1521}1522```15231524### 优雅重启或停止15251526您想要优雅地重启或停止您的Web服务器吗?1527有一些方法可以做到这一点。15281529我们可以使用[fvbock / endless](https://github.com/fvbock/endless)来替换默认的`ListenAndServe`。 有关更多详细信息,请参阅问题[#296](https://github.com/gin-gonic/gin/issues/296)。15301531```go1532router := gin.Default()1533router.GET("/", handler)1534// [...]1535endless.ListenAndServe(":4242", router)1536```15371538另一种替代方案:15391540* [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服务器的平滑重启和零停机时间部署。15431544如果您使用的是Go 1.8,则可能不需要使用此库! 考虑使用http.Server的内置[Shutdown()](https://golang.org/pkg/net/http/#Server.Shutdown)方法进行正常关机。 请参阅gin的完整[graceful-shutdown](./ examples / graceful-shutdown)示例。15451546[embedmd]:# (examples/graceful-shutdown/graceful-shutdown/server.go go)1547```go1548// +build go1.815491550package main15511552import (1553 "context"1554 "log"1555 "net/http"1556 "os"1557 "os/signal"1558 "time"15591560 "github.com/gin-gonic/gin"1561)15621563func 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 })15691570 srv := &http.Server{1571 Addr: ":8080",1572 Handler: router,1573 }15741575 go func() {1576 // service connections1577 if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {1578 log.Fatalf("listen: %s\n", err)1579 }1580 }()15811582 // 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 ...")15881589 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```15971598### 使用模板构建单个二进制文件15991600您可以使用[go-assets] []将服务器构建到包含模板的单个二进制文件中。16011602[go-assets]:https://github.com/jessevdk/go-assets16031604```go1605func main() {1606 r := gin.New()16071608 t, err := loadTemplate()1609 if err != nil {1610 panic(err)1611 }1612 r.SetHTMLTemplate(t)16131614 r.GET("/", func(c *gin.Context) {1615 c.HTML(http.StatusOK, "/html/index.tmpl",nil)1616 })1617 r.Run(":8080")1618}16191620// loadTemplate loads templates embedded by go-assets-builder1621func 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```16391640请参阅`examples / assets-in-binary`目录中的完整示例。16411642### Bind form-data request with custom struct16431644以下示例使用自定义结构:16451646```go1647type StructA struct {1648 FieldA string `form:"field_a"`1649}16501651type StructB struct {1652 NestedStruct StructA1653 FieldB string `form:"field_b"`1654}16551656type StructC struct {1657 NestedStructPointer *StructA1658 FieldC string `form:"field_c"`1659}16601661type StructD struct {1662 NestedAnonyStruct struct {1663 FieldX string `form:"field_x"`1664 }1665 FieldD string `form:"field_d"`1666}16671668func 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}16761677func 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}16851686func 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}16941695func main() {1696 r := gin.Default()1697 r.GET("/getb", GetDataB)1698 r.GET("/getc", GetDataC)1699 r.GET("/getd", GetDataD)17001701 r.Run()1702}1703```17041705使用命令`curl`命令结果:17061707```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```17151716**注意**:不支持以下样式结构:17171718```go1719type StructX struct {1720 X struct {} `form:"name_x"` // HERE have form1721}17221723type StructY struct {1724 Y StructX `form:"name_y"` // HERE have form1725}17261727type StructZ struct {1728 Z *StructZ `form:"name_z"` // HERE have form1729}1730```17311732总之,只支持现在没有`form`的嵌套自定义结构。17331734### 尝试将 body 绑定到不同的结构中17351736绑定请求体的常规方法使用`c.Request.Body`和它们1737不能多次调用。17381739```go1740type formA struct {1741 Foo string `json:"foo" xml:"foo" binding:"required"`1742}17431744type formB struct {1745 Bar string `json:"bar" xml:"bar" binding:"required"`1746}17471748func 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```17621763为此,您可以使用`c.ShouldBindBodyWith`.17641765```go1766func 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```178317841785482/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))。17931794### http2 server 推送179517961797http.Pusher仅支持** go1.8 + **。 有关详细信息,请参阅[golang blog](https://blog.golang.org/h2push)。17981799[embedmd]:# (examples/http-pusher/main.go go)1800```go1801package main18021803import (1804 "html/template"1805 "log"18061807 "github.com/gin-gonic/gin"1808)18091810var 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`))18211822func main() {1823 r := gin.Default()1824 r.Static("/assets", "./assets")1825 r.SetHTMLTemplate(html)18261827 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 })18381839 // Listen and Server in https://127.0.0.1:80801840 r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")1841}1842```18431844### 定义路由日志的格式18451846路由的默认日志是: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```18521853如果要以给定格式记录此信息(例如JSON,键值或其他内容),则可以使用`gin.DebugPrintRouteFunc`定义此格式。1854在下面的示例中,我们使用标准日志包记录所有路由,但您可以使用其他适合您需求的日志工具。1855```go1856import (1857 "log"1858 "net/http"18591860 "github.com/gin-gonic/gin"1861)18621863func 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 }18681869 r.POST("/foo", func(c *gin.Context) {1870 c.JSON(http.StatusOK, "foo")1871 })18721873 r.GET("/bar", func(c *gin.Context) {1874 c.JSON(http.StatusOK, "bar")1875 })18761877 r.GET("/status", func(c *gin.Context) {1878 c.JSON(http.StatusOK, "ok")1879 })18801881 // Listen and Server in http://0.0.0.0:80801882 r.Run()1883}1884```188518861887## 测试18881889`net / http / httptest`包是HTTP测试的首选方式。18901891```go1892package main18931894func setupRouter() *gin.Engine {1895 r := gin.Default()1896 r.GET("/ping", func(c *gin.Context) {1897 c.String(200, "pong")1898 })1899 return r1900}19011902func main() {1903 r := setupRouter()1904 r.Run(":8080")1905}1906```19071908测试上面的代码示例:19091910```go1911package main19121913import (1914 "net/http"1915 "net/http/httptest"1916 "testing"19171918 "github.com/stretchr/testify/assert"1919)19201921func TestPingRoute(t *testing.T) {1922 router := setupRouter()19231924 w := httptest.NewRecorder()1925 req, _ := http.NewRequest("GET", "/ping", nil)1926 router.ServeHTTP(w, req)19271928 assert.Equal(t, 200, w.Code)1929 assert.Equal(t, "pong", w.Body.String())1930}1931```19321933## 用户193419351936使用[Gin](https://github.com/gin-gonic/gin)Web框架的令人敬畏的项目列表。19371938* [drone](https://github.com/drone/drone):drone,用Go编写。1939* [gorush](https://github.com/appleboy/gorush):用Go编写的推送通知服务器。1940* [fnproject](https://github.com/fnproject/fn):容器本机,云无关的无服务器平台。