├── .idea
└── vcs.xml
└── README.md
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
5 |
6 | [](https://travis-ci.org/gin-gonic/gin)
7 | [](https://codecov.io/gh/gin-gonic/gin)
8 | [](https://goreportcard.com/report/github.com/gin-gonic/gin)
9 | [](https://godoc.org/github.com/gin-gonic/gin)
10 | [](https://gitter.im/gin-gonic/gin?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
11 | [](https://www.codetriage.com/gin-gonic/gin)
12 |
13 |
14 | Gin是一个使用Go语言写的web框架.它拥有与Martini相似的API,但它比Martini快40多倍.Gin内部使用 Golang最快的HTTP路由器[httprouter](https://github.com/julienschmidt/httprouter).如果你需要更高的性能,更快的开发效率,你会喜欢上Gin.
15 |
16 | 
17 |
18 | 项目地址[Gin Web Framework](https://github.com/gin-gonic/gin)
19 |
20 |
21 | ## 目录
22 |
23 | - [快速开始](#quick-start)
24 | - [性能基准](#benchmarks)
25 | - [Gin v1.稳定版](#gin-v1-stable)
26 | - [开始使用](#start-using-it)
27 | - [使用jsoniter](#build-with-jsoniter)
28 | - [API示例](#api-examples)
29 | - [GET,POST,PUT,PATCH,DELETE和OPTIONS](#using-get-post-put-patch-delete-and-options)
30 | - [url路径中的参数](#parameters-in-path)
31 | - [url中的查询参数](#querystring-parameters)
32 | - [Multipart/Urlencoded Form](#multiparturlencoded-form)
33 | - [url中查询参数+form表单数据](#another-example-query--post-form)
34 | - [文件上传](#upload-files)
35 | - [路由分组](#grouping-routes)
36 | - [不使用默认的中间件](#blank-gin-without-middleware-by-default)
37 | - [使用中间件](#using-middleware)
38 | - [如何编写日志文件](#how-to-write-log-file)
39 | - [模型绑定和验证](#model-binding-and-validation)
40 | - [自定义验证](#custom-validators)
41 | - [仅绑定查询字符串](#only-bind-query-string)
42 | - [绑定查询字符串或Post数据](#bind-query-string-or-post-data)
43 | - [绑定 HTML checkboxes](#bind-html-checkboxes)
44 | - [绑定 Multipart/Urlencoded](#multiparturlencoded-binding)
45 | - [XML, JSON 和 YAML 绑定](#xml-json-and-yaml-rendering)
46 | - [JSONP](#jsonp)
47 | - [静态文件](#serving-static-files)
48 | - [Serving data from reader](#serving-data-from-reader)
49 | - [HTML模板渲染](#html-rendering)
50 | - [Multitemplate](#multitemplate)
51 | - [重定向](#redirects)
52 | - [自定义中间件](#custom-middleware)
53 | - [使用 BasicAuth() 中间件](#using-basicauth-middleware)
54 | - [中间件内的Goroutines](#goroutines-inside-a-middleware)
55 | - [自定义HTTP配置](#custom-http-configuration)
56 | - [使用Let's Encrypt证书](#support-lets-encrypt)
57 | - [使用Gin运行多个服务](#run-multiple-service-using-gin)
58 | - [优雅的重启或停止](#graceful-restart-or-stop)
59 | - [用模板构建一个二进制文件](#build-a-single-binary-with-templates)
60 | - [使用自定义结构绑定表单数据请求](#bind-form-data-request-with-custom-struct)
61 | - [尝试将body绑定到不同的结构中](#try-to-bind-body-into-different-structs)
62 | - [测试](#testing)
63 | - [Users](#users--)
64 |
65 | ## Quick start
66 | ## 快速开始
67 |
68 | ```sh
69 | # 在example.go文件中假设有以下代码
70 | $ cat example.go
71 | ```
72 |
73 | ```go
74 | package main
75 |
76 | import "github.com/gin-gonic/gin"
77 |
78 | func main() {
79 | r := gin.Default()
80 | r.GET("/ping", func(c *gin.Context) {
81 | c.JSON(200, gin.H{
82 | "message": "pong",
83 | })
84 | })
85 | r.Run() // listen and serve on 0.0.0.0:8080
86 | }
87 | ```
88 |
89 | ```
90 | # 运行 example.go 并在浏览器中访问 0.0.0.0:8080/ping
91 | $ go run example.go
92 | ```
93 |
94 | ## Benchmarks
95 | ## 基准测试
96 |
97 | Gin 使用自定义版本的 [HttpRouter](https://github.com/julienschmidt/httprouter)
98 |
99 | [查看所有测试结果](https://github.com/gin-gonic/gin/blob/master/BENCHMARKS.md)
100 |
101 | Benchmark name | (1) | (2) | (3) | (4)
102 | --------------------------------------------|-----------:|------------:|-----------:|---------:
103 | **BenchmarkGin_GithubAll** | **30000** | **48375** | **0** | **0**
104 | BenchmarkAce_GithubAll | 10000 | 134059 | 13792 | 167
105 | BenchmarkBear_GithubAll | 5000 | 534445 | 86448 | 943
106 | BenchmarkBeego_GithubAll | 3000 | 592444 | 74705 | 812
107 | BenchmarkBone_GithubAll | 200 | 6957308 | 698784 | 8453
108 | BenchmarkDenco_GithubAll | 10000 | 158819 | 20224 | 167
109 | BenchmarkEcho_GithubAll | 10000 | 154700 | 6496 | 203
110 | BenchmarkGocraftWeb_GithubAll | 3000 | 570806 | 131656 | 1686
111 | BenchmarkGoji_GithubAll | 2000 | 818034 | 56112 | 334
112 | BenchmarkGojiv2_GithubAll | 2000 | 1213973 | 274768 | 3712
113 | BenchmarkGoJsonRest_GithubAll | 2000 | 785796 | 134371 | 2737
114 | BenchmarkGoRestful_GithubAll | 300 | 5238188 | 689672 | 4519
115 | BenchmarkGorillaMux_GithubAll | 100 | 10257726 | 211840 | 2272
116 | BenchmarkHttpRouter_GithubAll | 20000 | 105414 | 13792 | 167
117 | BenchmarkHttpTreeMux_GithubAll | 10000 | 319934 | 65856 | 671
118 | BenchmarkKocha_GithubAll | 10000 | 209442 | 23304 | 843
119 | BenchmarkLARS_GithubAll | 20000 | 62565 | 0 | 0
120 | BenchmarkMacaron_GithubAll | 2000 | 1161270 | 204194 | 2000
121 | BenchmarkMartini_GithubAll | 200 | 9991713 | 226549 | 2325
122 | BenchmarkPat_GithubAll | 200 | 5590793 | 1499568 | 27435
123 | BenchmarkPossum_GithubAll | 10000 | 319768 | 84448 | 609
124 | BenchmarkR2router_GithubAll | 10000 | 305134 | 77328 | 979
125 | BenchmarkRivet_GithubAll | 10000 | 132134 | 16272 | 167
126 | BenchmarkTango_GithubAll | 3000 | 552754 | 63826 | 1618
127 | BenchmarkTigerTonic_GithubAll | 1000 | 1439483 | 239104 | 5374
128 | BenchmarkTraffic_GithubAll | 100 | 11383067 | 2659329 | 21848
129 | BenchmarkVulcan_GithubAll | 5000 | 394253 | 19894 | 609
130 |
131 | - (1): 持续时间达到的总重复次数越多,意味着结果越好
132 | - (2): 单次重复持续时间(ns / op)越低越好
133 | - (3): 堆内存(B / op)越低越好
134 | - (4): 平均每次重复分配 (allocs/op) 越低越好
135 |
136 | ## Gin v1. stable
137 |
138 | - [x] Zero allocation router.
139 | - [x] Still the fastest http router and framework. From routing to writing.
140 | - [x] Complete suite of unit tests
141 | - [x] Battle tested
142 | - [x] API frozen, new releases will not break your code.
143 |
144 | ## Start using it
145 | ## 开始使用
146 |
147 | 1. 下载并安装它:
148 |
149 | ```sh
150 | $ go get github.com/gin-gonic/gin
151 | ```
152 |
153 | 2. 将其导入到您的代码中:
154 |
155 | ```go
156 | import "github.com/gin-gonic/gin"
157 | ```
158 |
159 | 3. (可选的) 导入 `net/http`. 如果您要使用诸如`http.StatusOK`的常量.
160 |
161 | ```go
162 | import "net/http"
163 | ```
164 |
165 | ### Use a vendor tool like [Govendor](https://github.com/kardianos/govendor)
166 | ### 使用包管理工具 [Govendor](https://github.com/kardianos/govendor)
167 |
168 | 1. 使用`go get`获取 `govendor`
169 |
170 | ```sh
171 | $ go get github.com/kardianos/govendor
172 | ```
173 | 2. 创建并进入你的项目文件夹
174 |
175 | ```sh
176 | $ mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"
177 | ```
178 |
179 | 3. 初始化你的项目并添加gin
180 |
181 | ```sh
182 | $ govendor init
183 | $ govendor fetch github.com/gin-gonic/gin@v1.2
184 | ```
185 |
186 | 4. 复制一个初始模板到你的项目中
187 |
188 | ```sh
189 | $ curl https://raw.githubusercontent.com/gin-gonic/gin/master/examples/basic/main.go > main.go
190 | ```
191 |
192 | 5. 运行你的项目
193 |
194 | ```sh
195 | $ go run main.go
196 | ```
197 |
198 | ## Build with [jsoniter](https://github.com/json-iterator/go)
199 | ## 使用[jsoniter](https://github.com/json-iterator/go)
200 |
201 |
202 | Gin使用`dncoding/json` 作为默认的json包,但是你可以在构建的时候用[jsoniter](https://github.com/json-iterator/go) 替换它
203 |
204 | ```sh
205 | $ go build -tags=jsoniter .
206 | ```
207 |
208 | ## API示例
209 |
210 | ### Using GET, POST, PUT, PATCH, DELETE and OPTIONS
211 |
212 | ```go
213 | func main() {
214 | // 禁用控制台颜色
215 | // gin.DisableConsoleColor()
216 |
217 | // 用默认的中间件创建一个gin路由器:
218 | // logger and recovery (crash-free) middleware
219 | // 记录 恢复(不崩溃) 中间件
220 | 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 a
231 | // PORT environment variable was defined.
232 | // 服务默认使用8080端口,除非你自定义了端口号的环境变量
233 | router.Run()
234 | // router.Run(":3000") 指定端口号为 :3000
235 |
236 | }
237 | ```
238 |
239 | ### Parameters in path
240 | ### url路径中的参数
241 |
242 | ```go
243 | func main() {
244 | router := gin.Default()
245 |
246 | // 路由1 匹配 /user/john,但是不匹配 /user/ 或 /user
247 | router.GET("/user/:name", func(c *gin.Context) {
248 | name := c.Param("name")
249 | c.String(http.StatusOK, "Hello %s", name)
250 | })
251 |
252 |
253 | // 路由2 这个会匹配 /user/john/ 和 /user/john/send
254 | router.GET("/user/:name/*action", func(c *gin.Context) {
255 | name := c.Param("name")
256 | action := c.Param("action")
257 | message := name + " is " + action
258 | c.String(http.StatusOK, message)
259 | })
260 |
261 | // 注意 /user/:name 和 /user/:name/是俩个完全不同的路由
262 |
263 | router.Run(":8080")
264 | }
265 | ```
266 | ```bash
267 | ➜ ~ curl 127.0.0.1:8080/user/jack
268 | Hello jack
269 | ➜ ~ curl 127.0.0.1:8080/user/jack/
270 | jack is
271 | ➜ ~ curl 127.0.0.1:8080/user/jack/do
272 | jack is /do
273 | ```
274 |
275 |
276 | ### Querystring parameters
277 | ### url中的查询参数
278 | 如?q=123&key=789
279 | ```go
280 | func main() {
281 | router := gin.Default()
282 |
283 | // Query string parameters are parsed using the existing underlying request object.
284 | // 匹配url: /welcome?firstname=Jane&lastname=Doe
285 | router.GET("/welcome", func(c *gin.Context) {
286 | // 取firstname的值,不存在则设为Guest
287 | firstname := c.DefaultQuery("firstname", "Guest")
288 | lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")
289 |
290 | c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
291 | })
292 | router.Run(":8080")
293 | }
294 | ```
295 | ```bash
296 | ➜ ~ curl -XGET "127.0.0.1:8080/welcome?firstname=Jane&lastname=Doe"
297 | Hello Jane Doe
298 | ➜ ~ curl -XGET "127.0.0.1:8080/welcome"
299 | Hello Guest
300 | ➜ ~ curl -XGET "127.0.0.1:8080/welcome?lastname=Doe"
301 | Hello Guest Doe
302 | ```
303 |
304 | ### Multipart/Urlencoded Form
305 |
306 | ```go
307 | func main() {
308 | router := gin.Default()
309 |
310 | router.POST("/form_post", func(c *gin.Context) {
311 | message := c.PostForm("message")
312 | nick := c.DefaultPostForm("nick", "anonymous")
313 |
314 | c.JSON(200, gin.H{
315 | "status": "posted",
316 | "message": message,
317 | "nick": nick,
318 | })
319 | })
320 | router.Run(":8080")
321 | }
322 | ```
323 | ```bash
324 | ➜ ~ curl -X POST http://127.0.0.1:8080/form_post -F nick=bddbnet -F message=hello
325 | {"message":"hello","nick":"bddbnet","status":"posted"}
326 | ➜ ~ curl -X POST http://127.0.0.1:8080/form_post -F message=hello
327 | {"message":"hello","nick":"anonymous","status":"posted"}
328 | ➜ ~ curl -X POST http://127.0.0.1:8080/form_post -F nick=bddbnet
329 | {"message":"","nick":"bddbnet","status":"posted"}
330 | ```
331 |
332 | ### Another example: query + post form
333 | ### url中查询参数+form表单数据
334 |
335 | ```
336 | POST /post?id=1234&page=1 HTTP/1.1
337 | Content-Type: application/x-www-form-urlencoded
338 |
339 | name=manu&message=this_is_great
340 | ```
341 |
342 | ```go
343 | func main() {
344 | router := gin.Default()
345 |
346 | router.POST("/post", func(c *gin.Context) {
347 | // url中查询数据
348 | id := c.Query("id")
349 | page := c.DefaultQuery("page", "0")
350 |
351 | // post表单中数据
352 | name := c.PostForm("name")
353 | message := c.PostForm("message")
354 |
355 | c.JSON(200, gin.H{
356 | "status": "posted",
357 | "id": id,
358 | "page": page,
359 | "name": name,
360 | "message": message,
361 | })
362 | fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
363 | })
364 | router.Run(":8080")
365 | }
366 | ```
367 |
368 | ```bash
369 | ➜ ~ curl -X POST 'http://127.0.0.1:8080/post?id=123&page=1' -F name=bddbnet -F message=hello
370 | {"id":"123","message":"hello","name":"bddbnet","page":"1","status":"posted"}
371 | ➜ ~ curl -X POST 'http://127.0.0.1:8080/post?id=123' -F name=bddbnet -F message=hello
372 | {"id":"123","message":"hello","name":"bddbnet","page":"0","status":"posted"}
373 | ➜ ~ curl -X POST 'http://127.0.0.1:8080/post' -F name=bddbnet -F message=hello
374 | {"id":"","message":"hello","name":"bddbnet","page":"0","status":"posted"}
375 | ➜ ~ curl -X POST 'http://127.0.0.1:8080/post' -F name=bddbnet
376 | {"id":"","message":"","name":"bddbnet","page":"0","status":"posted"}
377 | ```
378 |
379 | ### Upload files
380 | ### 文件上传
381 |
382 | #### Single file
383 | #### 单个文件
384 |
385 | 参考问题 [#774](https://github.com/gin-gonic/gin/issues/774) 和细节[example code](examples/upload-file/single).
386 |
387 | ```go
388 | func main() {
389 | router := gin.Default()
390 | // Set a lower memory limit for multipart forms (default is 32 MiB)
391 | // router.MaxMultipartMemory = 8 << 20 // 8 MiB
392 | router.POST("/upload", func(c *gin.Context) {
393 | // single file
394 | file, _ := c.FormFile("file")
395 | log.Println(file.Filename)
396 |
397 |
398 | savePath := "/tmp/"
399 | dst := savePath + file.Filename
400 |
401 | // Upload the file to specific dst.
402 | err := c.SaveUploadedFile(file, dst)
403 | if err != nil {
404 | panic(err)
405 | }
406 |
407 | c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
408 | })
409 | router.Run(":8080")
410 | }
411 | ```
412 |
413 | ```bash
414 | ➜ ~ curl -X POST http://localhost:8080/upload \
415 | -F "file=@/home/bddbnet/Pictures/bg002.jpg" \
416 | -H "Content-Type: multipart/form-data"
417 | 'bg002.jpg' uploaded!
418 | ```
419 |
420 | #### Multiple files
421 | #### 多个文件
422 |
423 | See the detail [example code](examples/upload-file/multiple).
424 |
425 | ```go
426 | func main() {
427 | router := gin.Default()
428 | // Set a lower memory limit for multipart forms (default is 32 MiB)
429 | // router.MaxMultipartMemory = 8 << 20 // 8 MiB
430 | router.POST("/upload", func(c *gin.Context) {
431 | // Multipart form
432 | form, _ := c.MultipartForm()
433 | files := form.File["upload[]"]
434 | savePath := "/tmp/"
435 |
436 | for _, file := range files {
437 | log.Println(file.Filename)
438 |
439 | dst := savePath + file.Filename
440 | // Upload the file to specific dst.
441 | c.SaveUploadedFile(file, dst)
442 | }
443 | c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
444 | })
445 | router.Run(":8080")
446 | }
447 | ```
448 | ```bash
449 | curl -X POST http://localhost:8080/upload \
450 | -F "upload[]=@/Users/appleboy/test1.zip" \
451 | -F "upload[]=@/Users/appleboy/test2.zip" \
452 | -H "Content-Type: multipart/form-data"
453 | 2 files uploaded!
454 | ```
455 |
456 | ### Grouping routes
457 | ### 路由分组
458 |
459 | ```go
460 | func main() {
461 | router := gin.Default()
462 |
463 | // Simple group: v1
464 | v1 := router.Group("/v1")
465 | {
466 | v1.POST("/login", loginEndpoint)
467 | v1.POST("/submit", submitEndpoint)
468 | v1.POST("/read", readEndpoint)
469 | }
470 |
471 | // Simple group: v2
472 | v2 := router.Group("/v2")
473 | {
474 | v2.POST("/login", loginEndpoint)
475 | v2.POST("/submit", submitEndpoint)
476 | v2.POST("/read", readEndpoint)
477 | }
478 |
479 | router.Run(":8080")
480 | }
481 | ```
482 | ### Blank Gin without middleware by default
483 | ### 不使用默认的中间件
484 |
485 | 用
486 |
487 | ```go
488 | r := gin.New()
489 | ```
490 |
491 | 替代
492 |
493 | ```go
494 | // Default With the Logger and Recovery middleware already attached
495 | // 默认情况已启用了log和恢复中间件
496 | r := gin.Default()
497 | ```
498 |
499 | ### Using middleware
500 | ### 使用中间件
501 | ```go
502 | func main() {
503 | // 默认情况下创建一个没有任何中间件的路由器
504 | r := gin.New()
505 |
506 | // Global middleware
507 | // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.
508 | // By default gin.DefaultWriter = os.Stdout
509 | r.Use(gin.Logger())
510 |
511 | // Recovery middleware recovers from any panics and writes a 500 if there was one.
512 | r.Use(gin.Recovery())
513 |
514 | // 每个路由中,你可以使用任意多个中间件.
515 | r.GET("/benchmark", MyBenchLogger(), benchEndpoint)
516 |
517 | // 权限组
518 | // authorized := r.Group("/", AuthRequired())
519 | // 等同于:
520 | authorized := r.Group("/")
521 | // 在这组路由中,我们使用自定义的中间件
522 | // AuthRequired() 中间件只在 "authorized" 组中使用.
523 | authorized.Use(AuthRequired())
524 | {
525 | authorized.POST("/login", loginEndpoint)
526 | authorized.POST("/submit", submitEndpoint)
527 | authorized.POST("/read", readEndpoint)
528 |
529 | // 嵌套组
530 | testing := authorized.Group("testing")
531 | testing.GET("/analytics", analyticsEndpoint)
532 | }
533 |
534 | // Listen and serve on 0.0.0.0:8080
535 | r.Run(":8080")
536 | }
537 | ```
538 |
539 | ### How to write log file
540 | ### 如何写日志文件
541 | ```go
542 | func main() {
543 |
544 | // 禁用控制台颜色,写入日志文件时不需要添加颜色
545 | gin.DisableConsoleColor()
546 |
547 | // 写入到文件.
548 | f, _ := os.Create("gin.log")
549 | gin.DefaultWriter = io.MultiWriter(f)
550 |
551 | // 如果您需要同时将日志写入文件和控制台,请使用以下代码
552 | // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
553 |
554 | router := gin.Default()
555 | router.GET("/ping", func(c *gin.Context) {
556 | c.String(200, "pong")
557 | })
558 |
559 | router.Run(":8080")
560 | }
561 | ```
562 |
563 | ### Model binding and validation
564 | ### 模型绑定和验证
565 |
566 |
567 | 使用模型绑定,将请求主体绑定到一个类型.我们目前支持JSON的绑定,XML和标准表单值(foo=bar&boo=baz).
568 |
569 | 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)查看所有文档.
570 |
571 | 请注意,您需要在所有要绑定的字段上设置相应的绑定标签.例如从JSON绑定时, 添加结构体字段标签 `json:"fieldname"`.
572 |
573 | 此外,Gin提供了两种绑定方法:
574 | - **种类** - Must bind
575 | - **方法** - `Bind`, `BindJSON`, `BindQuery`
576 | - **特性** - 这些方法在底层使用`MustBindWith`。如果存在绑定错误,则使用`c.AbortWithError(400,err).SetType(ErrorTypeBind)`中止请求。这将响应状态码设置为400,并且将`Content-Type`标头设置为`text/plain; charset=utf-8`。请注意,如果您尝试在此之后设置响应代码,则会导致警告`[GIN-debug] [WARNING] Headers were already written(请求头已经设置). Wanted to override status code 400 with 422(企图用422覆盖状态码400)`。如果你希望更好地控制行为,可以考虑使用`ShouldBind`等价的方法。
577 |
578 | - **种类** - Should bind
579 | - **方法** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindQuery`
580 | - **特性** - 这些方法使用`ShouldBindWith`。如果存在绑定错误,则返回错误,并且开发人员有责任正确处理请求和错误
581 |
582 | 使用绑定方法时, Gin试图根据Content-Type头推断绑定数据的类型. 如果你能够确认绑定数据的类型, 可以使用 `MustBindWith` 或 `ShouldBindWith`绑定数据.
583 |
584 |
585 | 你可以指定需要绑定数据的字段. 如果这个字段存在这个 `binding:"required"`的结构体字段标签并且在绑定时字段的值为空值时, 将会返回一个错误.
586 |
587 | ```go
588 | // Binding from JSON
589 | type Login struct {
590 | User string `form:"user" json:"user" binding:"required"`
591 | Password string `form:"password" json:"password" binding:"required"`
592 | }
593 |
594 | func main() {
595 | router := gin.Default()
596 |
597 | // Example for binding JSON ({"user": "manu", "password": "123"})
598 | router.POST("/loginJSON", func(c *gin.Context) {
599 | var json Login
600 | if err := c.ShouldBindJSON(&json); err == nil {
601 | if json.User == "manu" && json.Password == "123" {
602 | c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
603 | } else {
604 | c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
605 | }
606 | } else {
607 | c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
608 | }
609 | })
610 |
611 | // Example for binding a HTML form (user=manu&password=123)
612 | router.POST("/loginForm", func(c *gin.Context) {
613 | var form Login
614 | // This will infer what binder to use depending on the content-type header.
615 | if err := c.ShouldBind(&form); err == nil {
616 | if form.User == "manu" && form.Password == "123" {
617 | c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
618 | } else {
619 | c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
620 | }
621 | } else {
622 | c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
623 | }
624 | })
625 |
626 | // Listen and serve on 0.0.0.0:8080
627 | router.Run(":8080")
628 | }
629 | ```
630 |
631 | **Sample request**
632 | ```shell
633 | $ curl -v -X POST \
634 | http://localhost:8080/loginJSON \
635 | -H 'content-type: application/json' \
636 | -d '{ "user": "manu" }'
637 | > POST /loginJSON HTTP/1.1
638 | > Host: localhost:8080
639 | > User-Agent: curl/7.51.0
640 | > Accept: */*
641 | > content-type: application/json
642 | > Content-Length: 18
643 | >
644 | * upload completely sent off: 18 out of 18 bytes
645 | < HTTP/1.1 400 Bad Request
646 | < Content-Type: application/json; charset=utf-8
647 | < Date: Fri, 04 Aug 2017 03:51:31 GMT
648 | < Content-Length: 100
649 | <
650 | {"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}
651 | ```
652 |
653 | ### Custom Validators
654 | ### 自定义验证
655 |
656 | 你也可以注册自定义验证器. 点这里查看 [例子](examples/custom-validation/server.go).
657 |
658 | [embedmd]:# (examples/custom-validation/server.go go)
659 | ```go
660 | package main
661 |
662 | import (
663 | "net/http"
664 | "reflect"
665 | "time"
666 |
667 | "github.com/gin-gonic/gin"
668 | "github.com/gin-gonic/gin/binding"
669 | "gopkg.in/go-playground/validator.v8"
670 | )
671 |
672 | type Booking struct {
673 | CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`
674 | CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`
675 | }
676 |
677 | func bookableDate(
678 | v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,
679 | field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,
680 | ) bool {
681 | if date, ok := field.Interface().(time.Time); ok {
682 | today := time.Now()
683 | if today.Year() > date.Year() || today.YearDay() > date.YearDay() {
684 | return false
685 | }
686 | }
687 | return true
688 | }
689 |
690 | func main() {
691 | route := gin.Default()
692 |
693 | if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
694 | v.RegisterValidation("bookabledate", bookableDate)
695 | }
696 |
697 | route.GET("/bookable", getBookable)
698 | route.Run(":8085")
699 | }
700 |
701 | func getBookable(c *gin.Context) {
702 | var b Booking
703 | if err := c.ShouldBindWith(&b, binding.Query); err == nil {
704 | c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
705 | } else {
706 | c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
707 | }
708 | }
709 | ```
710 |
711 | ```console
712 | $ curl "localhost:8085/bookable?check_in=2018-04-16&check_out=2018-04-17"
713 | {"message":"Booking dates are valid!"}
714 |
715 | $ curl "localhost:8085/bookable?check_in=2018-03-08&check_out=2018-03-09"
716 | {"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}
717 | ```
718 |
719 | [结构级别验证](https://github.com/go-playground/validator/releases/tag/v8.7) 也可以用这种方式注册.
720 | 点击这里查看 [例子](examples/struct-lvl-validations) .
721 |
722 | ### Only Bind Query String
723 | ### 仅绑定Url查询字符串
724 |
725 | `ShouldBindQuery` 函数只绑定查询参数而不是post的数据. 详情点击这里 [查看](https://github.com/gin-gonic/gin/issues/742#issuecomment-315953017).
726 |
727 | ```go
728 | package main
729 |
730 | import (
731 | "log"
732 |
733 | "github.com/gin-gonic/gin"
734 | )
735 |
736 | type Person struct {
737 | Name string `form:"name"`
738 | Address string `form:"address"`
739 | }
740 |
741 | func main() {
742 | route := gin.Default()
743 | route.Any("/testing", startPage)
744 | route.Run(":8085")
745 | }
746 |
747 | func startPage(c *gin.Context) {
748 | var person Person
749 | if c.ShouldBindQuery(&person) == nil {
750 | log.Println("====== Only Bind By Query String ======")
751 | log.Println(person.Name)
752 | log.Println(person.Address)
753 | }
754 | c.JSON(http.StatusOK, gin.H{"Name": person.Name, "Address": person.Address})
755 | }
756 |
757 | ```
758 | ```bash
759 | ~ curl 'http://127.0.0.1:8080/testing?name=tom&address=none'
760 | {"Address":"none","Name":"tom"}
761 | ```
762 |
763 | ### Bind Query String or Post Data
764 | ### 绑定Url查询字符串或Post的数据
765 |
766 | 详情见 [这里](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292).
767 |
768 | ```go
769 | package main
770 |
771 | import "log"
772 | import "github.com/gin-gonic/gin"
773 | import "time"
774 |
775 | type Person struct {
776 | Name string `form:"name"`
777 | Address string `form:"address"`
778 | Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`
779 | }
780 |
781 | func main() {
782 | route := gin.Default()
783 | route.GET("/testing", startPage)
784 | route.Run(":8085")
785 | }
786 |
787 | func startPage(c *gin.Context) {
788 | var person Person
789 | // If `GET`, only `Form` binding engine (`query`) used.
790 | // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).
791 | // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48
792 | if c.ShouldBind(&person) == nil {
793 | log.Println(person.Name)
794 | log.Println(person.Address)
795 | log.Println(person.Birthday)
796 | }
797 |
798 | c.String(200, "Success")
799 | }
800 | ```
801 |
802 | Test it with:
803 | ```sh
804 | $ curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15"
805 | ```
806 |
807 | ### Bind HTML checkboxes
808 | ### 绑定 HTML checkboxes
809 |
810 | See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)
811 |
812 | main.go
813 |
814 | ```go
815 | ...
816 |
817 | type myForm struct {
818 | Colors []string `form:"colors[]"`
819 | }
820 |
821 | ...
822 |
823 | func formHandler(c *gin.Context) {
824 | var fakeForm myForm
825 | c.ShouldBind(&fakeForm)
826 | c.JSON(200, gin.H{"color": fakeForm.Colors})
827 | }
828 |
829 | ...
830 |
831 | ```
832 |
833 | form.html
834 |
835 | ```html
836 |
Using posts/index.tmpl
1095 | 1096 | {{ end }} 1097 | ``` 1098 | 1099 | templates/users/index.tmpl 1100 | 1101 | ```html 1102 | {{ define "users/index.tmpl" }} 1103 |Using users/index.tmpl
1107 | 1108 | {{ end }} 1109 | ``` 1110 | 1111 | #### Custom Template renderer 1112 | #### 自定义模板渲染 1113 | 1114 | 你也可以自己定义模板渲染方式 1115 | ```go 1116 | import "html/template" 1117 | 1118 | func main() { 1119 | router := gin.Default() 1120 | html := template.Must(template.ParseFiles("file1", "file2")) 1121 | router.SetHTMLTemplate(html) 1122 | router.Run(":8080") 1123 | } 1124 | ``` 1125 | 1126 | #### Custom Delimiters 1127 | #### 自定义分隔符 1128 | 1129 | 你可以自己定义分隔符 1130 | 1131 | ```go 1132 | r := gin.Default() 1133 | r.Delims("{[{", "}]}") 1134 | r.LoadHTMLGlob("/path/to/templates")) 1135 | ``` 1136 | 1137 | #### Custom Template Funcs 1138 | #### 自定义模板函数 1139 | 1140 | 细节看 [这里](examples/template). 1141 | 1142 | main.go 1143 | 1144 | ```go 1145 | import ( 1146 | "fmt" 1147 | "html/template" 1148 | "net/http" 1149 | "time" 1150 | 1151 | "github.com/gin-gonic/gin" 1152 | ) 1153 | 1154 | // 定义了一个函数 1155 | func formatAsDate(t time.Time) string { 1156 | year, month, day := t.Date() 1157 | return fmt.Sprintf("%d%02d/%02d", year, month, day) 1158 | } 1159 | 1160 | func main() { 1161 | router := gin.Default() 1162 | // 设置分隔符 1163 | router.Delims("{[{", "}]}") 1164 | // 注册函数 1165 | router.SetFuncMap(template.FuncMap{ 1166 | "formatAsDate": formatAsDate, 1167 | }) 1168 | router.LoadHTMLFiles("./fixtures/basic/raw.tmpl") 1169 | 1170 | router.GET("/raw", func(c *gin.Context) { 1171 | c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{ 1172 | "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC), 1173 | }) 1174 | }) 1175 | 1176 | router.Run(":8080") 1177 | } 1178 | 1179 | ``` 1180 | 1181 | raw.tmpl 1182 | 1183 | ```html 1184 | // 使用formatAsDate函数 1185 | Date: {[{.now | formatAsDate}]} 1186 | ``` 1187 | 1188 | Result: 1189 | ``` 1190 | Date: 2017/07/01 1191 | ``` 1192 | 1193 | ### Multitemplate 1194 | ### 使用多个模板文件 1195 | 1196 | Gin 默认情况下只允许使用一个模板文件. 点击 [这里](https://github.com/gin-contrib/multitemplate) 看如何使用如 go 1.6 `block template`来实现多模板渲染. 1197 | 1198 | ### Redirects 1199 | ### 重定向 1200 | 1201 | HTTP重定向实现很容易: 1202 | 1203 | ```go 1204 | r.GET("/test", func(c *gin.Context) { 1205 | // 重定向 1206 | c.Redirect(http.StatusMovedPermanently, "http://www.google.com/") 1207 | }) 1208 | ``` 1209 | 站内站外的重定向都被支持 1210 | 1211 | ### Custom Middleware 1212 | ### 自定义中间件 1213 | 1214 | ```go 1215 | // 定义一个Looger中间件 1216 | func Logger() gin.HandlerFunc { 1217 | return func(c *gin.Context) { 1218 | t := time.Now() 1219 | 1220 | // Set example variable 1221 | c.Set("example", "12345") 1222 | 1223 | // request请求之前做什么的代码写在这里 1224 | 1225 | c.Next() 1226 | 1227 | // request请求之后做什么的代码写在这里 1228 | latency := time.Since(t) 1229 | log.Print(latency) 1230 | 1231 | // 获取我们正在发送的状态 1232 | status := c.Writer.Status() 1233 | log.Println(status) 1234 | } 1235 | } 1236 | 1237 | func main() { 1238 | r := gin.New() 1239 | // 使用中间件 1240 | r.Use(Logger()) 1241 | 1242 | r.GET("/test", func(c *gin.Context) { 1243 | // 获取中间件设置的变量 1244 | example := c.MustGet("example").(string) 1245 | 1246 | // it would print: "12345" 1247 | log.Println(example) 1248 | }) 1249 | 1250 | // Listen and serve on 0.0.0.0:8080 1251 | r.Run(":8080") 1252 | } 1253 | ``` 1254 | 1255 | ### Using BasicAuth() middleware 1256 | ### 使用认证中间件 1257 | 1258 | ```go 1259 | // 模拟一些私有数据 1260 | var secrets = gin.H{ 1261 | "foo": gin.H{"email": "foo@bar.com", "phone": "123433"}, 1262 | "austin": gin.H{"email": "austin@example.com", "phone": "666"}, 1263 | "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"}, 1264 | } 1265 | 1266 | func main() { 1267 | r := gin.Default() 1268 | 1269 | // Group using gin.BasicAuth() middleware 1270 | // gin.Accounts is a shortcut for map[string]string 1271 | authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{ 1272 | "foo": "bar", 1273 | "austin": "1234", 1274 | "lena": "hello2", 1275 | "manu": "4321", 1276 | })) 1277 | 1278 | // /admin/secrets endpoint 1279 | // hit "localhost:8080/admin/secrets 1280 | authorized.GET("/secrets", func(c *gin.Context) { 1281 | // get user, it was set by the BasicAuth middleware 1282 | user := c.MustGet(gin.AuthUserKey).(string) 1283 | if secret, ok := secrets[user]; ok { 1284 | c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret}) 1285 | } else { 1286 | c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("}) 1287 | } 1288 | }) 1289 | 1290 | // Listen and serve on 0.0.0.0:8080 1291 | r.Run(":8080") 1292 | } 1293 | ``` 1294 | 1295 | ### Goroutines inside a middleware 1296 | ### 中间件内的Goroutines 1297 | 1298 | 在中间件或处理程序中启动新的Goroutines时, 你 **一定不要** 使用它内部的原始上下文, 你必须使用只读副本. 1299 | 1300 | ```go 1301 | func main() { 1302 | r := gin.Default() 1303 | 1304 | // 异步执行 1305 | r.GET("/long_async", func(c *gin.Context) { 1306 | // create copy to be used inside the goroutine 1307 | cCp := c.Copy() 1308 | go func() { 1309 | // 模拟一个耗时任务 1310 | time.Sleep(5 * time.Second) 1311 | 1312 | // 一定要使用复制的cCp 1313 | log.Println("Done! in path " + cCp.Request.URL.Path) 1314 | }() 1315 | }) 1316 | 1317 | // 同步执行 1318 | r.GET("/long_sync", func(c *gin.Context) { 1319 | // simulate a long task with time.Sleep(). 5 seconds 1320 | time.Sleep(5 * time.Second) 1321 | 1322 | // 不使用Goroutines则不需要复制 1323 | log.Println("Done! in path " + c.Request.URL.Path) 1324 | }) 1325 | 1326 | // Listen and serve on 0.0.0.0:8080 1327 | r.Run(":8080") 1328 | } 1329 | ``` 1330 | 1331 | ### Custom HTTP configuration 1332 | ### 自定义HTTP配置 1333 | 1334 | Use `http.ListenAndServe()` directly, like this: 1335 | 1336 | ```go 1337 | func main() { 1338 | router := gin.Default() 1339 | http.ListenAndServe(":8080", router) 1340 | } 1341 | ``` 1342 | or 1343 | 1344 | ```go 1345 | func main() { 1346 | router := gin.Default() 1347 | 1348 | s := &http.Server{ 1349 | Addr: ":8080", 1350 | Handler: router, 1351 | ReadTimeout: 10 * time.Second, 1352 | WriteTimeout: 10 * time.Second, 1353 | MaxHeaderBytes: 1 << 20, 1354 | } 1355 | s.ListenAndServe() 1356 | } 1357 | ``` 1358 | 1359 | ### Support Let's Encrypt 1360 | ### 使用Let's Encrypt证书 1361 | 1362 | 1行代码实现 LetsEncrypt HTTPS服务器. 1363 | 1364 | [embedmd]:# (examples/auto-tls/example1/main.go go) 1365 | ```go 1366 | package main 1367 | 1368 | import ( 1369 | "log" 1370 | 1371 | "github.com/gin-gonic/autotls" 1372 | "github.com/gin-gonic/gin" 1373 | ) 1374 | 1375 | func main() { 1376 | r := gin.Default() 1377 | 1378 | // Ping handler 1379 | r.GET("/ping", func(c *gin.Context) { 1380 | c.String(200, "pong") 1381 | }) 1382 | 1383 | log.Fatal(autotls.Run(r, "example1.com", "example2.com")) 1384 | } 1385 | ``` 1386 | 1387 | 自定义autocert管理器的示例. 1388 | 1389 | [embedmd]:# (examples/auto-tls/example2/main.go go) 1390 | ```go 1391 | package main 1392 | 1393 | import ( 1394 | "log" 1395 | 1396 | "github.com/gin-gonic/autotls" 1397 | "github.com/gin-gonic/gin" 1398 | "golang.org/x/crypto/acme/autocert" 1399 | ) 1400 | 1401 | func main() { 1402 | r := gin.Default() 1403 | 1404 | // Ping handler 1405 | r.GET("/ping", func(c *gin.Context) { 1406 | c.String(200, "pong") 1407 | }) 1408 | 1409 | m := autocert.Manager{ 1410 | Prompt: autocert.AcceptTOS, 1411 | HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"), 1412 | Cache: autocert.DirCache("/var/www/.cache"), 1413 | } 1414 | 1415 | log.Fatal(autotls.RunWithManager(r, &m)) 1416 | } 1417 | ``` 1418 | 1419 | ### Run multiple service using Gin 1420 | ### 使用Gin运行多个服务 1421 | 1422 | 请参阅[问题](https://github.com/gin-gonic/gin/issues/346)并尝试以下示例: 1423 | 1424 | [embedmd]:# (examples/multiple-service/main.go go) 1425 | ```go 1426 | package main 1427 | 1428 | import ( 1429 | "log" 1430 | "net/http" 1431 | "time" 1432 | 1433 | "github.com/gin-gonic/gin" 1434 | "golang.org/x/sync/errgroup" 1435 | ) 1436 | 1437 | var ( 1438 | g errgroup.Group 1439 | ) 1440 | 1441 | func router01() http.Handler { 1442 | e := gin.New() 1443 | e.Use(gin.Recovery()) 1444 | e.GET("/", func(c *gin.Context) { 1445 | c.JSON( 1446 | http.StatusOK, 1447 | gin.H{ 1448 | "code": http.StatusOK, 1449 | "error": "Welcome server 01", 1450 | }, 1451 | ) 1452 | }) 1453 | 1454 | return e 1455 | } 1456 | 1457 | func router02() http.Handler { 1458 | e := gin.New() 1459 | e.Use(gin.Recovery()) 1460 | e.GET("/", func(c *gin.Context) { 1461 | c.JSON( 1462 | http.StatusOK, 1463 | gin.H{ 1464 | "code": http.StatusOK, 1465 | "error": "Welcome server 02", 1466 | }, 1467 | ) 1468 | }) 1469 | 1470 | return e 1471 | } 1472 | 1473 | func main() { 1474 | server01 := &http.Server{ 1475 | Addr: ":8080", 1476 | Handler: router01(), 1477 | ReadTimeout: 5 * time.Second, 1478 | WriteTimeout: 10 * time.Second, 1479 | } 1480 | 1481 | server02 := &http.Server{ 1482 | Addr: ":8081", 1483 | Handler: router02(), 1484 | ReadTimeout: 5 * time.Second, 1485 | WriteTimeout: 10 * time.Second, 1486 | } 1487 | 1488 | g.Go(func() error { 1489 | return server01.ListenAndServe() 1490 | }) 1491 | 1492 | g.Go(func() error { 1493 | return server02.ListenAndServe() 1494 | }) 1495 | 1496 | if err := g.Wait(); err != nil { 1497 | log.Fatal(err) 1498 | } 1499 | } 1500 | ``` 1501 | 1502 | ### Graceful restart or stop 1503 | ### 优雅的重启或停止 1504 | 1505 | 以下方式可以让你优雅的重启或停止你的web服务器。 1506 | 1507 | 我们可以用 [fvbock/endless](https://github.com/fvbock/endless) 取代默认的 `ListenAndServe`. 请参阅 [问题#296](https://github.com/gin-gonic/gin/issues/296)获得更多细节. 1508 | 1509 | ```go 1510 | router := gin.Default() 1511 | router.GET("/", handler) 1512 | // [...] 1513 | endless.ListenAndServe(":4242", router) 1514 | ``` 1515 | 1516 | 其他的替代方案: 1517 | 1518 | * [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully. 1519 | * [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server. 1520 | * [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers. 1521 | 1522 | If you are using Go 1.8, you may not need to use this library! Consider using http.Server's built-in [Shutdown()](https://golang.org/pkg/net/http/#Server.Shutdown) method for graceful shutdowns. See the full [graceful-shutdown](./examples/graceful-shutdown) example with gin. 1523 | 1524 | [embedmd]:# (examples/graceful-shutdown/graceful-shutdown/server.go go) 1525 | ```go 1526 | // +build go1.8 1527 | 1528 | package main 1529 | 1530 | import ( 1531 | "context" 1532 | "log" 1533 | "net/http" 1534 | "os" 1535 | "os/signal" 1536 | "time" 1537 | 1538 | "github.com/gin-gonic/gin" 1539 | ) 1540 | 1541 | func main() { 1542 | router := gin.Default() 1543 | router.GET("/", func(c *gin.Context) { 1544 | time.Sleep(5 * time.Second) 1545 | c.String(http.StatusOK, "Welcome Gin Server") 1546 | }) 1547 | 1548 | srv := &http.Server{ 1549 | Addr: ":8080", 1550 | Handler: router, 1551 | } 1552 | 1553 | go func() { 1554 | // service connections 1555 | if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { 1556 | log.Fatalf("listen: %s\n", err) 1557 | } 1558 | }() 1559 | 1560 | // Wait for interrupt signal to gracefully shutdown the server with 1561 | // a timeout of 5 seconds. 1562 | quit := make(chan os.Signal) 1563 | signal.Notify(quit, os.Interrupt) 1564 | <-quit 1565 | log.Println("Shutdown Server ...") 1566 | 1567 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) 1568 | defer cancel() 1569 | if err := srv.Shutdown(ctx); err != nil { 1570 | log.Fatal("Server Shutdown:", err) 1571 | } 1572 | log.Println("Server exiting") 1573 | } 1574 | ``` 1575 | 1576 | ### Build a single binary with templates 1577 | ### 将服务器构建为一个包含模板文件的二进制文件 1578 | 1579 | 您可以通过使用[go-assets](https://github.com/jessevdk/go-assets),将服务器构建为包含模板的单个二进制文件 1580 | 1581 | ```go 1582 | func main() { 1583 | r := gin.New() 1584 | 1585 | t, err := loadTemplate() 1586 | if err != nil { 1587 | panic(err) 1588 | } 1589 | r.SetHTMLTemplate(t) 1590 | 1591 | r.GET("/", func(c *gin.Context) { 1592 | c.HTML(http.StatusOK, "/html/index.tmpl",nil) 1593 | }) 1594 | r.Run(":8080") 1595 | } 1596 | 1597 | // loadTemplate loads templates embedded by go-assets-builder 1598 | func loadTemplate() (*template.Template, error) { 1599 | t := template.New("") 1600 | for name, file := range Assets.Files { 1601 | if file.IsDir() || !strings.HasSuffix(name, ".tmpl") { 1602 | continue 1603 | } 1604 | h, err := ioutil.ReadAll(file) 1605 | if err != nil { 1606 | return nil, err 1607 | } 1608 | t, err = t.New(name).Parse(string(h)) 1609 | if err != nil { 1610 | return nil, err 1611 | } 1612 | } 1613 | return t, nil 1614 | } 1615 | ``` 1616 | 1617 | See a complete example in the `examples/assets-in-binary` directory. 1618 | 1619 | ### Bind form-data request with custom struct 1620 | ### 使用自定义结构绑定表单数据 1621 | 1622 | 以下使用自定义结构的示例: 1623 | 1624 | ```go 1625 | type StructA struct { 1626 | FieldA string `form:"field_a"` 1627 | } 1628 | 1629 | type StructB struct { 1630 | NestedStruct StructA 1631 | FieldB string `form:"field_b"` 1632 | } 1633 | 1634 | type StructC struct { 1635 | NestedStructPointer *StructA 1636 | FieldC string `form:"field_c"` 1637 | } 1638 | 1639 | type StructD struct { 1640 | NestedAnonyStruct struct { 1641 | FieldX string `form:"field_x"` 1642 | } 1643 | FieldD string `form:"field_d"` 1644 | } 1645 | 1646 | func GetDataB(c *gin.Context) { 1647 | var b StructB 1648 | c.Bind(&b) 1649 | c.JSON(200, gin.H{ 1650 | "a": b.NestedStruct, 1651 | "b": b.FieldB, 1652 | }) 1653 | } 1654 | 1655 | func GetDataC(c *gin.Context) { 1656 | var b StructC 1657 | c.Bind(&b) 1658 | c.JSON(200, gin.H{ 1659 | "a": b.NestedStructPointer, 1660 | "c": b.FieldC, 1661 | }) 1662 | } 1663 | 1664 | func GetDataD(c *gin.Context) { 1665 | var b StructD 1666 | c.Bind(&b) 1667 | c.JSON(200, gin.H{ 1668 | "x": b.NestedAnonyStruct, 1669 | "d": b.FieldD, 1670 | }) 1671 | } 1672 | 1673 | func main() { 1674 | r := gin.Default() 1675 | r.GET("/getb", GetDataB) 1676 | r.GET("/getc", GetDataC) 1677 | r.GET("/getd", GetDataD) 1678 | 1679 | r.Run() 1680 | } 1681 | ``` 1682 | 1683 | Using the command `curl` command result: 1684 | 1685 | ``` 1686 | $ curl "http://localhost:8080/getb?field_a=hello&field_b=world" 1687 | {"a":{"FieldA":"hello"},"b":"world"} 1688 | $ curl "http://localhost:8080/getc?field_a=hello&field_c=world" 1689 | {"a":{"FieldA":"hello"},"c":"world"} 1690 | $ curl "http://localhost:8080/getd?field_x=hello&field_d=world" 1691 | {"d":"world","x":{"FieldX":"hello"}} 1692 | ``` 1693 | 1694 | **NOTE**: NOT support the follow style struct: 1695 | 1696 | ```go 1697 | type StructX struct { 1698 | X struct {} `form:"name_x"` // HERE have form 1699 | } 1700 | 1701 | type StructY struct { 1702 | Y StructX `form:"name_y"` // HERE hava form 1703 | } 1704 | 1705 | type StructZ struct { 1706 | Z *StructZ `form:"name_z"` // HERE hava form 1707 | } 1708 | ``` 1709 | 1710 | In a word, only support nested custom struct which have no `form` now. 1711 | 1712 | ### Try to bind body into different structs 1713 | ### 尝试将body绑定到不同的结构中 1714 | 1715 | The normal methods for binding request body consumes `c.Request.Body` and they 1716 | cannot be called multiple times. 1717 | 1718 | ```go 1719 | type formA struct { 1720 | Foo string `json:"foo" xml:"foo" binding:"required"` 1721 | } 1722 | 1723 | type formB struct { 1724 | Bar string `json:"bar" xml:"bar" binding:"required"` 1725 | } 1726 | 1727 | func SomeHandler(c *gin.Context) { 1728 | objA := formA{} 1729 | objB := formB{} 1730 | // This c.ShouldBind consumes c.Request.Body and it cannot be reused. 1731 | if errA := c.ShouldBind(&objA); errA == nil { 1732 | c.String(http.StatusOK, `the body should be formA`) 1733 | // Always an error is occurred by this because c.Request.Body is EOF now. 1734 | } else if errB := c.ShouldBind(&objB); errB == nil { 1735 | c.String(http.StatusOK, `the body should be formB`) 1736 | } else { 1737 | ... 1738 | } 1739 | } 1740 | ``` 1741 | 1742 | For this, you can use `c.ShouldBindBodyWith`. 1743 | 1744 | ```go 1745 | func SomeHandler(c *gin.Context) { 1746 | objA := formA{} 1747 | objB := formB{} 1748 | // This reads c.Request.Body and stores the result into the context. 1749 | if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil { 1750 | c.String(http.StatusOK, `the body should be formA`) 1751 | // At this time, it reuses body stored in the context. 1752 | } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil { 1753 | c.String(http.StatusOK, `the body should be formB JSON`) 1754 | // And it can accepts other formats 1755 | } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil { 1756 | c.String(http.StatusOK, `the body should be formB XML`) 1757 | } else { 1758 | ... 1759 | } 1760 | } 1761 | ``` 1762 | 1763 | * `c.ShouldBindBodyWith` stores body into the context before binding. This has 1764 | a slight impact to performance, so you should not use this method if you are 1765 | enough to call binding at once. 1766 | * This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`, 1767 | `ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`, 1768 | can be called by `c.ShouldBind()` multiple times without any damage to 1769 | performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)). 1770 | 1771 | ## Testing 1772 | ## 测试 1773 | 1774 | The `net/http/httptest` package is preferable way for HTTP testing. 1775 | 1776 | ```go 1777 | package main 1778 | 1779 | func setupRouter() *gin.Engine { 1780 | r := gin.Default() 1781 | r.GET("/ping", func(c *gin.Context) { 1782 | c.String(200, "pong") 1783 | }) 1784 | return r 1785 | } 1786 | 1787 | func main() { 1788 | r := setupRouter() 1789 | r.Run(":8080") 1790 | } 1791 | ``` 1792 | 1793 | Test for code example above: 1794 | 1795 | ```go 1796 | package main 1797 | 1798 | import ( 1799 | "net/http" 1800 | "net/http/httptest" 1801 | "testing" 1802 | 1803 | "github.com/stretchr/testify/assert" 1804 | ) 1805 | 1806 | func TestPingRoute(t *testing.T) { 1807 | router := setupRouter() 1808 | 1809 | w := httptest.NewRecorder() 1810 | req, _ := http.NewRequest("GET", "/ping", nil) 1811 | router.ServeHTTP(w, req) 1812 | 1813 | assert.Equal(t, 200, w.Code) 1814 | assert.Equal(t, "pong", w.Body.String()) 1815 | } 1816 | ``` 1817 | 1818 | ## Users [](https://sourcegraph.com/github.com/gin-gonic/gin?badge) 1819 | 1820 | Awesome project lists using [Gin](https://github.com/gin-gonic/gin) web framework. 1821 | 1822 | * [drone](https://github.com/drone/drone): Drone is a Continuous Delivery platform built on Docker, written in Go 1823 | * [gorush](https://github.com/appleboy/gorush): A push notification server written in Go. 1824 | 1825 | 1826 | --------------------------------------------------------------------------------