Skip to content
Myr

chore: update readme (#1793)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* update readme * add multi-language version doc link * add multi-language version doc link * update readme * update * update readme * update readme * update readme

authored by 田欧 · committed by GitHub · parent e526148 · Browse files · 1 file+35 added−1972 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+35 added−1972 removed

  • other:+35 added−1972 removed

1 file+35 added−1972 removed

modified:README.md+35 added-1972 removed
11 unmodified lines
12[![Release](https://img.shields.io/github/release/gin-gonic/gin.svg?style=flat-square)](https://github.com/gin-gonic/gin/releases)1314Gin is a web framework written in Go (Golang). It features a martini-like API with much better performance, up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin.1516![Gin console logger](testdata/assets/console.png)16**The key features of Gin are:**1718## Contents18- Zero allocation router19- Fast20- Middleware support21- Crash-free22- JSON validation23- Routes grouping24- Error management25- Rendering built-in26- Extendable2720- [Installation](#installation)21- [Prerequisite](#prerequisite)22- [Quick start](#quick-start)23- [Benchmarks](#benchmarks)24- [Gin v1.stable](#gin-v1-stable)25- [Build with jsoniter](#build-with-jsoniter)26- [API Examples](#api-examples)27 - [Using GET,POST,PUT,PATCH,DELETE and OPTIONS](#using-get-post-put-patch-delete-and-options)28 - [Parameters in path](#parameters-in-path)29 - [Querystring parameters](#querystring-parameters)30 - [Multipart/Urlencoded Form](#multiparturlencoded-form)31 - [Another example: query + post form](#another-example-query--post-form)32 - [Map as querystring or postform parameters](#map-as-querystring-or-postform-parameters)33 - [Upload files](#upload-files)34 - [Grouping routes](#grouping-routes)35 - [Blank Gin without middleware by default](#blank-gin-without-middleware-by-default)36 - [Using middleware](#using-middleware)37 - [How to write log file](#how-to-write-log-file)38 - [Custom Log Format](#custom-log-format)39 - [Model binding and validation](#model-binding-and-validation)40 - [Custom Validators](#custom-validators)41 - [Only Bind Query String](#only-bind-query-string)42 - [Bind Query String or Post Data](#bind-query-string-or-post-data)43 - [Bind Uri](#bind-uri)44 - [Bind HTML checkboxes](#bind-html-checkboxes)45 - [Multipart/Urlencoded binding](#multiparturlencoded-binding)46 - [XML, JSON, YAML and ProtoBuf rendering](#xml-json-yaml-and-protobuf-rendering)47 - [JSONP rendering](#jsonp)48 - [Serving static files](#serving-static-files)49 - [Serving data from reader](#serving-data-from-reader)50 - [HTML rendering](#html-rendering)51 - [Multitemplate](#multitemplate)52 - [Redirects](#redirects)53 - [Custom Middleware](#custom-middleware)54 - [Using BasicAuth() middleware](#using-basicauth-middleware)55 - [Goroutines inside a middleware](#goroutines-inside-a-middleware)56 - [Custom HTTP configuration](#custom-http-configuration)57 - [Support Let's Encrypt](#support-lets-encrypt)58 - [Run multiple service using Gin](#run-multiple-service-using-gin)59 - [Graceful restart or stop](#graceful-restart-or-stop)60 - [Build a single binary with templates](#build-a-single-binary-with-templates)61 - [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct)62 - [Try to bind body into different structs](#try-to-bind-body-into-different-structs)63 - [http2 server push](#http2-server-push)64 - [Define format for the log of routes](#define-format-for-the-log-of-routes)65 - [Set and get a cookie](#set-and-get-a-cookie)66- [Testing](#testing)67- [Users](#users)28For more feature details, please see the [Gin website introduction](https://gin-gonic.com/docs/introduction/).2969## Installation30## Getting started3171To install Gin package, you need to install Go and set your Go workspace first.32### Getting Gin33731. Download and install it:34The first need [Go](https://golang.org/) installed (version 1.6+ is required), then you can use the below Go command to install Gin.3536```sh37$ go get -u github.com/gin-gonic/gin38```39792. Import it in your code:40For more installation guides such as vendor tool, please check out [Gin quickstart](https://gin-gonic.com/docs/quickstart/).4181```go82import "github.com/gin-gonic/gin"83```42### Running Gin43853. (Optional) Import `net/http`. This is required for example if using constants such as `http.StatusOK`.44First you need to import Gin package for using Gin, one simplest example likes the follow `example.go`:4546```go88import "net/http"89```9091### Use a vendor tool like [Govendor](https://github.com/kardianos/govendor)92931. `go get` govendor9495```sh96$ go get github.com/kardianos/govendor97```982. Create your project folder and `cd` inside99100```sh101$ mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"102```1031043. Vendor init your project and add gin105106```sh107$ govendor init108$ govendor fetch github.com/gin-gonic/gin@v1.3109```1101114. Copy a starting template inside your project112113```sh114$ curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go115```1161175. Run your project118119```sh120$ go run main.go121```122123## Prerequisite124125Now Gin requires Go 1.6 or later and Go 1.7 will be required soon.126127## Quick start128 129```sh130# assume the following codes in example.go file131$ cat example.go132```133134```go47package main4849import "github.com/gin-gonic/gin"50
7 unmodified lines
58 r.Run() // listen and serve on 0.0.0.0:808059}60```6162And use the Go command to run the demo:6364```65# run example.go and visit 0.0.0.0:8080/ping on browser66$ go run example.go67```6869## Benchmarks70157Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter)71Please see all benchmarks details from [Gin website](https://gin-gonic.com/docs/benchmarks/).72159[See all benchmarks](/BENCHMARKS.md)16073Benchmark name | (1) | (2) | (3) | (4)74--------------------------------------------|-----------:|------------:|-----------:|---------:75**BenchmarkGin_GithubAll** | **30000** | **48375** | **0** | **0**76BenchmarkAce_GithubAll | 10000 | 134059 | 13792 | 167
27 unmodified lines
104- (2): Single Repetition Duration (ns/op), lower is better105- (3): Heap Memory (B/op), lower is better106- (4): Average Allocations per Repetition (allocs/op), lower is better107196## Gin v1. stable108## Middlewares109198- [x] Zero allocation router.199- [x] Still the fastest http router and framework. From routing to writing.200- [x] Complete suite of unit tests201- [x] Battle tested202- [x] API frozen, new releases will not break your code.110You can find many useful Gin middlewares at [gin-contrib](https://github.com/gin-contrib).111204## Build with [jsoniter](https://github.com/json-iterator/go)112## Documentation113206Gin uses `encoding/json` as default json package but you can change to [jsoniter](https://github.com/json-iterator/go) by build from other tags.114All documentation is available on the Gin website.115208```sh209$ go build -tags=jsoniter .210```116- [English](https://gin-gonic.com/docs/)117- [简体中文](https://gin-gonic.com/zh-cn/docs/)118- [繁體中文](https://gin-gonic.com/zh-tw/docs/)119- [にほんご](https://gin-gonic.com/ja/docs/)120212## API Examples121## Examples122214You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples).123A number of ready-to-run examples demonstrating various use cases of Gin on the [Gin examples](https://github.com/gin-gonic/examples) repository.124216### Using GET, POST, PUT, PATCH, DELETE and OPTIONS125## Users126218```go219func main() {220 // Creates a gin router with default middleware:221 // logger and recovery (crash-free) middleware222 router := gin.Default()127[Gin website](https://gin-gonic.com/docs/users/) lists some awesome projects made with Gin web framework.128224 router.GET("/someGet", getting)225 router.POST("/somePost", posting)226 router.PUT("/somePut", putting)227 router.DELETE("/someDelete", deleting)228 router.PATCH("/somePatch", patching)229 router.HEAD("/someHead", head)230 router.OPTIONS("/someOptions", options)129## Contributing130232 // By default it serves on :8080 unless a233 // PORT environment variable was defined.234 router.Run()235 // router.Run(":3000") for a hard coded port236}237```131Gin is the work of hundreds of contributors. We appreciate your help!132239### Parameters in path133Please see [CONTRIBUTING](CONTRIBUTING.md) for details on submitting patches and the contribution workflow.134241```go242func main() {243 router := gin.Default()244245 // This handler will match /user/john but will not match /user/ or /user246 router.GET("/user/:name", func(c *gin.Context) {247 name := c.Param("name")248 c.String(http.StatusOK, "Hello %s", name)249 })250251 // However, this one will match /user/john/ and also /user/john/send252 // If no other routers match /user/john, it will redirect to /user/john/253 router.GET("/user/:name/*action", func(c *gin.Context) {254 name := c.Param("name")255 action := c.Param("action")256 message := name + " is " + action257 c.String(http.StatusOK, message)258 })259260 router.Run(":8080")261}262```263264### Querystring parameters265266```go267func main() {268 router := gin.Default()269270 // Query string parameters are parsed using the existing underlying request object.271 // The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe272 router.GET("/welcome", func(c *gin.Context) {273 firstname := c.DefaultQuery("firstname", "Guest")274 lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")275276 c.String(http.StatusOK, "Hello %s %s", firstname, lastname)277 })278 router.Run(":8080")279}280```281282### Multipart/Urlencoded Form283284```go285func main() {286 router := gin.Default()287288 router.POST("/form_post", func(c *gin.Context) {289 message := c.PostForm("message")290 nick := c.DefaultPostForm("nick", "anonymous")291292 c.JSON(200, gin.H{293 "status": "posted",294 "message": message,295 "nick": nick,296 })297 })298 router.Run(":8080")299}300```301302### Another example: query + post form303304```305POST /post?id=1234&page=1 HTTP/1.1306Content-Type: application/x-www-form-urlencoded307308name=manu&message=this_is_great309```310311```go312func main() {313 router := gin.Default()314315 router.POST("/post", func(c *gin.Context) {316317 id := c.Query("id")318 page := c.DefaultQuery("page", "0")319 name := c.PostForm("name")320 message := c.PostForm("message")321322 fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)323 })324 router.Run(":8080")325}326```327328```329id: 1234; page: 1; name: manu; message: this_is_great330```331332### Map as querystring or postform parameters333334```335POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1336Content-Type: application/x-www-form-urlencoded337338names[first]=thinkerou&names[second]=tianou339```340341```go342func main() {343 router := gin.Default()344345 router.POST("/post", func(c *gin.Context) {346347 ids := c.QueryMap("ids")348 names := c.PostFormMap("names")349350 fmt.Printf("ids: %v; names: %v", ids, names)351 })352 router.Run(":8080")353}354```355356```357ids: map[b:hello a:1234], names: map[second:tianou first:thinkerou]358```359360### Upload files361362#### Single file363364References issue [#774](https://github.com/gin-gonic/gin/issues/774) and detail [example code](https://github.com/gin-gonic/examples/tree/master/upload-file/single).365366`file.Filename` **SHOULD NOT** be trusted. See [`Content-Disposition` on MDN](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition#Directives) and [#1693](https://github.com/gin-gonic/gin/issues/1693)367368> The filename is always optional and must not be used blindly by the application: path information should be stripped, and conversion to the server file system rules should be done.369370```go371func main() {372 router := gin.Default()373 // Set a lower memory limit for multipart forms (default is 32 MiB)374 // router.MaxMultipartMemory = 8 << 20 // 8 MiB375 router.POST("/upload", func(c *gin.Context) {376 // single file377 file, _ := c.FormFile("file")378 log.Println(file.Filename)379380 // Upload the file to specific dst.381 // c.SaveUploadedFile(file, dst)382383 c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))384 })385 router.Run(":8080")386}387```388389How to `curl`:390391```bash392curl -X POST http://localhost:8080/upload \393 -F "file=@/Users/appleboy/test.zip" \394 -H "Content-Type: multipart/form-data"395```396397#### Multiple files398399See the detail [example code](https://github.com/gin-gonic/examples/tree/master/upload-file/multiple).400401```go402func main() {403 router := gin.Default()404 // Set a lower memory limit for multipart forms (default is 32 MiB)405 // router.MaxMultipartMemory = 8 << 20 // 8 MiB406 router.POST("/upload", func(c *gin.Context) {407 // Multipart form408 form, _ := c.MultipartForm()409 files := form.File["upload[]"]410411 for _, file := range files {412 log.Println(file.Filename)413414 // Upload the file to specific dst.415 // c.SaveUploadedFile(file, dst)416 }417 c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))418 })419 router.Run(":8080")420}421```422423How to `curl`:424425```bash426curl -X POST http://localhost:8080/upload \427 -F "upload[]=@/Users/appleboy/test1.zip" \428 -F "upload[]=@/Users/appleboy/test2.zip" \429 -H "Content-Type: multipart/form-data"430```431432### Grouping routes433434```go435func main() {436 router := gin.Default()437438 // Simple group: v1439 v1 := router.Group("/v1")440 {441 v1.POST("/login", loginEndpoint)442 v1.POST("/submit", submitEndpoint)443 v1.POST("/read", readEndpoint)444 }445446 // Simple group: v2447 v2 := router.Group("/v2")448 {449 v2.POST("/login", loginEndpoint)450 v2.POST("/submit", submitEndpoint)451 v2.POST("/read", readEndpoint)452 }453454 router.Run(":8080")455}456```457458### Blank Gin without middleware by default459460Use461462```go463r := gin.New()464```465466instead of467468```go469// Default With the Logger and Recovery middleware already attached470r := gin.Default()471```472473474### Using middleware475```go476func main() {477 // Creates a router without any middleware by default478 r := gin.New()479480 // Global middleware481 // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.482 // By default gin.DefaultWriter = os.Stdout483 r.Use(gin.Logger())484485 // Recovery middleware recovers from any panics and writes a 500 if there was one.486 r.Use(gin.Recovery())487488 // Per route middleware, you can add as many as you desire.489 r.GET("/benchmark", MyBenchLogger(), benchEndpoint)490491 // Authorization group492 // authorized := r.Group("/", AuthRequired())493 // exactly the same as:494 authorized := r.Group("/")495 // per group middleware! in this case we use the custom created496 // AuthRequired() middleware just in the "authorized" group.497 authorized.Use(AuthRequired())498 {499 authorized.POST("/login", loginEndpoint)500 authorized.POST("/submit", submitEndpoint)501 authorized.POST("/read", readEndpoint)502503 // nested group504 testing := authorized.Group("testing")505 testing.GET("/analytics", analyticsEndpoint)506 }507508 // Listen and serve on 0.0.0.0:8080509 r.Run(":8080")510}511```512513### How to write log file514```go515func main() {516 // Disable Console Color, you don't need console color when writing the logs to file.517 gin.DisableConsoleColor()518519 // Logging to a file.520 f, _ := os.Create("gin.log")521 gin.DefaultWriter = io.MultiWriter(f)522523 // Use the following code if you need to write the logs to file and console at the same time.524 // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)525526 router := gin.Default()527 router.GET("/ping", func(c *gin.Context) {528 c.String(200, "pong")529 })530531    router.Run(":8080")532}533```534535### Custom Log Format536```go537func main() {538 router := gin.New()539540 // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter541 // By default gin.DefaultWriter = os.Stdout542 router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {543544 // your custom format545 return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",546 param.ClientIP,547 param.TimeStamp.Format(time.RFC1123),548 param.Method,549 param.Path,550 param.Request.Proto,551 param.StatusCode,552 param.Latency,553 param.Request.UserAgent(),554 param.ErrorMessage,555 )556 }))557 router.Use(gin.Recovery())558559 router.GET("/ping", func(c *gin.Context) {560 c.String(200, "pong")561 })562563 router.Run(":8080")564}565```566567**Sample Output**568```569::1 - [Fri, 07 Dec 2018 17:04:38 JST] "GET /ping HTTP/1.1 200 122.767µs "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.80 Safari/537.36" "570```571572### Controlling Log output coloring 573574By default, logs output on console should be colorized depending on the detected TTY.575576Never colorize logs: 577578```go579func main() {580 // Disable log's color581 gin.DisableConsoleColor()582 583 // Creates a gin router with default middleware:584 // logger and recovery (crash-free) middleware585 router := gin.Default()586 587 router.GET("/ping", func(c *gin.Context) {588 c.String(200, "pong")589 })590 591 router.Run(":8080")592}593```594595Always colorize logs: 596597```go598func main() {599 // Force log's color600 gin.ForceConsoleColor()601 602 // Creates a gin router with default middleware:603 // logger and recovery (crash-free) middleware604 router := gin.Default()605 606 router.GET("/ping", func(c *gin.Context) {607 c.String(200, "pong")608 })609 610 router.Run(":8080")611}612```613614### Model binding and validation615616To bind a request body into a type, use model binding. We currently support binding of JSON, XML, YAML and standard form values (foo=bar&boo=baz).617618Gin uses [**go-playground/validator.v8**](https://github.com/go-playground/validator) for validation. Check the full docs on tags usage [here](http://godoc.org/gopkg.in/go-playground/validator.v8#hdr-Baked_In_Validators_and_Tags).619620Note that you need to set the corresponding binding tag on all fields you want to bind. For example, when binding from JSON, set `json:"fieldname"`.621622Also, Gin provides two sets of methods for binding:623- **Type** - Must bind624 - **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`625 - **Behavior** - These methods use `MustBindWith` under the hood. If there is a binding error, the request is aborted with `c.AbortWithError(400, err).SetType(ErrorTypeBind)`. This sets the response status code to 400 and the `Content-Type` header is set to `text/plain; charset=utf-8`. Note that if you try to set the response code after this, it will result in a warning `[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422`. If you wish to have greater control over the behavior, consider using the `ShouldBind` equivalent method.626- **Type** - Should bind627 - **Methods** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindXML`, `ShouldBindQuery`, `ShouldBindYAML`628 - **Behavior** - These methods use `ShouldBindWith` under the hood. If there is a binding error, the error is returned and it is the developer's responsibility to handle the request and error appropriately.629630When using the Bind-method, Gin tries to infer the binder depending on the Content-Type header. If you are sure what you are binding, you can use `MustBindWith` or `ShouldBindWith`.631632You can also specify that specific fields are required. If a field is decorated with `binding:"required"` and has a empty value when binding, an error will be returned.633634```go635// Binding from JSON636type Login struct {637 User string `form:"user" json:"user" xml:"user" binding:"required"`638 Password string `form:"password" json:"password" xml:"password" binding:"required"`639}640641func main() {642 router := gin.Default()643644 // Example for binding JSON ({"user": "manu", "password": "123"})645 router.POST("/loginJSON", func(c *gin.Context) {646 var json Login647 if err := c.ShouldBindJSON(&json); err != nil {648 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})649 return650 }651 652 if json.User != "manu" || json.Password != "123" {653 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})654 return655 } 656 657 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})658 })659660 // Example for binding XML (661 // <?xml version="1.0" encoding="UTF-8"?>662 // <root>663 // <user>user</user>664 // <password>123</password>665 // </root>)666 router.POST("/loginXML", func(c *gin.Context) {667 var xml Login668 if err := c.ShouldBindXML(&xml); err != nil {669 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})670 return671 }672 673 if xml.User != "manu" || xml.Password != "123" {674 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})675 return676 } 677 678 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})679 })680681 // Example for binding a HTML form (user=manu&password=123)682 router.POST("/loginForm", func(c *gin.Context) {683 var form Login684 // This will infer what binder to use depending on the content-type header.685 if err := c.ShouldBind(&form); err != nil {686 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})687 return688 }689 690 if form.User != "manu" || form.Password != "123" {691 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})692 return693 } 694 695 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})696 })697698 // Listen and serve on 0.0.0.0:8080699 router.Run(":8080")700}701```702703**Sample request**704```shell705$ curl -v -X POST \706 http://localhost:8080/loginJSON \707 -H 'content-type: application/json' \708 -d '{ "user": "manu" }'709> POST /loginJSON HTTP/1.1710> Host: localhost:8080711> User-Agent: curl/7.51.0712> Accept: */*713> content-type: application/json714> Content-Length: 18715>716* upload completely sent off: 18 out of 18 bytes717< HTTP/1.1 400 Bad Request718< Content-Type: application/json; charset=utf-8719< Date: Fri, 04 Aug 2017 03:51:31 GMT720< Content-Length: 100721<722{"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}723```724725**Skip validate**726727When running the above example using the above the `curl` command, it returns error. Because the example use `binding:"required"` for `Password`. If use `binding:"-"` for `Password`, then it will not return error when running the above example again.728729### Custom Validators730731It is also possible to register custom validators. See the [example code](https://github.com/gin-gonic/examples/tree/master/custom-validation/server.go).732733```go734package main735736import (737 "net/http"738 "reflect"739 "time"740741 "github.com/gin-gonic/gin"742 "github.com/gin-gonic/gin/binding"743 "gopkg.in/go-playground/validator.v8"744)745746// Booking contains binded and validated data.747type Booking struct {748 CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`749 CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`750}751752func bookableDate(753 v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,754 field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,755) bool {756 if date, ok := field.Interface().(time.Time); ok {757 today := time.Now()758 if today.Year() > date.Year() || today.YearDay() > date.YearDay() {759 return false760 }761 }762 return true763}764765func main() {766 route := gin.Default()767768 if v, ok := binding.Validator.Engine().(*validator.Validate); ok {769 v.RegisterValidation("bookabledate", bookableDate)770 }771772 route.GET("/bookable", getBookable)773 route.Run(":8085")774}775776func getBookable(c *gin.Context) {777 var b Booking778 if err := c.ShouldBindWith(&b, binding.Query); err == nil {779 c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})780 } else {781 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})782 }783}784```785786```console787$ curl "localhost:8085/bookable?check_in=2018-04-16&check_out=2018-04-17"788{"message":"Booking dates are valid!"}789790$ curl "localhost:8085/bookable?check_in=2018-03-08&check_out=2018-03-09"791{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}792```793794[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way.795See the [struct-lvl-validation example](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) to learn more.796797### Only Bind Query String798799`ShouldBindQuery` function only binds the query params and not the post data. See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-315953017).800801```go802package main803804import (805 "log"806807 "github.com/gin-gonic/gin"808)809810type Person struct {811 Name string `form:"name"`812 Address string `form:"address"`813}814815func main() {816 route := gin.Default()817 route.Any("/testing", startPage)818 route.Run(":8085")819}820821func startPage(c *gin.Context) {822 var person Person823 if c.ShouldBindQuery(&person) == nil {824 log.Println("====== Only Bind By Query String ======")825 log.Println(person.Name)826 log.Println(person.Address)827 }828 c.String(200, "Success")829}830831```832833### Bind Query String or Post Data834835See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292).836837```go838package main839840import (841 "log"842 "time"843844 "github.com/gin-gonic/gin"845)846847type Person struct {848 Name string `form:"name"`849 Address string `form:"address"`850 Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`851}852853func main() {854 route := gin.Default()855 route.GET("/testing", startPage)856 route.Run(":8085")857}858859func startPage(c *gin.Context) {860 var person Person861 // If `GET`, only `Form` binding engine (`query`) used.862 // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).863 // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48864 if c.ShouldBind(&person) == nil {865 log.Println(person.Name)866 log.Println(person.Address)867 log.Println(person.Birthday)868 }869870 c.String(200, "Success")871}872```873874Test it with:875```sh876$ curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15"877```878879### Bind Uri880881See the [detail information](https://github.com/gin-gonic/gin/issues/846).882883```go884package main885886import "github.com/gin-gonic/gin"887888type Person struct {889 ID string `uri:"id" binding:"required,uuid"`890 Name string `uri:"name" binding:"required"`891}892893func main() {894 route := gin.Default()895 route.GET("/:name/:id", func(c *gin.Context) {896 var person Person897 if err := c.ShouldBindUri(&person); err != nil {898 c.JSON(400, gin.H{"msg": err})899 return900 }901 c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID})902 })903 route.Run(":8088")904}905```906907Test it with:908```sh909$ curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3910$ curl -v localhost:8088/thinkerou/not-uuid911```912913### Bind HTML checkboxes914915See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)916917main.go918919```go920...921922type myForm struct {923 Colors []string `form:"colors[]"`924}925926...927928func formHandler(c *gin.Context) {929 var fakeForm myForm930 c.ShouldBind(&fakeForm)931 c.JSON(200, gin.H{"color": fakeForm.Colors})932}933934...935936```937938form.html939940```html941<form action="/" method="POST">942 <p>Check some colors</p>943 <label for="red">Red</label>944 <input type="checkbox" name="colors[]" value="red" id="red">945 <label for="green">Green</label>946 <input type="checkbox" name="colors[]" value="green" id="green">947 <label for="blue">Blue</label>948 <input type="checkbox" name="colors[]" value="blue" id="blue">949 <input type="submit">950</form>951```952953result:954955```956{"color":["red","green","blue"]}957```958959### Multipart/Urlencoded binding960961```go962package main963964import (965 "github.com/gin-gonic/gin"966)967968type LoginForm struct {969 User string `form:"user" binding:"required"`970 Password string `form:"password" binding:"required"`971}972973func main() {974 router := gin.Default()975 router.POST("/login", func(c *gin.Context) {976 // you can bind multipart form with explicit binding declaration:977 // c.ShouldBindWith(&form, binding.Form)978 // or you can simply use autobinding with ShouldBind method:979 var form LoginForm980 // in this case proper binding will be automatically selected981 if c.ShouldBind(&form) == nil {982 if form.User == "user" && form.Password == "password" {983 c.JSON(200, gin.H{"status": "you are logged in"})984 } else {985 c.JSON(401, gin.H{"status": "unauthorized"})986 }987 }988 })989 router.Run(":8080")990}991```992993Test it with:994```sh995$ curl -v --form user=user --form password=password http://localhost:8080/login996```997998### XML, JSON, YAML and ProtoBuf rendering9991000```go1001func main() {1002 r := gin.Default()10031004 // gin.H is a shortcut for map[string]interface{}1005 r.GET("/someJSON", func(c *gin.Context) {1006 c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1007 })10081009 r.GET("/moreJSON", func(c *gin.Context) {1010 // You also can use a struct1011 var msg struct {1012 Name string `json:"user"`1013 Message string1014 Number int1015 }1016 msg.Name = "Lena"1017 msg.Message = "hey"1018 msg.Number = 1231019 // Note that msg.Name becomes "user" in the JSON1020 // Will output : {"user": "Lena", "Message": "hey", "Number": 123}1021 c.JSON(http.StatusOK, msg)1022 })10231024 r.GET("/someXML", func(c *gin.Context) {1025 c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1026 })10271028 r.GET("/someYAML", func(c *gin.Context) {1029 c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1030 })10311032 r.GET("/someProtoBuf", func(c *gin.Context) {1033 reps := []int64{int64(1), int64(2)}1034 label := "test"1035 // The specific definition of protobuf is written in the testdata/protoexample file.1036 data := &protoexample.Test{1037 Label: &label,1038 Reps: reps,1039 }1040 // Note that data becomes binary data in the response1041 // Will output protoexample.Test protobuf serialized data1042 c.ProtoBuf(http.StatusOK, data)1043 })10441045 // Listen and serve on 0.0.0.0:80801046 r.Run(":8080")1047}1048```10491050#### SecureJSON10511052Using SecureJSON to prevent json hijacking. Default prepends `"while(1),"` to response body if the given struct is array values.10531054```go1055func main() {1056 r := gin.Default()10571058 // You can also use your own secure json prefix1059 // r.SecureJsonPrefix(")]}',\n")10601061 r.GET("/someJSON", func(c *gin.Context) {1062 names := []string{"lena", "austin", "foo"}10631064 // Will output : while(1);["lena","austin","foo"]1065 c.SecureJSON(http.StatusOK, names)1066 })10671068 // Listen and serve on 0.0.0.0:80801069 r.Run(":8080")1070}1071```1072#### JSONP10731074Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists.10751076```go1077func main() {1078 r := gin.Default()10791080 r.GET("/JSONP?callback=x", func(c *gin.Context) {1081 data := map[string]interface{}{1082 "foo": "bar",1083 }1084 1085 //callback is x1086 // Will output : x({\"foo\":\"bar\"})1087 c.JSONP(http.StatusOK, data)1088 })10891090 // Listen and serve on 0.0.0.0:80801091 r.Run(":8080")1092}1093```10941095#### AsciiJSON10961097Using AsciiJSON to Generates ASCII-only JSON with escaped non-ASCII chracters.10981099```go1100func main() {1101 r := gin.Default()11021103 r.GET("/someJSON", func(c *gin.Context) {1104 data := map[string]interface{}{1105 "lang": "GO语言",1106 "tag": "<br>",1107 }11081109 // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}1110 c.AsciiJSON(http.StatusOK, data)1111 })11121113 // Listen and serve on 0.0.0.0:80801114 r.Run(":8080")1115}1116```11171118#### PureJSON11191120Normally, JSON replaces special HTML characters with their unicode entities, e.g. `<` becomes `\u003c`. If you want to encode such characters literally, you can use PureJSON instead.1121This feature is unavailable in Go 1.6 and lower.11221123```go1124func main() {1125 r := gin.Default()1126 1127 // Serves unicode entities1128 r.GET("/json", func(c *gin.Context) {1129 c.JSON(200, gin.H{1130 "html": "<b>Hello, world!</b>",1131 })1132 })1133 1134 // Serves literal characters1135 r.GET("/purejson", func(c *gin.Context) {1136 c.PureJSON(200, gin.H{1137 "html": "<b>Hello, world!</b>",1138 })1139 })1140 1141 // listen and serve on 0.0.0.0:80801142 r.Run(":8080")1143}1144```11451146### Serving static files11471148```go1149func main() {1150 router := gin.Default()1151 router.Static("/assets", "./assets")1152 router.StaticFS("/more_static", http.Dir("my_file_system"))1153 router.StaticFile("/favicon.ico", "./resources/favicon.ico")11541155 // Listen and serve on 0.0.0.0:80801156 router.Run(":8080")1157}1158```11591160### Serving data from reader11611162```go1163func main() {1164 router := gin.Default()1165 router.GET("/someDataFromReader", func(c *gin.Context) {1166 response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")1167 if err != nil || response.StatusCode != http.StatusOK {1168 c.Status(http.StatusServiceUnavailable)1169 return1170 }11711172 reader := response.Body1173 contentLength := response.ContentLength1174 contentType := response.Header.Get("Content-Type")11751176 extraHeaders := map[string]string{1177 "Content-Disposition": `attachment; filename="gopher.png"`,1178 }11791180 c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)1181 })1182 router.Run(":8080")1183}1184```11851186### HTML rendering11871188Using LoadHTMLGlob() or LoadHTMLFiles()11891190```go1191func main() {1192 router := gin.Default()1193 router.LoadHTMLGlob("templates/*")1194 //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")1195 router.GET("/index", func(c *gin.Context) {1196 c.HTML(http.StatusOK, "index.tmpl", gin.H{1197 "title": "Main website",1198 })1199 })1200 router.Run(":8080")1201}1202```12031204templates/index.tmpl12051206```html1207<html>1208 <h1>1209 {{ .title }}1210 </h1>1211</html>1212```12131214Using templates with same name in different directories12151216```go1217func main() {1218 router := gin.Default()1219 router.LoadHTMLGlob("templates/**/*")1220 router.GET("/posts/index", func(c *gin.Context) {1221 c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{1222 "title": "Posts",1223 })1224 })1225 router.GET("/users/index", func(c *gin.Context) {1226 c.HTML(http.StatusOK, "users/index.tmpl", gin.H{1227 "title": "Users",1228 })1229 })1230 router.Run(":8080")1231}1232```12331234templates/posts/index.tmpl12351236```html1237{{ define "posts/index.tmpl" }}1238<html><h1>1239 {{ .title }}1240</h1>1241<p>Using posts/index.tmpl</p>1242</html>1243{{ end }}1244```12451246templates/users/index.tmpl12471248```html1249{{ define "users/index.tmpl" }}1250<html><h1>1251 {{ .title }}1252</h1>1253<p>Using users/index.tmpl</p>1254</html>1255{{ end }}1256```12571258#### Custom Template renderer12591260You can also use your own html template render12611262```go1263import "html/template"12641265func main() {1266 router := gin.Default()1267 html := template.Must(template.ParseFiles("file1", "file2"))1268 router.SetHTMLTemplate(html)1269 router.Run(":8080")1270}1271```12721273#### Custom Delimiters12741275You may use custom delims12761277```go1278 r := gin.Default()1279 r.Delims("{[{", "}]}")1280 r.LoadHTMLGlob("/path/to/templates")1281```12821283#### Custom Template Funcs12841285See the detail [example code](https://github.com/gin-gonic/examples/tree/master/template).12861287main.go12881289```go1290import (1291 "fmt"1292 "html/template"1293 "net/http"1294 "time"12951296 "github.com/gin-gonic/gin"1297)12981299func formatAsDate(t time.Time) string {1300 year, month, day := t.Date()1301 return fmt.Sprintf("%d%02d/%02d", year, month, day)1302}13031304func main() {1305 router := gin.Default()1306 router.Delims("{[{", "}]}")1307 router.SetFuncMap(template.FuncMap{1308 "formatAsDate": formatAsDate,1309 })1310 router.LoadHTMLFiles("./testdata/template/raw.tmpl")13111312 router.GET("/raw", func(c *gin.Context) {1313 c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{1314 "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),1315 })1316 })13171318 router.Run(":8080")1319}13201321```13221323raw.tmpl13241325```html1326Date: {[{.now | formatAsDate}]}1327```13281329Result:1330```1331Date: 2017/07/011332```13331334### Multitemplate13351336Gin allow by default use only one html.Template. Check [a multitemplate render](https://github.com/gin-contrib/multitemplate) for using features like go 1.6 `block template`.13371338### Redirects13391340Issuing a HTTP redirect is easy. Both internal and external locations are supported.13411342```go1343r.GET("/test", func(c *gin.Context) {1344 c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")1345})1346```134713481349Issuing a Router redirect, use `HandleContext` like below.13501351``` go1352r.GET("/test", func(c *gin.Context) {1353 c.Request.URL.Path = "/test2"1354 r.HandleContext(c)1355})1356r.GET("/test2", func(c *gin.Context) {1357 c.JSON(200, gin.H{"hello": "world"})1358})1359```136013611362### Custom Middleware13631364```go1365func Logger() gin.HandlerFunc {1366 return func(c *gin.Context) {1367 t := time.Now()13681369 // Set example variable1370 c.Set("example", "12345")13711372 // before request13731374 c.Next()13751376 // after request1377 latency := time.Since(t)1378 log.Print(latency)13791380 // access the status we are sending1381 status := c.Writer.Status()1382 log.Println(status)1383 }1384}13851386func main() {1387 r := gin.New()1388 r.Use(Logger())13891390 r.GET("/test", func(c *gin.Context) {1391 example := c.MustGet("example").(string)13921393 // it would print: "12345"1394 log.Println(example)1395 })13961397 // Listen and serve on 0.0.0.0:80801398 r.Run(":8080")1399}1400```14011402### Using BasicAuth() middleware14031404```go1405// simulate some private data1406var secrets = gin.H{1407 "foo": gin.H{"email": "foo@bar.com", "phone": "123433"},1408 "austin": gin.H{"email": "austin@example.com", "phone": "666"},1409 "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},1410}14111412func main() {1413 r := gin.Default()14141415 // Group using gin.BasicAuth() middleware1416 // gin.Accounts is a shortcut for map[string]string1417 authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{1418 "foo": "bar",1419 "austin": "1234",1420 "lena": "hello2",1421 "manu": "4321",1422 }))14231424 // /admin/secrets endpoint1425 // hit "localhost:8080/admin/secrets1426 authorized.GET("/secrets", func(c *gin.Context) {1427 // get user, it was set by the BasicAuth middleware1428 user := c.MustGet(gin.AuthUserKey).(string)1429 if secret, ok := secrets[user]; ok {1430 c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})1431 } else {1432 c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})1433 }1434 })14351436 // Listen and serve on 0.0.0.0:80801437 r.Run(":8080")1438}1439```14401441### Goroutines inside a middleware14421443When starting new Goroutines inside a middleware or handler, you **SHOULD NOT** use the original context inside it, you have to use a read-only copy.14441445```go1446func main() {1447 r := gin.Default()14481449 r.GET("/long_async", func(c *gin.Context) {1450 // create copy to be used inside the goroutine1451 cCp := c.Copy()1452 go func() {1453 // simulate a long task with time.Sleep(). 5 seconds1454 time.Sleep(5 * time.Second)14551456 // note that you are using the copied context "cCp", IMPORTANT1457 log.Println("Done! in path " + cCp.Request.URL.Path)1458 }()1459 })14601461 r.GET("/long_sync", func(c *gin.Context) {1462 // simulate a long task with time.Sleep(). 5 seconds1463 time.Sleep(5 * time.Second)14641465 // since we are NOT using a goroutine, we do not have to copy the context1466 log.Println("Done! in path " + c.Request.URL.Path)1467 })14681469 // Listen and serve on 0.0.0.0:80801470 r.Run(":8080")1471}1472```14731474### Custom HTTP configuration14751476Use `http.ListenAndServe()` directly, like this:14771478```go1479func main() {1480 router := gin.Default()1481 http.ListenAndServe(":8080", router)1482}1483```1484or14851486```go1487func main() {1488 router := gin.Default()14891490 s := &http.Server{1491 Addr: ":8080",1492 Handler: router,1493 ReadTimeout: 10 * time.Second,1494 WriteTimeout: 10 * time.Second,1495 MaxHeaderBytes: 1 << 20,1496 }1497 s.ListenAndServe()1498}1499```15001501### Support Let's Encrypt15021503example for 1-line LetsEncrypt HTTPS servers.15041505```go1506package main15071508import (1509 "log"15101511 "github.com/gin-gonic/autotls"1512 "github.com/gin-gonic/gin"1513)15141515func main() {1516 r := gin.Default()15171518 // Ping handler1519 r.GET("/ping", func(c *gin.Context) {1520 c.String(200, "pong")1521 })15221523 log.Fatal(autotls.Run(r, "example1.com", "example2.com"))1524}1525```15261527example for custom autocert manager.15281529```go1530package main15311532import (1533 "log"15341535 "github.com/gin-gonic/autotls"1536 "github.com/gin-gonic/gin"1537 "golang.org/x/crypto/acme/autocert"1538)15391540func main() {1541 r := gin.Default()15421543 // Ping handler1544 r.GET("/ping", func(c *gin.Context) {1545 c.String(200, "pong")1546 })15471548 m := autocert.Manager{1549 Prompt: autocert.AcceptTOS,1550 HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),1551 Cache: autocert.DirCache("/var/www/.cache"),1552 }15531554 log.Fatal(autotls.RunWithManager(r, &m))1555}1556```15571558### Run multiple service using Gin15591560See the [question](https://github.com/gin-gonic/gin/issues/346) and try the following example:15611562```go1563package main15641565import (1566 "log"1567 "net/http"1568 "time"15691570 "github.com/gin-gonic/gin"1571 "golang.org/x/sync/errgroup"1572)15731574var (1575 g errgroup.Group1576)15771578func router01() http.Handler {1579 e := gin.New()1580 e.Use(gin.Recovery())1581 e.GET("/", func(c *gin.Context) {1582 c.JSON(1583 http.StatusOK,1584 gin.H{1585 "code": http.StatusOK,1586 "error": "Welcome server 01",1587 },1588 )1589 })15901591 return e1592}15931594func router02() http.Handler {1595 e := gin.New()1596 e.Use(gin.Recovery())1597 e.GET("/", func(c *gin.Context) {1598 c.JSON(1599 http.StatusOK,1600 gin.H{1601 "code": http.StatusOK,1602 "error": "Welcome server 02",1603 },1604 )1605 })16061607 return e1608}16091610func main() {1611 server01 := &http.Server{1612 Addr: ":8080",1613 Handler: router01(),1614 ReadTimeout: 5 * time.Second,1615 WriteTimeout: 10 * time.Second,1616 }16171618 server02 := &http.Server{1619 Addr: ":8081",1620 Handler: router02(),1621 ReadTimeout: 5 * time.Second,1622 WriteTimeout: 10 * time.Second,1623 }16241625 g.Go(func() error {1626 return server01.ListenAndServe()1627 })16281629 g.Go(func() error {1630 return server02.ListenAndServe()1631 })16321633 if err := g.Wait(); err != nil {1634 log.Fatal(err)1635 }1636}1637```16381639### Graceful restart or stop16401641Do you want to graceful restart or stop your web server?1642There are some ways this can be done.16431644We can use [fvbock/endless](https://github.com/fvbock/endless) to replace the default `ListenAndServe`. Refer issue [#296](https://github.com/gin-gonic/gin/issues/296) for more details.16451646```go1647router := gin.Default()1648router.GET("/", handler)1649// [...]1650endless.ListenAndServe(":4242", router)1651```16521653An alternative to endless:16541655* [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully.1656* [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server.1657* [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers.16581659If 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](https://github.com/gin-gonic/examples/tree/master/graceful-shutdown) example with gin.16601661```go1662// +build go1.816631664package main16651666import (1667 "context"1668 "log"1669 "net/http"1670 "os"1671 "os/signal"1672 "syscall"1673 "time"16741675 "github.com/gin-gonic/gin"1676)16771678func main() {1679 router := gin.Default()1680 router.GET("/", func(c *gin.Context) {1681 time.Sleep(5 * time.Second)1682 c.String(http.StatusOK, "Welcome Gin Server")1683 })16841685 srv := &http.Server{1686 Addr: ":8080",1687 Handler: router,1688 }16891690 go func() {1691 // service connections1692 if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {1693 log.Fatalf("listen: %s\n", err)1694 }1695 }()16961697 // Wait for interrupt signal to gracefully shutdown the server with1698 // a timeout of 5 seconds.1699 quit := make(chan os.Signal)1700 // kill (no param) default send syscanll.SIGTERM1701 // kill -2 is syscall.SIGINT1702 // kill -9 is syscall. SIGKILL but can"t be catch, so don't need add it1703 signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)1704 <-quit1705 log.Println("Shutdown Server ...")17061707 ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)1708 defer cancel()1709 if err := srv.Shutdown(ctx); err != nil {1710 log.Fatal("Server Shutdown:", err)1711 }1712 // catching ctx.Done(). timeout of 5 seconds.1713 select {1714 case <-ctx.Done():1715 log.Println("timeout of 5 seconds.")1716 }1717 log.Println("Server exiting")1718}1719```17201721### Build a single binary with templates17221723You can build a server into a single binary containing templates by using [go-assets][].17241725[go-assets]: https://github.com/jessevdk/go-assets17261727```go1728func main() {1729 r := gin.New()17301731 t, err := loadTemplate()1732 if err != nil {1733 panic(err)1734 }1735 r.SetHTMLTemplate(t)17361737 r.GET("/", func(c *gin.Context) {1738 c.HTML(http.StatusOK, "/html/index.tmpl",nil)1739 })1740 r.Run(":8080")1741}17421743// loadTemplate loads templates embedded by go-assets-builder1744func loadTemplate() (*template.Template, error) {1745 t := template.New("")1746 for name, file := range Assets.Files {1747 if file.IsDir() || !strings.HasSuffix(name, ".tmpl") {1748 continue1749 }1750 h, err := ioutil.ReadAll(file)1751 if err != nil {1752 return nil, err1753 }1754 t, err = t.New(name).Parse(string(h))1755 if err != nil {1756 return nil, err1757 }1758 }1759 return t, nil1760}1761```17621763See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary` directory.17641765### Bind form-data request with custom struct17661767The follow example using custom struct:17681769```go1770type StructA struct {1771 FieldA string `form:"field_a"`1772}17731774type StructB struct {1775 NestedStruct StructA1776 FieldB string `form:"field_b"`1777}17781779type StructC struct {1780 NestedStructPointer *StructA1781 FieldC string `form:"field_c"`1782}17831784type StructD struct {1785 NestedAnonyStruct struct {1786 FieldX string `form:"field_x"`1787 }1788 FieldD string `form:"field_d"`1789}17901791func GetDataB(c *gin.Context) {1792 var b StructB1793 c.Bind(&b)1794 c.JSON(200, gin.H{1795 "a": b.NestedStruct,1796 "b": b.FieldB,1797 })1798}17991800func GetDataC(c *gin.Context) {1801 var b StructC1802 c.Bind(&b)1803 c.JSON(200, gin.H{1804 "a": b.NestedStructPointer,1805 "c": b.FieldC,1806 })1807}18081809func GetDataD(c *gin.Context) {1810 var b StructD1811 c.Bind(&b)1812 c.JSON(200, gin.H{1813 "x": b.NestedAnonyStruct,1814 "d": b.FieldD,1815 })1816}18171818func main() {1819 r := gin.Default()1820 r.GET("/getb", GetDataB)1821 r.GET("/getc", GetDataC)1822 r.GET("/getd", GetDataD)18231824 r.Run()1825}1826```18271828Using the command `curl` command result:18291830```1831$ curl "http://localhost:8080/getb?field_a=hello&field_b=world"1832{"a":{"FieldA":"hello"},"b":"world"}1833$ curl "http://localhost:8080/getc?field_a=hello&field_c=world"1834{"a":{"FieldA":"hello"},"c":"world"}1835$ curl "http://localhost:8080/getd?field_x=hello&field_d=world"1836{"d":"world","x":{"FieldX":"hello"}}1837```18381839### Try to bind body into different structs18401841The normal methods for binding request body consumes `c.Request.Body` and they1842cannot be called multiple times.18431844```go1845type formA struct {1846 Foo string `json:"foo" xml:"foo" binding:"required"`1847}18481849type formB struct {1850 Bar string `json:"bar" xml:"bar" binding:"required"`1851}18521853func SomeHandler(c *gin.Context) {1854 objA := formA{}1855 objB := formB{}1856 // This c.ShouldBind consumes c.Request.Body and it cannot be reused.1857 if errA := c.ShouldBind(&objA); errA == nil {1858 c.String(http.StatusOK, `the body should be formA`)1859 // Always an error is occurred by this because c.Request.Body is EOF now.1860 } else if errB := c.ShouldBind(&objB); errB == nil {1861 c.String(http.StatusOK, `the body should be formB`)1862 } else {1863 ...1864 }1865}1866```18671868For this, you can use `c.ShouldBindBodyWith`.18691870```go1871func SomeHandler(c *gin.Context) {1872 objA := formA{}1873 objB := formB{}1874 // This reads c.Request.Body and stores the result into the context.1875 if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil {1876 c.String(http.StatusOK, `the body should be formA`)1877 // At this time, it reuses body stored in the context.1878 } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {1879 c.String(http.StatusOK, `the body should be formB JSON`)1880 // And it can accepts other formats1881 } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {1882 c.String(http.StatusOK, `the body should be formB XML`)1883 } else {1884 ...1885 }1886}1887```18881889* `c.ShouldBindBodyWith` stores body into the context before binding. This has1890a slight impact to performance, so you should not use this method if you are1891enough to call binding at once.1892* This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`,1893`ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`,1894can be called by `c.ShouldBind()` multiple times without any damage to1895performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)).18961897### http2 server push18981899http.Pusher is supported only **go1.8+**. See the [golang blog](https://blog.golang.org/h2push) for detail information.19001901```go1902package main19031904import (1905 "html/template"1906 "log"19071908 "github.com/gin-gonic/gin"1909)19101911var html = template.Must(template.New("https").Parse(`1912<html>1913<head>1914 <title>Https Test</title>1915 <script src="/assets/app.js"></script>1916</head>1917<body>1918 <h1 style="color:red;">Welcome, Ginner!</h1>1919</body>1920</html>1921`))19221923func main() {1924 r := gin.Default()1925 r.Static("/assets", "./assets")1926 r.SetHTMLTemplate(html)19271928 r.GET("/", func(c *gin.Context) {1929 if pusher := c.Writer.Pusher(); pusher != nil {1930 // use pusher.Push() to do server push1931 if err := pusher.Push("/assets/app.js", nil); err != nil {1932 log.Printf("Failed to push: %v", err)1933 }1934 }1935 c.HTML(200, "https", gin.H{1936 "status": "success",1937 })1938 })19391940 // Listen and Server in https://127.0.0.1:80801941 r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")1942}1943```19441945### Define format for the log of routes19461947The default log of routes is:1948```1949[GIN-debug] POST /foo --> main.main.func1 (3 handlers)1950[GIN-debug] GET /bar --> main.main.func2 (3 handlers)1951[GIN-debug] GET /status --> main.main.func3 (3 handlers)1952```19531954If you want to log this information in given format (e.g. JSON, key values or something else), then you can define this format with `gin.DebugPrintRouteFunc`.1955In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs.1956```go1957import (1958 "log"1959 "net/http"19601961 "github.com/gin-gonic/gin"1962)19631964func main() {1965 r := gin.Default()1966 gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {1967 log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers)1968 }19691970 r.POST("/foo", func(c *gin.Context) {1971 c.JSON(http.StatusOK, "foo")1972 })19731974 r.GET("/bar", func(c *gin.Context) {1975 c.JSON(http.StatusOK, "bar")1976 })19771978 r.GET("/status", func(c *gin.Context) {1979 c.JSON(http.StatusOK, "ok")1980 })19811982 // Listen and Server in http://0.0.0.0:80801983 r.Run()1984}1985```19861987### Set and get a cookie19881989```go1990import (1991 "fmt"19921993 "github.com/gin-gonic/gin"1994)19951996func main() {19971998 router := gin.Default()19992000 router.GET("/cookie", func(c *gin.Context) {20012002 cookie, err := c.Cookie("gin_cookie")20032004 if err != nil {2005 cookie = "NotSet"2006 c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)2007 }20082009 fmt.Printf("Cookie value: %s \n", cookie)2010 })20112012 router.Run()2013}2014```201520162017## Testing20182019The `net/http/httptest` package is preferable way for HTTP testing.20202021```go2022package main20232024func setupRouter() *gin.Engine {2025 r := gin.Default()2026 r.GET("/ping", func(c *gin.Context) {2027 c.String(200, "pong")2028 })2029 return r2030}20312032func main() {2033 r := setupRouter()2034 r.Run(":8080")2035}2036```20372038Test for code example above:20392040```go2041package main20422043import (2044 "net/http"2045 "net/http/httptest"2046 "testing"20472048 "github.com/stretchr/testify/assert"2049)20502051func TestPingRoute(t *testing.T) {2052 router := setupRouter()20532054 w := httptest.NewRecorder()2055 req, _ := http.NewRequest("GET", "/ping", nil)2056 router.ServeHTTP(w, req)20572058 assert.Equal(t, 200, w.Code)2059 assert.Equal(t, "pong", w.Body.String())2060}2061```20622063## Users20642065Awesome project lists using [Gin](https://github.com/gin-gonic/gin) web framework.20662067* [gorush](https://github.com/appleboy/gorush): A push notification server written in Go.2068* [fnproject](https://github.com/fnproject/fn): The container native, cloud agnostic serverless platform.2069* [photoprism](https://github.com/photoprism/photoprism): Personal photo management powered by Go and Google TensorFlow.2070* [krakend](https://github.com/devopsfaith/krakend): Ultra performant API Gateway with middlewares.2071* [picfit](https://github.com/thoas/picfit): An image resizing server written in Go.