docs(readme): move more example to docs/doc.md (#3449)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by thinkerou · committed by GitHub · parent 8659ab5 · Browse files · 2 files·+2316 added−2272 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
2 files+2316 added−2272 removed
- other:+2316 added−2272 removed
Provenance
- Commit
82e1c53- Tree
b8a2a47- Author
thinkerou <thinkerou@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
8659ab5
2 files changed+2316 added−2272 removed
added:docs/doc.md+2246 added
1+# Gin Quick Start2+3+## Contents4+5+- [Build Tags](#build-tags)6+ - [Build with json replacement](#build-with-json-replacement)7+ - [Build without `MsgPack` rendering feature](#build-without-msgpack-rendering-feature)8+- [API Examples](#api-examples)9+ - [Using GET, POST, PUT, PATCH, DELETE and OPTIONS](#using-get-post-put-patch-delete-and-options)10+ - [Parameters in path](#parameters-in-path)11+ - [Querystring parameters](#querystring-parameters)12+ - [Multipart/Urlencoded Form](#multiparturlencoded-form)13+ - [Another example: query + post form](#another-example-query--post-form)14+ - [Map as querystring or postform parameters](#map-as-querystring-or-postform-parameters)15+ - [Upload files](#upload-files)16+ - [Single file](#single-file)17+ - [Multiple files](#multiple-files)18+ - [Grouping routes](#grouping-routes)19+ - [Blank Gin without middleware by default](#blank-gin-without-middleware-by-default)20+ - [Using middleware](#using-middleware)21+ - [Custom Recovery behavior](#custom-recovery-behavior)22+ - [How to write log file](#how-to-write-log-file)23+ - [Custom Log Format](#custom-log-format)24+ - [Controlling Log output coloring](#controlling-log-output-coloring)25+ - [Model binding and validation](#model-binding-and-validation)26+ - [Custom Validators](#custom-validators)27+ - [Only Bind Query String](#only-bind-query-string)28+ - [Bind Query String or Post Data](#bind-query-string-or-post-data)29+ - [Bind Uri](#bind-uri)30+ - [Bind Header](#bind-header)31+ - [Bind HTML checkboxes](#bind-html-checkboxes)32+ - [Multipart/Urlencoded binding](#multiparturlencoded-binding)33+ - [XML, JSON, YAML, TOML and ProtoBuf rendering](#xml-json-yaml-toml-and-protobuf-rendering)34+ - [SecureJSON](#securejson)35+ - [JSONP](#jsonp)36+ - [AsciiJSON](#asciijson)37+ - [PureJSON](#purejson)38+ - [Serving static files](#serving-static-files)39+ - [Serving data from file](#serving-data-from-file)40+ - [Serving data from reader](#serving-data-from-reader)41+ - [HTML rendering](#html-rendering)42+ - [Custom Template renderer](#custom-template-renderer)43+ - [Custom Delimiters](#custom-delimiters)44+ - [Custom Template Funcs](#custom-template-funcs)45+ - [Multitemplate](#multitemplate)46+ - [Redirects](#redirects)47+ - [Custom Middleware](#custom-middleware)48+ - [Using BasicAuth() middleware](#using-basicauth-middleware)49+ - [Goroutines inside a middleware](#goroutines-inside-a-middleware)50+ - [Custom HTTP configuration](#custom-http-configuration)51+ - [Support Let's Encrypt](#support-lets-encrypt)52+ - [Run multiple service using Gin](#run-multiple-service-using-gin)53+ - [Graceful shutdown or restart](#graceful-shutdown-or-restart)54+ - [Third-party packages](#third-party-packages)55+ - [Manually](#manually)56+ - [Build a single binary with templates](#build-a-single-binary-with-templates)57+ - [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct)58+ - [Try to bind body into different structs](#try-to-bind-body-into-different-structs)59+ - [Bind form-data request with custom struct and custom tag](#bind-form-data-request-with-custom-struct-and-custom-tag)60+ - [http2 server push](#http2-server-push)61+ - [Define format for the log of routes](#define-format-for-the-log-of-routes)62+ - [Set and get a cookie](#set-and-get-a-cookie)63+- [Don't trust all proxies](#dont-trust-all-proxies)64+- [Testing](#testing)65+66+## Build tags67+68+### Build with json replacement69+70+Gin uses `encoding/json` as default json package but you can change it by build from other tags.71+72+[jsoniter](https://github.com/json-iterator/go)73+74+```sh75+go build -tags=jsoniter .76+```77+78+[go-json](https://github.com/goccy/go-json)79+80+```sh81+go build -tags=go_json .82+```83+84+[sonic](https://github.com/bytedance/sonic) (you have to ensure that your cpu support avx instruction.)85+86+```sh87+$ go build -tags="sonic avx" .88+```89+90+### Build without `MsgPack` rendering feature91+92+Gin enables `MsgPack` rendering feature by default. But you can disable this feature by specifying `nomsgpack` build tag.93+94+```sh95+go build -tags=nomsgpack .96+```97+98+This is useful to reduce the binary size of executable files. See the [detail information](https://github.com/gin-gonic/gin/pull/1852).99+100+## API Examples101+102+You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples).103+104+### Using GET, POST, PUT, PATCH, DELETE and OPTIONS105+106+```go107+func main() {108+ // Creates a gin router with default middleware:109+ // logger and recovery (crash-free) middleware110+ router := gin.Default()111+112+ router.GET("/someGet", getting)113+ router.POST("/somePost", posting)114+ router.PUT("/somePut", putting)115+ router.DELETE("/someDelete", deleting)116+ router.PATCH("/somePatch", patching)117+ router.HEAD("/someHead", head)118+ router.OPTIONS("/someOptions", options)119+120+ // By default it serves on :8080 unless a121+ // PORT environment variable was defined.122+ router.Run()123+ // router.Run(":3000") for a hard coded port124+}125+```126+127+### Parameters in path128+129+```go130+func main() {131+ router := gin.Default()132+133+ // This handler will match /user/john but will not match /user/ or /user134+ router.GET("/user/:name", func(c *gin.Context) {135+ name := c.Param("name")136+ c.String(http.StatusOK, "Hello %s", name)137+ })138+139+ // However, this one will match /user/john/ and also /user/john/send140+ // If no other routers match /user/john, it will redirect to /user/john/141+ router.GET("/user/:name/*action", func(c *gin.Context) {142+ name := c.Param("name")143+ action := c.Param("action")144+ message := name + " is " + action145+ c.String(http.StatusOK, message)146+ })147+148+ // For each matched request Context will hold the route definition149+ router.POST("/user/:name/*action", func(c *gin.Context) {150+ b := c.FullPath() == "/user/:name/*action" // true151+ c.String(http.StatusOK, "%t", b)152+ })153+154+ // This handler will add a new router for /user/groups.155+ // Exact routes are resolved before param routes, regardless of the order they were defined.156+ // Routes starting with /user/groups are never interpreted as /user/:name/... routes157+ router.GET("/user/groups", func(c *gin.Context) {158+ c.String(http.StatusOK, "The available groups are [...]")159+ })160+161+ router.Run(":8080")162+}163+```164+165+### Querystring parameters166+167+```go168+func main() {169+ router := gin.Default()170+171+ // Query string parameters are parsed using the existing underlying request object.172+ // The request responds to an url matching: /welcome?firstname=Jane&lastname=Doe173+ router.GET("/welcome", func(c *gin.Context) {174+ firstname := c.DefaultQuery("firstname", "Guest")175+ lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")176+177+ c.String(http.StatusOK, "Hello %s %s", firstname, lastname)178+ })179+ router.Run(":8080")180+}181+```182+183+### Multipart/Urlencoded Form184+185+```go186+func main() {187+ router := gin.Default()188+189+ router.POST("/form_post", func(c *gin.Context) {190+ message := c.PostForm("message")191+ nick := c.DefaultPostForm("nick", "anonymous")192+193+ c.JSON(http.StatusOK, gin.H{194+ "status": "posted",195+ "message": message,196+ "nick": nick,197+ })198+ })199+ router.Run(":8080")200+}201+```202+203+### Another example: query + post form204+205+```sh206+POST /post?id=1234&page=1 HTTP/1.1207+Content-Type: application/x-www-form-urlencoded208+209+name=manu&message=this_is_great210+```211+212+```go213+func main() {214+ router := gin.Default()215+216+ router.POST("/post", func(c *gin.Context) {217+218+ id := c.Query("id")219+ page := c.DefaultQuery("page", "0")220+ name := c.PostForm("name")221+ message := c.PostForm("message")222+223+ fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)224+ })225+ router.Run(":8080")226+}227+```228+229+```sh230+id: 1234; page: 1; name: manu; message: this_is_great231+```232+233+### Map as querystring or postform parameters234+235+```sh236+POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1237+Content-Type: application/x-www-form-urlencoded238+239+names[first]=thinkerou&names[second]=tianou240+```241+242+```go243+func main() {244+ router := gin.Default()245+246+ router.POST("/post", func(c *gin.Context) {247+248+ ids := c.QueryMap("ids")249+ names := c.PostFormMap("names")250+251+ fmt.Printf("ids: %v; names: %v", ids, names)252+ })253+ router.Run(":8080")254+}255+```256+257+```sh258+ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou]259+```260+261+### Upload files262+263+#### Single file264+265+References 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).266+267+`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)268+269+> 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.270+271+```go272+func main() {273+ router := gin.Default()274+ // Set a lower memory limit for multipart forms (default is 32 MiB)275+ router.MaxMultipartMemory = 8 << 20 // 8 MiB276+ router.POST("/upload", func(c *gin.Context) {277+ // Single file278+ file, _ := c.FormFile("file")279+ log.Println(file.Filename)280+281+ // Upload the file to specific dst.282+ c.SaveUploadedFile(file, dst)283+284+ c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))285+ })286+ router.Run(":8080")287+}288+```289+290+How to `curl`:291+292+```bash293+curl -X POST http://localhost:8080/upload \294+ -F "file=@/Users/appleboy/test.zip" \295+ -H "Content-Type: multipart/form-data"296+```297+298+#### Multiple files299+300+See the detail [example code](https://github.com/gin-gonic/examples/tree/master/upload-file/multiple).301+302+```go303+func main() {304+ router := gin.Default()305+ // Set a lower memory limit for multipart forms (default is 32 MiB)306+ router.MaxMultipartMemory = 8 << 20 // 8 MiB307+ router.POST("/upload", func(c *gin.Context) {308+ // Multipart form309+ form, _ := c.MultipartForm()310+ files := form.File["upload[]"]311+312+ for _, file := range files {313+ log.Println(file.Filename)314+315+ // Upload the file to specific dst.316+ c.SaveUploadedFile(file, dst)317+ }318+ c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))319+ })320+ router.Run(":8080")321+}322+```323+324+How to `curl`:325+326+```bash327+curl -X POST http://localhost:8080/upload \328+ -F "upload[]=@/Users/appleboy/test1.zip" \329+ -F "upload[]=@/Users/appleboy/test2.zip" \330+ -H "Content-Type: multipart/form-data"331+```332+333+### Grouping routes334+335+```go336+func main() {337+ router := gin.Default()338+339+ // Simple group: v1340+ v1 := router.Group("/v1")341+ {342+ v1.POST("/login", loginEndpoint)343+ v1.POST("/submit", submitEndpoint)344+ v1.POST("/read", readEndpoint)345+ }346+347+ // Simple group: v2348+ v2 := router.Group("/v2")349+ {350+ v2.POST("/login", loginEndpoint)351+ v2.POST("/submit", submitEndpoint)352+ v2.POST("/read", readEndpoint)353+ }354+355+ router.Run(":8080")356+}357+```358+359+### Blank Gin without middleware by default360+361+Use362+363+```go364+r := gin.New()365+```366+367+instead of368+369+```go370+// Default With the Logger and Recovery middleware already attached371+r := gin.Default()372+```373+374+### Using middleware375+376+```go377+func main() {378+ // Creates a router without any middleware by default379+ r := gin.New()380+381+ // Global middleware382+ // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.383+ // By default gin.DefaultWriter = os.Stdout384+ r.Use(gin.Logger())385+386+ // Recovery middleware recovers from any panics and writes a 500 if there was one.387+ r.Use(gin.Recovery())388+389+ // Per route middleware, you can add as many as you desire.390+ r.GET("/benchmark", MyBenchLogger(), benchEndpoint)391+392+ // Authorization group393+ // authorized := r.Group("/", AuthRequired())394+ // exactly the same as:395+ authorized := r.Group("/")396+ // per group middleware! in this case we use the custom created397+ // AuthRequired() middleware just in the "authorized" group.398+ authorized.Use(AuthRequired())399+ {400+ authorized.POST("/login", loginEndpoint)401+ authorized.POST("/submit", submitEndpoint)402+ authorized.POST("/read", readEndpoint)403+404+ // nested group405+ testing := authorized.Group("testing")406+ // visit 0.0.0.0:8080/testing/analytics407+ testing.GET("/analytics", analyticsEndpoint)408+ }409+410+ // Listen and serve on 0.0.0.0:8080411+ r.Run(":8080")412+}413+```414+415+### Custom Recovery behavior416+417+```go418+func main() {419+ // Creates a router without any middleware by default420+ r := gin.New()421+422+ // Global middleware423+ // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.424+ // By default gin.DefaultWriter = os.Stdout425+ r.Use(gin.Logger())426+427+ // Recovery middleware recovers from any panics and writes a 500 if there was one.428+ r.Use(gin.CustomRecovery(func(c *gin.Context, recovered interface{}) {429+ if err, ok := recovered.(string); ok {430+ c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))431+ }432+ c.AbortWithStatus(http.StatusInternalServerError)433+ }))434+435+ r.GET("/panic", func(c *gin.Context) {436+ // panic with a string -- the custom middleware could save this to a database or report it to the user437+ panic("foo")438+ })439+440+ r.GET("/", func(c *gin.Context) {441+ c.String(http.StatusOK, "ohai")442+ })443+444+ // Listen and serve on 0.0.0.0:8080445+ r.Run(":8080")446+}447+```448+449+### How to write log file450+451+```go452+func main() {453+ // Disable Console Color, you don't need console color when writing the logs to file.454+ gin.DisableConsoleColor()455+456+ // Logging to a file.457+ f, _ := os.Create("gin.log")458+ gin.DefaultWriter = io.MultiWriter(f)459+460+ // Use the following code if you need to write the logs to file and console at the same time.461+ // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)462+463+ router := gin.Default()464+ router.GET("/ping", func(c *gin.Context) {465+ c.String(http.StatusOK, "pong")466+ })467+468+ router.Run(":8080")469+}470+```471+472+### Custom Log Format473+474+```go475+func main() {476+ router := gin.New()477+478+ // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter479+ // By default gin.DefaultWriter = os.Stdout480+ router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {481+482+ // your custom format483+ return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",484+ param.ClientIP,485+ param.TimeStamp.Format(time.RFC1123),486+ param.Method,487+ param.Path,488+ param.Request.Proto,489+ param.StatusCode,490+ param.Latency,491+ param.Request.UserAgent(),492+ param.ErrorMessage,493+ )494+ }))495+ router.Use(gin.Recovery())496+497+ router.GET("/ping", func(c *gin.Context) {498+ c.String(http.StatusOK, "pong")499+ })500+501+ router.Run(":8080")502+}503+```504+505+Sample Output506+507+```sh508+::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" "509+```510+511+### Controlling Log output coloring512+513+By default, logs output on console should be colorized depending on the detected TTY.514+515+Never colorize logs:516+517+```go518+func main() {519+ // Disable log's color520+ gin.DisableConsoleColor()521+522+ // Creates a gin router with default middleware:523+ // logger and recovery (crash-free) middleware524+ router := gin.Default()525+526+ router.GET("/ping", func(c *gin.Context) {527+ c.String(http.StatusOK, "pong")528+ })529+530+ router.Run(":8080")531+}532+```533+534+Always colorize logs:535+536+```go537+func main() {538+ // Force log's color539+ gin.ForceConsoleColor()540+541+ // Creates a gin router with default middleware:542+ // logger and recovery (crash-free) middleware543+ router := gin.Default()544+545+ router.GET("/ping", func(c *gin.Context) {546+ c.String(http.StatusOK, "pong")547+ })548+549+ router.Run(":8080")550+}551+```552+553+### Model binding and validation554+555+To bind a request body into a type, use model binding. We currently support binding of JSON, XML, YAML, TOML and standard form values (foo=bar&boo=baz).556+557+Gin uses [**go-playground/validator/v10**](https://github.com/go-playground/validator) for validation. Check the full docs on tags usage [here](https://pkg.go.dev/github.com/go-playground/validator#hdr-Baked_In_Validators_and_Tags).558+559+Note 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"`.560+561+Also, Gin provides two sets of methods for binding:562+563+- **Type** - Must bind564+ - **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`, `BindHeader`, `BindTOML`565+ - **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.566+- **Type** - Should bind567+ - **Methods** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindXML`, `ShouldBindQuery`, `ShouldBindYAML`, `ShouldBindHeader`, `ShouldBindTOML`,568+ - **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.569+570+When 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`.571+572+You can also specify that specific fields are required. If a field is decorated with `binding:"required"` and has an empty value when binding, an error will be returned.573+574+```go575+// Binding from JSON576+type Login struct {577+ User string `form:"user" json:"user" xml:"user" binding:"required"`578+ Password string `form:"password" json:"password" xml:"password" binding:"required"`579+}580+581+func main() {582+ router := gin.Default()583+584+ // Example for binding JSON ({"user": "manu", "password": "123"})585+ router.POST("/loginJSON", func(c *gin.Context) {586+ var json Login587+ if err := c.ShouldBindJSON(&json); err != nil {588+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})589+ return590+ }591+592+ if json.User != "manu" || json.Password != "123" {593+ c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})594+ return595+ }596+597+ c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})598+ })599+600+ // Example for binding XML (601+ // <?xml version="1.0" encoding="UTF-8"?>602+ // <root>603+ // <user>manu</user>604+ // <password>123</password>605+ // </root>)606+ router.POST("/loginXML", func(c *gin.Context) {607+ var xml Login608+ if err := c.ShouldBindXML(&xml); err != nil {609+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})610+ return611+ }612+613+ if xml.User != "manu" || xml.Password != "123" {614+ c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})615+ return616+ }617+618+ c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})619+ })620+621+ // Example for binding a HTML form (user=manu&password=123)622+ router.POST("/loginForm", func(c *gin.Context) {623+ var form Login624+ // This will infer what binder to use depending on the content-type header.625+ if err := c.ShouldBind(&form); err != nil {626+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})627+ return628+ }629+630+ if form.User != "manu" || form.Password != "123" {631+ c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})632+ return633+ }634+635+ c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})636+ })637+638+ // Listen and serve on 0.0.0.0:8080639+ router.Run(":8080")640+}641+```642+643+Sample request644+645+```sh646+$ curl -v -X POST \647+ http://localhost:8080/loginJSON \648+ -H 'content-type: application/json' \649+ -d '{ "user": "manu" }'650+> POST /loginJSON HTTP/1.1651+> Host: localhost:8080652+> User-Agent: curl/7.51.0653+> Accept: */*654+> content-type: application/json655+> Content-Length: 18656+>657+* upload completely sent off: 18 out of 18 bytes658+< HTTP/1.1 400 Bad Request659+< Content-Type: application/json; charset=utf-8660+< Date: Fri, 04 Aug 2017 03:51:31 GMT661+< Content-Length: 100662+<663+{"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}664+```665+666+Skip validate: when 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.667+668+### Custom Validators669+670+It is also possible to register custom validators. See the [example code](https://github.com/gin-gonic/examples/tree/master/custom-validation/server.go).671+672+```go673+package main674+675+import (676+ "net/http"677+ "time"678+679+ "github.com/gin-gonic/gin"680+ "github.com/gin-gonic/gin/binding"681+ "github.com/go-playground/validator/v10"682+)683+684+// Booking contains binded and validated data.685+type Booking struct {686+ CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`687+ CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`688+}689+690+var bookableDate validator.Func = func(fl validator.FieldLevel) bool {691+ date, ok := fl.Field().Interface().(time.Time)692+ if ok {693+ today := time.Now()694+ if today.After(date) {695+ return false696+ }697+ }698+ return true699+}700+701+func main() {702+ route := gin.Default()703+704+ if v, ok := binding.Validator.Engine().(*validator.Validate); ok {705+ v.RegisterValidation("bookabledate", bookableDate)706+ }707+708+ route.GET("/bookable", getBookable)709+ route.Run(":8085")710+}711+712+func getBookable(c *gin.Context) {713+ var b Booking714+ if err := c.ShouldBindWith(&b, binding.Query); err == nil {715+ c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})716+ } else {717+ c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})718+ }719+}720+```721+722+```console723+$ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17"724+{"message":"Booking dates are valid!"}725+726+$ curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09"727+{"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"}728+729+$ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10"730+{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}%731+```732+733+[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way.734+See the [struct-lvl-validation example](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) to learn more.735+736+### Only Bind Query String737+738+`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).739+740+```go741+package main742+743+import (744+ "log"745+ "net/http"746+747+ "github.com/gin-gonic/gin"748+)749+750+type Person struct {751+ Name string `form:"name"`752+ Address string `form:"address"`753+}754+755+func main() {756+ route := gin.Default()757+ route.Any("/testing", startPage)758+ route.Run(":8085")759+}760+761+func startPage(c *gin.Context) {762+ var person Person763+ if c.ShouldBindQuery(&person) == nil {764+ log.Println("====== Only Bind By Query String ======")765+ log.Println(person.Name)766+ log.Println(person.Address)767+ }768+ c.String(http.StatusOK, "Success")769+}770+771+```772+773+### Bind Query String or Post Data774+775+See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292).776+777+```go778+package main779+780+import (781+ "log"782+ "net/http"783+ "time"784+785+ "github.com/gin-gonic/gin"786+)787+788+type Person struct {789+ Name string `form:"name"`790+ Address string `form:"address"`791+ Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`792+ CreateTime time.Time `form:"createTime" time_format:"unixNano"`793+ UnixTime time.Time `form:"unixTime" time_format:"unix"`794+}795+796+func main() {797+ route := gin.Default()798+ route.GET("/testing", startPage)799+ route.Run(":8085")800+}801+802+func startPage(c *gin.Context) {803+ var person Person804+ // If `GET`, only `Form` binding engine (`query`) used.805+ // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).806+ // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L88807+ if c.ShouldBind(&person) == nil {808+ log.Println(person.Name)809+ log.Println(person.Address)810+ log.Println(person.Birthday)811+ log.Println(person.CreateTime)812+ log.Println(person.UnixTime)813+ }814+815+ c.String(http.StatusOK, "Success")816+}817+```818+819+Test it with:820+821+```sh822+curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"823+```824+825+### Bind Uri826+827+See the [detail information](https://github.com/gin-gonic/gin/issues/846).828+829+```go830+package main831+832+import (833+ "net/http"834+835+ "github.com/gin-gonic/gin"836+)837+838+type Person struct {839+ ID string `uri:"id" binding:"required,uuid"`840+ Name string `uri:"name" binding:"required"`841+}842+843+func main() {844+ route := gin.Default()845+ route.GET("/:name/:id", func(c *gin.Context) {846+ var person Person847+ if err := c.ShouldBindUri(&person); err != nil {848+ c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})849+ return850+ }851+ c.JSON(http.StatusOK, gin.H{"name": person.Name, "uuid": person.ID})852+ })853+ route.Run(":8088")854+}855+```856+857+Test it with:858+859+```sh860+curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3861+curl -v localhost:8088/thinkerou/not-uuid862+```863+864+### Bind Header865+866+```go867+package main868+869+import (870+ "fmt"871+ "net/http"872+873+ "github.com/gin-gonic/gin"874+)875+876+type testHeader struct {877+ Rate int `header:"Rate"`878+ Domain string `header:"Domain"`879+}880+881+func main() {882+ r := gin.Default()883+ r.GET("/", func(c *gin.Context) {884+ h := testHeader{}885+886+ if err := c.ShouldBindHeader(&h); err != nil {887+ c.JSON(http.StatusOK, err)888+ }889+890+ fmt.Printf("%#v\n", h)891+ c.JSON(http.StatusOK, gin.H{"Rate": h.Rate, "Domain": h.Domain})892+ })893+894+ r.Run()895+896+// client897+// curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/898+// output899+// {"Domain":"music","Rate":300}900+}901+```902+903+### Bind HTML checkboxes904+905+See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)906+907+main.go908+909+```go910+...911+912+type myForm struct {913+ Colors []string `form:"colors[]"`914+}915+916+...917+918+func formHandler(c *gin.Context) {919+ var fakeForm myForm920+ c.ShouldBind(&fakeForm)921+ c.JSON(http.StatusOK, gin.H{"color": fakeForm.Colors})922+}923+924+...925+926+```927+928+form.html929+930+```html931+<form action="/" method="POST">932+ <p>Check some colors</p>933+ <label for="red">Red</label>934+ <input type="checkbox" name="colors[]" value="red" id="red">935+ <label for="green">Green</label>936+ <input type="checkbox" name="colors[]" value="green" id="green">937+ <label for="blue">Blue</label>938+ <input type="checkbox" name="colors[]" value="blue" id="blue">939+ <input type="submit">940+</form>941+```942+943+result:944+945+```json946+{"color":["red","green","blue"]}947+```948+949+### Multipart/Urlencoded binding950+951+```go952+type ProfileForm struct {953+ Name string `form:"name" binding:"required"`954+ Avatar *multipart.FileHeader `form:"avatar" binding:"required"`955+956+ // or for multiple files957+ // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"`958+}959+960+func main() {961+ router := gin.Default()962+ router.POST("/profile", func(c *gin.Context) {963+ // you can bind multipart form with explicit binding declaration:964+ // c.ShouldBindWith(&form, binding.Form)965+ // or you can simply use autobinding with ShouldBind method:966+ var form ProfileForm967+ // in this case proper binding will be automatically selected968+ if err := c.ShouldBind(&form); err != nil {969+ c.String(http.StatusBadRequest, "bad request")970+ return971+ }972+973+ err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename)974+ if err != nil {975+ c.String(http.StatusInternalServerError, "unknown error")976+ return977+ }978+979+ // db.Save(&form)980+981+ c.String(http.StatusOK, "ok")982+ })983+ router.Run(":8080")984+}985+```986+987+Test it with:988+989+```sh990+curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile991+```992+993+### XML, JSON, YAML, TOML and ProtoBuf rendering994+995+```go996+func main() {997+ r := gin.Default()998+999+ // gin.H is a shortcut for map[string]interface{}1000+ r.GET("/someJSON", func(c *gin.Context) {1001+ c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1002+ })1003+1004+ r.GET("/moreJSON", func(c *gin.Context) {1005+ // You also can use a struct1006+ var msg struct {1007+ Name string `json:"user"`1008+ Message string1009+ Number int1010+ }1011+ msg.Name = "Lena"1012+ msg.Message = "hey"1013+ msg.Number = 1231014+ // Note that msg.Name becomes "user" in the JSON1015+ // Will output : {"user": "Lena", "Message": "hey", "Number": 123}1016+ c.JSON(http.StatusOK, msg)1017+ })1018+1019+ r.GET("/someXML", func(c *gin.Context) {1020+ c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1021+ })1022+1023+ r.GET("/someYAML", func(c *gin.Context) {1024+ c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1025+ })1026+1027+ r.GET("/someTOML", func(c *gin.Context) {1028+ c.TOML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1029+ })1030+1031+ r.GET("/someProtoBuf", func(c *gin.Context) {1032+ reps := []int64{int64(1), int64(2)}1033+ label := "test"1034+ // The specific definition of protobuf is written in the testdata/protoexample file.1035+ data := &protoexample.Test{1036+ Label: &label,1037+ Reps: reps,1038+ }1039+ // Note that data becomes binary data in the response1040+ // Will output protoexample.Test protobuf serialized data1041+ c.ProtoBuf(http.StatusOK, data)1042+ })1043+1044+ // Listen and serve on 0.0.0.0:80801045+ r.Run(":8080")1046+}1047+```1048+1049+#### SecureJSON1050+1051+Using SecureJSON to prevent json hijacking. Default prepends `"while(1),"` to response body if the given struct is array values.1052+1053+```go1054+func main() {1055+ r := gin.Default()1056+1057+ // You can also use your own secure json prefix1058+ // r.SecureJsonPrefix(")]}',\n")1059+1060+ r.GET("/someJSON", func(c *gin.Context) {1061+ names := []string{"lena", "austin", "foo"}1062+1063+ // Will output : while(1);["lena","austin","foo"]1064+ c.SecureJSON(http.StatusOK, names)1065+ })1066+1067+ // Listen and serve on 0.0.0.0:80801068+ r.Run(":8080")1069+}1070+```1071+1072+#### JSONP1073+1074+Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists.1075+1076+```go1077+func main() {1078+ r := gin.Default()1079+1080+ r.GET("/JSONP", func(c *gin.Context) {1081+ data := gin.H{1082+ "foo": "bar",1083+ }1084+1085+ //callback is x1086+ // Will output : x({\"foo\":\"bar\"})1087+ c.JSONP(http.StatusOK, data)1088+ })1089+1090+ // Listen and serve on 0.0.0.0:80801091+ r.Run(":8080")1092+1093+ // client1094+ // curl http://127.0.0.1:8080/JSONP?callback=x1095+}1096+```1097+1098+#### AsciiJSON1099+1100+Using AsciiJSON to Generates ASCII-only JSON with escaped non-ASCII characters.1101+1102+```go1103+func main() {1104+ r := gin.Default()1105+1106+ r.GET("/someJSON", func(c *gin.Context) {1107+ data := gin.H{1108+ "lang": "GO语言",1109+ "tag": "<br>",1110+ }1111+1112+ // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}1113+ c.AsciiJSON(http.StatusOK, data)1114+ })1115+1116+ // Listen and serve on 0.0.0.0:80801117+ r.Run(":8080")1118+}1119+```1120+1121+#### PureJSON1122+1123+Normally, 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.1124+This feature is unavailable in Go 1.6 and lower.1125+1126+```go1127+func main() {1128+ r := gin.Default()1129+1130+ // Serves unicode entities1131+ r.GET("/json", func(c *gin.Context) {1132+ c.JSON(http.StatusOK, gin.H{1133+ "html": "<b>Hello, world!</b>",1134+ })1135+ })1136+1137+ // Serves literal characters1138+ r.GET("/purejson", func(c *gin.Context) {1139+ c.PureJSON(http.StatusOK, gin.H{1140+ "html": "<b>Hello, world!</b>",1141+ })1142+ })1143+1144+ // listen and serve on 0.0.0.0:80801145+ r.Run(":8080")1146+}1147+```1148+1149+### Serving static files1150+1151+```go1152+func main() {1153+ router := gin.Default()1154+ router.Static("/assets", "./assets")1155+ router.StaticFS("/more_static", http.Dir("my_file_system"))1156+ router.StaticFile("/favicon.ico", "./resources/favicon.ico")1157+ router.StaticFileFS("/more_favicon.ico", "more_favicon.ico", http.Dir("my_file_system"))1158+ 1159+ // Listen and serve on 0.0.0.0:80801160+ router.Run(":8080")1161+}1162+```1163+1164+### Serving data from file1165+1166+```go1167+func main() {1168+ router := gin.Default()1169+1170+ router.GET("/local/file", func(c *gin.Context) {1171+ c.File("local/file.go")1172+ })1173+1174+ var fs http.FileSystem = // ...1175+ router.GET("/fs/file", func(c *gin.Context) {1176+ c.FileFromFS("fs/file.go", fs)1177+ })1178+}1179+1180+```1181+1182+### Serving data from reader1183+1184+```go1185+func main() {1186+ router := gin.Default()1187+ router.GET("/someDataFromReader", func(c *gin.Context) {1188+ response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")1189+ if err != nil || response.StatusCode != http.StatusOK {1190+ c.Status(http.StatusServiceUnavailable)1191+ return1192+ }1193+1194+ reader := response.Body1195+ defer reader.Close()1196+ contentLength := response.ContentLength1197+ contentType := response.Header.Get("Content-Type")1198+1199+ extraHeaders := map[string]string{1200+ "Content-Disposition": `attachment; filename="gopher.png"`,1201+ }1202+1203+ c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)1204+ })1205+ router.Run(":8080")1206+}1207+```1208+1209+### HTML rendering1210+1211+Using LoadHTMLGlob() or LoadHTMLFiles()1212+1213+```go1214+func main() {1215+ router := gin.Default()1216+ router.LoadHTMLGlob("templates/*")1217+ //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")1218+ router.GET("/index", func(c *gin.Context) {1219+ c.HTML(http.StatusOK, "index.tmpl", gin.H{1220+ "title": "Main website",1221+ })1222+ })1223+ router.Run(":8080")1224+}1225+```1226+1227+templates/index.tmpl1228+1229+```html1230+<html>1231+ <h1>1232+ {{ .title }}1233+ </h1>1234+</html>1235+```1236+1237+Using templates with same name in different directories1238+1239+```go1240+func main() {1241+ router := gin.Default()1242+ router.LoadHTMLGlob("templates/**/*")1243+ router.GET("/posts/index", func(c *gin.Context) {1244+ c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{1245+ "title": "Posts",1246+ })1247+ })1248+ router.GET("/users/index", func(c *gin.Context) {1249+ c.HTML(http.StatusOK, "users/index.tmpl", gin.H{1250+ "title": "Users",1251+ })1252+ })1253+ router.Run(":8080")1254+}1255+```1256+1257+templates/posts/index.tmpl1258+1259+```html1260+{{ define "posts/index.tmpl" }}1261+<html><h1>1262+ {{ .title }}1263+</h1>1264+<p>Using posts/index.tmpl</p>1265+</html>1266+{{ end }}1267+```1268+1269+templates/users/index.tmpl1270+1271+```html1272+{{ define "users/index.tmpl" }}1273+<html><h1>1274+ {{ .title }}1275+</h1>1276+<p>Using users/index.tmpl</p>1277+</html>1278+{{ end }}1279+```1280+1281+#### Custom Template renderer1282+1283+You can also use your own html template render1284+1285+```go1286+import "html/template"1287+1288+func main() {1289+ router := gin.Default()1290+ html := template.Must(template.ParseFiles("file1", "file2"))1291+ router.SetHTMLTemplate(html)1292+ router.Run(":8080")1293+}1294+```1295+1296+#### Custom Delimiters1297+1298+You may use custom delims1299+1300+```go1301+ r := gin.Default()1302+ r.Delims("{[{", "}]}")1303+ r.LoadHTMLGlob("/path/to/templates")1304+```1305+1306+#### Custom Template Funcs1307+1308+See the detail [example code](https://github.com/gin-gonic/examples/tree/master/template).1309+1310+main.go1311+1312+```go1313+import (1314+ "fmt"1315+ "html/template"1316+ "net/http"1317+ "time"1318+1319+ "github.com/gin-gonic/gin"1320+)1321+1322+func formatAsDate(t time.Time) string {1323+ year, month, day := t.Date()1324+ return fmt.Sprintf("%d/%02d/%02d", year, month, day)1325+}1326+1327+func main() {1328+ router := gin.Default()1329+ router.Delims("{[{", "}]}")1330+ router.SetFuncMap(template.FuncMap{1331+ "formatAsDate": formatAsDate,1332+ })1333+ router.LoadHTMLFiles("./testdata/template/raw.tmpl")1334+1335+ router.GET("/raw", func(c *gin.Context) {1336+ c.HTML(http.StatusOK, "raw.tmpl", gin.H{1337+ "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),1338+ })1339+ })1340+1341+ router.Run(":8080")1342+}1343+1344+```1345+1346+raw.tmpl1347+1348+```html1349+Date: {[{.now | formatAsDate}]}1350+```1351+1352+Result:1353+1354+```sh1355+Date: 2017/07/011356+```1357+1358+### Multitemplate1359+1360+Gin 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`.1361+1362+### Redirects1363+1364+Issuing a HTTP redirect is easy. Both internal and external locations are supported.1365+1366+```go1367+r.GET("/test", func(c *gin.Context) {1368+ c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")1369+})1370+```1371+1372+Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444)1373+1374+```go1375+r.POST("/test", func(c *gin.Context) {1376+ c.Redirect(http.StatusFound, "/foo")1377+})1378+```1379+1380+Issuing a Router redirect, use `HandleContext` like below.1381+1382+``` go1383+r.GET("/test", func(c *gin.Context) {1384+ c.Request.URL.Path = "/test2"1385+ r.HandleContext(c)1386+})1387+r.GET("/test2", func(c *gin.Context) {1388+ c.JSON(http.StatusOK, gin.H{"hello": "world"})1389+})1390+```1391+1392+### Custom Middleware1393+1394+```go1395+func Logger() gin.HandlerFunc {1396+ return func(c *gin.Context) {1397+ t := time.Now()1398+1399+ // Set example variable1400+ c.Set("example", "12345")1401+1402+ // before request1403+1404+ c.Next()1405+1406+ // after request1407+ latency := time.Since(t)1408+ log.Print(latency)1409+1410+ // access the status we are sending1411+ status := c.Writer.Status()1412+ log.Println(status)1413+ }1414+}1415+1416+func main() {1417+ r := gin.New()1418+ r.Use(Logger())1419+1420+ r.GET("/test", func(c *gin.Context) {1421+ example := c.MustGet("example").(string)1422+1423+ // it would print: "12345"1424+ log.Println(example)1425+ })1426+1427+ // Listen and serve on 0.0.0.0:80801428+ r.Run(":8080")1429+}1430+```1431+1432+### Using BasicAuth() middleware1433+1434+```go1435+// simulate some private data1436+var secrets = gin.H{1437+ "foo": gin.H{"email": "foo@bar.com", "phone": "123433"},1438+ "austin": gin.H{"email": "austin@example.com", "phone": "666"},1439+ "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},1440+}1441+1442+func main() {1443+ r := gin.Default()1444+1445+ // Group using gin.BasicAuth() middleware1446+ // gin.Accounts is a shortcut for map[string]string1447+ authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{1448+ "foo": "bar",1449+ "austin": "1234",1450+ "lena": "hello2",1451+ "manu": "4321",1452+ }))1453+1454+ // /admin/secrets endpoint1455+ // hit "localhost:8080/admin/secrets1456+ authorized.GET("/secrets", func(c *gin.Context) {1457+ // get user, it was set by the BasicAuth middleware1458+ user := c.MustGet(gin.AuthUserKey).(string)1459+ if secret, ok := secrets[user]; ok {1460+ c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})1461+ } else {1462+ c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})1463+ }1464+ })1465+1466+ // Listen and serve on 0.0.0.0:80801467+ r.Run(":8080")1468+}1469+```1470+1471+### Goroutines inside a middleware1472+1473+When 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.1474+1475+```go1476+func main() {1477+ r := gin.Default()1478+1479+ r.GET("/long_async", func(c *gin.Context) {1480+ // create copy to be used inside the goroutine1481+ cCp := c.Copy()1482+ go func() {1483+ // simulate a long task with time.Sleep(). 5 seconds1484+ time.Sleep(5 * time.Second)1485+1486+ // note that you are using the copied context "cCp", IMPORTANT1487+ log.Println("Done! in path " + cCp.Request.URL.Path)1488+ }()1489+ })1490+1491+ r.GET("/long_sync", func(c *gin.Context) {1492+ // simulate a long task with time.Sleep(). 5 seconds1493+ time.Sleep(5 * time.Second)1494+1495+ // since we are NOT using a goroutine, we do not have to copy the context1496+ log.Println("Done! in path " + c.Request.URL.Path)1497+ })1498+1499+ // Listen and serve on 0.0.0.0:80801500+ r.Run(":8080")1501+}1502+```1503+1504+### Custom HTTP configuration1505+1506+Use `http.ListenAndServe()` directly, like this:1507+1508+```go1509+func main() {1510+ router := gin.Default()1511+ http.ListenAndServe(":8080", router)1512+}1513+```1514+1515+or1516+1517+```go1518+func main() {1519+ router := gin.Default()1520+1521+ s := &http.Server{1522+ Addr: ":8080",1523+ Handler: router,1524+ ReadTimeout: 10 * time.Second,1525+ WriteTimeout: 10 * time.Second,1526+ MaxHeaderBytes: 1 << 20,1527+ }1528+ s.ListenAndServe()1529+}1530+```1531+1532+### Support Let's Encrypt1533+1534+example for 1-line LetsEncrypt HTTPS servers.1535+1536+```go1537+package main1538+1539+import (1540+ "log"1541+ "net/http"1542+1543+ "github.com/gin-gonic/autotls"1544+ "github.com/gin-gonic/gin"1545+)1546+1547+func main() {1548+ r := gin.Default()1549+1550+ // Ping handler1551+ r.GET("/ping", func(c *gin.Context) {1552+ c.String(http.StatusOK, "pong")1553+ })1554+1555+ log.Fatal(autotls.Run(r, "example1.com", "example2.com"))1556+}1557+```1558+1559+example for custom autocert manager.1560+1561+```go1562+package main1563+1564+import (1565+ "log"1566+ "net/http"1567+1568+ "github.com/gin-gonic/autotls"1569+ "github.com/gin-gonic/gin"1570+ "golang.org/x/crypto/acme/autocert"1571+)1572+1573+func main() {1574+ r := gin.Default()1575+1576+ // Ping handler1577+ r.GET("/ping", func(c *gin.Context) {1578+ c.String(http.StatusOK, "pong")1579+ })1580+1581+ m := autocert.Manager{1582+ Prompt: autocert.AcceptTOS,1583+ HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),1584+ Cache: autocert.DirCache("/var/www/.cache"),1585+ }1586+1587+ log.Fatal(autotls.RunWithManager(r, &m))1588+}1589+```1590+1591+### Run multiple service using Gin1592+1593+See the [question](https://github.com/gin-gonic/gin/issues/346) and try the following example:1594+1595+```go1596+package main1597+1598+import (1599+ "log"1600+ "net/http"1601+ "time"1602+1603+ "github.com/gin-gonic/gin"1604+ "golang.org/x/sync/errgroup"1605+)1606+1607+var (1608+ g errgroup.Group1609+)1610+1611+func router01() http.Handler {1612+ e := gin.New()1613+ e.Use(gin.Recovery())1614+ e.GET("/", func(c *gin.Context) {1615+ c.JSON(1616+ http.StatusOK,1617+ gin.H{1618+ "code": http.StatusOK,1619+ "error": "Welcome server 01",1620+ },1621+ )1622+ })1623+1624+ return e1625+}1626+1627+func router02() http.Handler {1628+ e := gin.New()1629+ e.Use(gin.Recovery())1630+ e.GET("/", func(c *gin.Context) {1631+ c.JSON(1632+ http.StatusOK,1633+ gin.H{1634+ "code": http.StatusOK,1635+ "error": "Welcome server 02",1636+ },1637+ )1638+ })1639+1640+ return e1641+}1642+1643+func main() {1644+ server01 := &http.Server{1645+ Addr: ":8080",1646+ Handler: router01(),1647+ ReadTimeout: 5 * time.Second,1648+ WriteTimeout: 10 * time.Second,1649+ }1650+1651+ server02 := &http.Server{1652+ Addr: ":8081",1653+ Handler: router02(),1654+ ReadTimeout: 5 * time.Second,1655+ WriteTimeout: 10 * time.Second,1656+ }1657+1658+ g.Go(func() error {1659+ err := server01.ListenAndServe()1660+ if err != nil && err != http.ErrServerClosed {1661+ log.Fatal(err)1662+ }1663+ return err1664+ })1665+1666+ g.Go(func() error {1667+ err := server02.ListenAndServe()1668+ if err != nil && err != http.ErrServerClosed {1669+ log.Fatal(err)1670+ }1671+ return err1672+ })1673+1674+ if err := g.Wait(); err != nil {1675+ log.Fatal(err)1676+ }1677+}1678+```1679+1680+### Graceful shutdown or restart1681+1682+There are a few approaches you can use to perform a graceful shutdown or restart. You can make use of third-party packages specifically built for that, or you can manually do the same with the functions and methods from the built-in packages.1683+1684+#### Third-party packages1685+1686+We can use [fvbock/endless](https://github.com/fvbock/endless) to replace the default `ListenAndServe`. Refer to issue [#296](https://github.com/gin-gonic/gin/issues/296) for more details.1687+1688+```go1689+router := gin.Default()1690+router.GET("/", handler)1691+// [...]1692+endless.ListenAndServe(":4242", router)1693+```1694+1695+Alternatives:1696+1697+* [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers.1698+* [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server.1699+* [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully.1700+1701+#### Manually1702+1703+In case you are using Go 1.8 or a later version, you may not need to use those libraries. Consider using `http.Server`'s built-in [Shutdown()](https://pkg.go.dev/net/http#Server.Shutdown) method for graceful shutdowns. The example below describes its usage, and we've got more examples using gin [here](https://github.com/gin-gonic/examples/tree/master/graceful-shutdown).1704+1705+```go1706+// +build go1.81707+1708+package main1709+1710+import (1711+ "context"1712+ "log"1713+ "net/http"1714+ "os"1715+ "os/signal"1716+ "syscall"1717+ "time"1718+1719+ "github.com/gin-gonic/gin"1720+)1721+1722+func main() {1723+ router := gin.Default()1724+ router.GET("/", func(c *gin.Context) {1725+ time.Sleep(5 * time.Second)1726+ c.String(http.StatusOK, "Welcome Gin Server")1727+ })1728+1729+ srv := &http.Server{1730+ Addr: ":8080",1731+ Handler: router,1732+ }1733+1734+ // Initializing the server in a goroutine so that1735+ // it won't block the graceful shutdown handling below1736+ go func() {1737+ if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {1738+ log.Printf("listen: %s\n", err)1739+ }1740+ }()1741+1742+ // Wait for interrupt signal to gracefully shutdown the server with1743+ // a timeout of 5 seconds.1744+ quit := make(chan os.Signal)1745+ // kill (no param) default send syscall.SIGTERM1746+ // kill -2 is syscall.SIGINT1747+ // kill -9 is syscall.SIGKILL but can't be caught, so don't need to add it1748+ signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)1749+ <-quit1750+ log.Println("Shutting down server...")1751+1752+ // The context is used to inform the server it has 5 seconds to finish1753+ // the request it is currently handling1754+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)1755+ defer cancel()1756+1757+ if err := srv.Shutdown(ctx); err != nil {1758+ log.Fatal("Server forced to shutdown:", err)1759+ }1760+1761+ log.Println("Server exiting")1762+}1763+```1764+1765+### Build a single binary with templates1766+1767+You can build a server into a single binary containing templates by using the [embed](https://pkg.go.dev/embed) package.1768+1769+```go1770+package main1771+1772+import (1773+ "embed"1774+ "html/template"1775+ "net/http"1776+1777+ "github.com/gin-gonic/gin"1778+)1779+1780+//go:embed assets/* templates/*1781+var f embed.FS1782+1783+func main() {1784+ router := gin.Default()1785+ templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl"))1786+ router.SetHTMLTemplate(templ)1787+1788+ // example: /public/assets/images/example.png1789+ router.StaticFS("/public", http.FS(f))1790+1791+ router.GET("/", func(c *gin.Context) {1792+ c.HTML(http.StatusOK, "index.tmpl", gin.H{1793+ "title": "Main website",1794+ })1795+ })1796+1797+ router.GET("/foo", func(c *gin.Context) {1798+ c.HTML(http.StatusOK, "bar.tmpl", gin.H{1799+ "title": "Foo website",1800+ })1801+ })1802+1803+ router.GET("favicon.ico", func(c *gin.Context) {1804+ file, _ := f.ReadFile("assets/favicon.ico")1805+ c.Data(1806+ http.StatusOK,1807+ "image/x-icon",1808+ file,1809+ )1810+ })1811+1812+ router.Run(":8080")1813+}1814+```1815+1816+See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary/example02` directory.1817+1818+### Bind form-data request with custom struct1819+1820+The follow example using custom struct:1821+1822+```go1823+type StructA struct {1824+ FieldA string `form:"field_a"`1825+}1826+1827+type StructB struct {1828+ NestedStruct StructA1829+ FieldB string `form:"field_b"`1830+}1831+1832+type StructC struct {1833+ NestedStructPointer *StructA1834+ FieldC string `form:"field_c"`1835+}1836+1837+type StructD struct {1838+ NestedAnonyStruct struct {1839+ FieldX string `form:"field_x"`1840+ }1841+ FieldD string `form:"field_d"`1842+}1843+1844+func GetDataB(c *gin.Context) {1845+ var b StructB1846+ c.Bind(&b)1847+ c.JSON(http.StatusOK, gin.H{1848+ "a": b.NestedStruct,1849+ "b": b.FieldB,1850+ })1851+}1852+1853+func GetDataC(c *gin.Context) {1854+ var b StructC1855+ c.Bind(&b)1856+ c.JSON(http.StatusOK, gin.H{1857+ "a": b.NestedStructPointer,1858+ "c": b.FieldC,1859+ })1860+}1861+1862+func GetDataD(c *gin.Context) {1863+ var b StructD1864+ c.Bind(&b)1865+ c.JSON(http.StatusOK, gin.H{1866+ "x": b.NestedAnonyStruct,1867+ "d": b.FieldD,1868+ })1869+}1870+1871+func main() {1872+ r := gin.Default()1873+ r.GET("/getb", GetDataB)1874+ r.GET("/getc", GetDataC)1875+ r.GET("/getd", GetDataD)1876+1877+ r.Run()1878+}1879+```1880+1881+Using the command `curl` command result:1882+1883+```sh1884+$ curl "http://localhost:8080/getb?field_a=hello&field_b=world"1885+{"a":{"FieldA":"hello"},"b":"world"}1886+$ curl "http://localhost:8080/getc?field_a=hello&field_c=world"1887+{"a":{"FieldA":"hello"},"c":"world"}1888+$ curl "http://localhost:8080/getd?field_x=hello&field_d=world"1889+{"d":"world","x":{"FieldX":"hello"}}1890+```1891+1892+### Try to bind body into different structs1893+1894+The normal methods for binding request body consumes `c.Request.Body` and they1895+cannot be called multiple times.1896+1897+```go1898+type formA struct {1899+ Foo string `json:"foo" xml:"foo" binding:"required"`1900+}1901+1902+type formB struct {1903+ Bar string `json:"bar" xml:"bar" binding:"required"`1904+}1905+1906+func SomeHandler(c *gin.Context) {1907+ objA := formA{}1908+ objB := formB{}1909+ // This c.ShouldBind consumes c.Request.Body and it cannot be reused.1910+ if errA := c.ShouldBind(&objA); errA == nil {1911+ c.String(http.StatusOK, `the body should be formA`)1912+ // Always an error is occurred by this because c.Request.Body is EOF now.1913+ } else if errB := c.ShouldBind(&objB); errB == nil {1914+ c.String(http.StatusOK, `the body should be formB`)1915+ } else {1916+ ...1917+ }1918+}1919+```1920+1921+For this, you can use `c.ShouldBindBodyWith`.1922+1923+```go1924+func SomeHandler(c *gin.Context) {1925+ objA := formA{}1926+ objB := formB{}1927+ // This reads c.Request.Body and stores the result into the context.1928+ if errA := c.ShouldBindBodyWith(&objA, binding.Form); errA == nil {1929+ c.String(http.StatusOK, `the body should be formA`)1930+ // At this time, it reuses body stored in the context.1931+ } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {1932+ c.String(http.StatusOK, `the body should be formB JSON`)1933+ // And it can accepts other formats1934+ } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {1935+ c.String(http.StatusOK, `the body should be formB XML`)1936+ } else {1937+ ...1938+ }1939+}1940+```1941+1942+1. `c.ShouldBindBodyWith` stores body into the context before binding. This has1943+a slight impact to performance, so you should not use this method if you are1944+enough to call binding at once.1945+2. This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`,1946+`ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`,1947+can be called by `c.ShouldBind()` multiple times without any damage to1948+performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)).1949+1950+### Bind form-data request with custom struct and custom tag1951+1952+```go1953+const (1954+ customerTag = "url"1955+ defaultMemory = 32 << 201956+)1957+1958+type customerBinding struct {}1959+1960+func (customerBinding) Name() string {1961+ return "form"1962+}1963+1964+func (customerBinding) Bind(req *http.Request, obj interface{}) error {1965+ if err := req.ParseForm(); err != nil {1966+ return err1967+ }1968+ if err := req.ParseMultipartForm(defaultMemory); err != nil {1969+ if err != http.ErrNotMultipart {1970+ return err1971+ }1972+ }1973+ if err := binding.MapFormWithTag(obj, req.Form, customerTag); err != nil {1974+ return err1975+ }1976+ return validate(obj)1977+}1978+1979+func validate(obj interface{}) error {1980+ if binding.Validator == nil {1981+ return nil1982+ }1983+ return binding.Validator.ValidateStruct(obj)1984+}1985+1986+// Now we can do this!!!1987+// FormA is an external type that we can't modify it's tag1988+type FormA struct {1989+ FieldA string `url:"field_a"`1990+}1991+1992+func ListHandler(s *Service) func(ctx *gin.Context) {1993+ return func(ctx *gin.Context) {1994+ var urlBinding = customerBinding{}1995+ var opt FormA1996+ err := ctx.MustBindWith(&opt, urlBinding)1997+ if err != nil {1998+ ...1999+ }2000+ ...2001+ }2002+}2003+```2004+2005+### http2 server push2006+2007+http.Pusher is supported only **go1.8+**. See the [golang blog](https://go.dev/blog/h2push) for detail information.2008+2009+```go2010+package main2011+2012+import (2013+ "html/template"2014+ "log"2015+ "net/http"2016+2017+ "github.com/gin-gonic/gin"2018+)2019+2020+var html = template.Must(template.New("https").Parse(`2021+<html>2022+<head>2023+ <title>Https Test</title>2024+ <script src="/assets/app.js"></script>2025+</head>2026+<body>2027+ <h1 style="color:red;">Welcome, Ginner!</h1>2028+</body>2029+</html>2030+`))2031+2032+func main() {2033+ r := gin.Default()2034+ r.Static("/assets", "./assets")2035+ r.SetHTMLTemplate(html)2036+2037+ r.GET("/", func(c *gin.Context) {2038+ if pusher := c.Writer.Pusher(); pusher != nil {2039+ // use pusher.Push() to do server push2040+ if err := pusher.Push("/assets/app.js", nil); err != nil {2041+ log.Printf("Failed to push: %v", err)2042+ }2043+ }2044+ c.HTML(http.StatusOK, "https", gin.H{2045+ "status": "success",2046+ })2047+ })2048+2049+ // Listen and Server in https://127.0.0.1:80802050+ r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")2051+}2052+```2053+2054+### Define format for the log of routes2055+2056+The default log of routes is:2057+2058+```sh2059+[GIN-debug] POST /foo --> main.main.func1 (3 handlers)2060+[GIN-debug] GET /bar --> main.main.func2 (3 handlers)2061+[GIN-debug] GET /status --> main.main.func3 (3 handlers)2062+```2063+2064+If 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`.2065+In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs.2066+2067+```go2068+import (2069+ "log"2070+ "net/http"2071+2072+ "github.com/gin-gonic/gin"2073+)2074+2075+func main() {2076+ r := gin.Default()2077+ gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {2078+ log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers)2079+ }2080+2081+ r.POST("/foo", func(c *gin.Context) {2082+ c.JSON(http.StatusOK, "foo")2083+ })2084+2085+ r.GET("/bar", func(c *gin.Context) {2086+ c.JSON(http.StatusOK, "bar")2087+ })2088+2089+ r.GET("/status", func(c *gin.Context) {2090+ c.JSON(http.StatusOK, "ok")2091+ })2092+2093+ // Listen and Server in http://0.0.0.0:80802094+ r.Run()2095+}2096+```2097+2098+### Set and get a cookie2099+2100+```go2101+import (2102+ "fmt"2103+2104+ "github.com/gin-gonic/gin"2105+)2106+2107+func main() {2108+2109+ router := gin.Default()2110+2111+ router.GET("/cookie", func(c *gin.Context) {2112+2113+ cookie, err := c.Cookie("gin_cookie")2114+2115+ if err != nil {2116+ cookie = "NotSet"2117+ c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)2118+ }2119+2120+ fmt.Printf("Cookie value: %s \n", cookie)2121+ })2122+2123+ router.Run()2124+}2125+```2126+2127+## Don't trust all proxies2128+2129+Gin lets you specify which headers to hold the real client IP (if any),2130+as well as specifying which proxies (or direct clients) you trust to2131+specify one of these headers.2132+2133+Use function `SetTrustedProxies()` on your `gin.Engine` to specify network addresses2134+or network CIDRs from where clients which their request headers related to client2135+IP can be trusted. They can be IPv4 addresses, IPv4 CIDRs, IPv6 addresses or2136+IPv6 CIDRs.2137+2138+**Attention:** Gin trust all proxies by default if you don't specify a trusted 2139+proxy using the function above, **this is NOT safe**. At the same time, if you don't2140+use any proxy, you can disable this feature by using `Engine.SetTrustedProxies(nil)`,2141+then `Context.ClientIP()` will return the remote address directly to avoid some2142+unnecessary computation.2143+2144+```go2145+import (2146+ "fmt"2147+2148+ "github.com/gin-gonic/gin"2149+)2150+2151+func main() {2152+2153+ router := gin.Default()2154+ router.SetTrustedProxies([]string{"192.168.1.2"})2155+2156+ router.GET("/", func(c *gin.Context) {2157+ // If the client is 192.168.1.2, use the X-Forwarded-For2158+ // header to deduce the original client IP from the trust-2159+ // worthy parts of that header.2160+ // Otherwise, simply return the direct client IP2161+ fmt.Printf("ClientIP: %s\n", c.ClientIP())2162+ })2163+ router.Run()2164+}2165+```2166+2167+**Notice:** If you are using a CDN service, you can set the `Engine.TrustedPlatform`2168+to skip TrustedProxies check, it has a higher priority than TrustedProxies. 2169+Look at the example below:2170+2171+```go2172+import (2173+ "fmt"2174+2175+ "github.com/gin-gonic/gin"2176+)2177+2178+func main() {2179+2180+ router := gin.Default()2181+ // Use predefined header gin.PlatformXXX2182+ router.TrustedPlatform = gin.PlatformGoogleAppEngine2183+ // Or set your own trusted request header for another trusted proxy service2184+ // Don't set it to any suspect request header, it's unsafe2185+ router.TrustedPlatform = "X-CDN-IP"2186+2187+ router.GET("/", func(c *gin.Context) {2188+ // If you set TrustedPlatform, ClientIP() will resolve the2189+ // corresponding header and return IP directly2190+ fmt.Printf("ClientIP: %s\n", c.ClientIP())2191+ })2192+ router.Run()2193+}2194+```2195+2196+## Testing2197+2198+The `net/http/httptest` package is preferable way for HTTP testing.2199+2200+```go2201+package main2202+2203+import (2204+ "net/http"2205+2206+ "github.com/gin-gonic/gin"2207+)2208+2209+func setupRouter() *gin.Engine {2210+ r := gin.Default()2211+ r.GET("/ping", func(c *gin.Context) {2212+ c.String(http.StatusOK, "pong")2213+ })2214+ return r2215+}2216+2217+func main() {2218+ r := setupRouter()2219+ r.Run(":8080")2220+}2221+```2222+2223+Test for code example above:2224+2225+```go2226+package main2227+2228+import (2229+ "net/http"2230+ "net/http/httptest"2231+ "testing"2232+2233+ "github.com/stretchr/testify/assert"2234+)2235+2236+func TestPingRoute(t *testing.T) {2237+ router := setupRouter()2238+2239+ w := httptest.NewRecorder()2240+ req, _ := http.NewRequest(http.MethodGet, "/ping", nil)2241+ router.ServeHTTP(w, req)2242+2243+ assert.Equal(t, http.StatusOK, w.Code)2244+ assert.Equal(t, "pong", w.Body.String())2245+}2246+```modified:README.md+70 added-2272 removed
10 unmodified lines11 [](https://www.codetriage.com/gin-gonic/gin)12 [](https://github.com/gin-gonic/gin/releases)13 [](https://www.tickgit.com/browse?repo=github.com/gin-gonic/gin)14 15-Gin is a web framework written in Go (Golang). It features a martini-like API with performance that is up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin.15+Gin is a web framework written in [Go](https://go.dev/). It features a martini-like API with performance that is up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin.16 17-## Contents17+**The key features of Gin are:**18 19-- [Gin Web Framework](#gin-web-framework)20- - [Contents](#contents)21- - [Installation](#installation)22- - [Quick start](#quick-start)23- - [Benchmarks](#benchmarks)24- - [Gin v1. stable](#gin-v1-stable)25- - [Build with json replacement](#build-with-json-replacement)26- - [Build without `MsgPack` rendering feature](#build-without-msgpack-rendering-feature)27- - [API Examples](#api-examples)28- - [Using GET, POST, PUT, PATCH, DELETE and OPTIONS](#using-get-post-put-patch-delete-and-options)29- - [Parameters in path](#parameters-in-path)30- - [Querystring parameters](#querystring-parameters)31- - [Multipart/Urlencoded Form](#multiparturlencoded-form)32- - [Another example: query + post form](#another-example-query--post-form)33- - [Map as querystring or postform parameters](#map-as-querystring-or-postform-parameters)34- - [Upload files](#upload-files)35- - [Single file](#single-file)36- - [Multiple files](#multiple-files)37- - [Grouping routes](#grouping-routes)38- - [Blank Gin without middleware by default](#blank-gin-without-middleware-by-default)39- - [Using middleware](#using-middleware)40- - [Custom Recovery behavior](#custom-recovery-behavior)41- - [How to write log file](#how-to-write-log-file)42- - [Custom Log Format](#custom-log-format)43- - [Controlling Log output coloring](#controlling-log-output-coloring)44- - [Model binding and validation](#model-binding-and-validation)45- - [Custom Validators](#custom-validators)46- - [Only Bind Query String](#only-bind-query-string)47- - [Bind Query String or Post Data](#bind-query-string-or-post-data)48- - [Bind Uri](#bind-uri)49- - [Bind Header](#bind-header)50- - [Bind HTML checkboxes](#bind-html-checkboxes)51- - [Multipart/Urlencoded binding](#multiparturlencoded-binding)52- - [XML, JSON, YAML, TOML and ProtoBuf rendering](#xml-json-yaml-toml-and-protobuf-rendering)53- - [SecureJSON](#securejson)54- - [JSONP](#jsonp)55- - [AsciiJSON](#asciijson)56- - [PureJSON](#purejson)57- - [Serving static files](#serving-static-files)58- - [Serving data from file](#serving-data-from-file)59- - [Serving data from reader](#serving-data-from-reader)60- - [HTML rendering](#html-rendering)61- - [Custom Template renderer](#custom-template-renderer)62- - [Custom Delimiters](#custom-delimiters)63- - [Custom Template Funcs](#custom-template-funcs)64- - [Multitemplate](#multitemplate)65- - [Redirects](#redirects)66- - [Custom Middleware](#custom-middleware)67- - [Using BasicAuth() middleware](#using-basicauth-middleware)68- - [Goroutines inside a middleware](#goroutines-inside-a-middleware)69- - [Custom HTTP configuration](#custom-http-configuration)70- - [Support Let's Encrypt](#support-lets-encrypt)71- - [Run multiple service using Gin](#run-multiple-service-using-gin)72- - [Graceful shutdown or restart](#graceful-shutdown-or-restart)73- - [Third-party packages](#third-party-packages)74- - [Manually](#manually)75- - [Build a single binary with templates](#build-a-single-binary-with-templates)76- - [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct)77- - [Try to bind body into different structs](#try-to-bind-body-into-different-structs)78- - [Bind form-data request with custom struct and custom tag](#bind-form-data-request-with-custom-struct-and-custom-tag)79- - [http2 server push](#http2-server-push)80- - [Define format for the log of routes](#define-format-for-the-log-of-routes)81- - [Set and get a cookie](#set-and-get-a-cookie)82- - [Don't trust all proxies](#dont-trust-all-proxies)83- - [Testing](#testing)84- - [Users](#users)19+- Zero allocation router20+- Fast21+- Middleware support22+- Crash-free23+- JSON validation24+- Routes grouping25+- Error management26+- Rendering built-in27+- Extendable28 86-## Installation29 88-To install Gin package, you need to install Go and set your Go workspace first.30+## Getting started31 90-1. You first need [Go](https://go.dev/) installed (**version 1.16+ is required**), then you can use the below Go command to install Gin.32+### Prerequisites33 92-```sh93-go get -u github.com/gin-gonic/gin94-```34+- **[Go](https://go.dev/)**: ~~any one of the **three latest major** [releases](https://go.dev/doc/devel/release)~~ (now version **1.16+** is required).35 96-2. Import it in your code:36+### Getting Gin37 38+With [Go module](https://github.com/golang/go/wiki/Modules) support, simply add the following import39+98-```go40+```41 import "github.com/gin-gonic/gin"42 ```43 102-3. (Optional) Import `net/http`. This is required for example if using constants such as `http.StatusOK`.44+to your code, and then `go [build|run|test]` will automatically fetch the necessary dependencies.45 104-```go105-import "net/http"106-```46+Otherwise, run the following Go command to install the `gin` package:47 108-## Quick start109-48 ```sh111-# assume the following codes in example.go file112-$ cat example.go49+$ go get -u github.com/gin-gonic/gin50 ```51 52+### Running Gin53+54+First you need to import Gin package for using Gin, one simplest example likes the follow `example.go`:55+56 ```go57 package main58 59 import (12 unmodified lines72 r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")73 }74 ```75 76+And use the Go command to run the demo:77+78 ```136-# run example.go and visit 0.0.0.0:8080/ping (for windows "localhost:8080/ping") on browser79+# run example.go and visit 0.0.0.0:8080/ping on browser80 $ go run example.go81 ```82 140-## Benchmarks83+### Learn more examples84 142-Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter)85+#### Quick Start86 144-[See all benchmarks](/BENCHMARKS.md)87+Learn and practice more examples, please read the [Gin Quick Start](docs/doc.md) which includes API examples and builds tag.88 89+#### Examples90+91+A number of ready-to-run examples demonstrating various use cases of Gin on the [Gin examples](https://github.com/gin-gonic/examples) repository.92+93+94+## Documentation95+96+See [API documentation and descriptions](https://godoc.org/github.com/gin-gonic/gin) for package.97+98+All documentation is available on the Gin website.99+100+- [English](https://gin-gonic.com/docs/)101+- [简体中文](https://gin-gonic.com/zh-cn/docs/)102+- [繁體中文](https://gin-gonic.com/zh-tw/docs/)103+- [日本語](https://gin-gonic.com/ja/docs/)104+- [Español](https://gin-gonic.com/es/docs/)105+- [한국어](https://gin-gonic.com/ko-kr/docs/)106+- [Turkish](https://gin-gonic.com/tr/docs/)107+- [Persian](https://gin-gonic.com/fa/docs/)108+109+### Articles about Gin110+111+A curated list of awesome Gin framework.112+113+- [Tutorial: Developing a RESTful API with Go and Gin](https://go.dev/doc/tutorial/web-service-gin)114+115+## Benchmarks116+117+Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter), [see all benchmarks details](/BENCHMARKS.md).118+119 | Benchmark name | (1) | (2) | (3) | (4) |120 | ------------------------------ | ---------:| ---------------:| ------------:| ---------------:|121 | BenchmarkGin_GithubAll | **43550** | **27364 ns/op** | **0 B/op** | **0 allocs/op** |122 | BenchmarkAce_GithubAll | 40543 | 29670 ns/op | 0 B/op | 0 allocs/op |30 unmodified lines153 - (2): Single Repetition Duration (ns/op), lower is better154 - (3): Heap Memory (B/op), lower is better155 - (4): Average Allocations per Repetition (allocs/op), lower is better156 184-## Gin v1. stable157 186-- [x] Zero allocation router.187-- [x] Still the fastest http router and framework. From routing to writing.188-- [x] Complete suite of unit tests.189-- [x] Battle tested.190-- [x] API frozen, new releases will not break your code.158+## Middlewares159 192-## Build with json replacement160+You can find many useful Gin middlewares at [gin-contrib](https://github.com/gin-contrib).161 194-Gin uses `encoding/json` as default json package but you can change it by build from other tags.162 196-[jsoniter](https://github.com/json-iterator/go)197-198-```sh199-go build -tags=jsoniter .200-```201-202-[go-json](https://github.com/goccy/go-json)203-204-```sh205-go build -tags=go_json .206-```207-208-[sonic](https://github.com/bytedance/sonic) (you have to ensure that your cpu support avx instruction.)209-210-```sh211-$ go build -tags="sonic avx" .212-```213-214-## Build without `MsgPack` rendering feature215-216-Gin enables `MsgPack` rendering feature by default. But you can disable this feature by specifying `nomsgpack` build tag.217-218-```sh219-go build -tags=nomsgpack .220-```221-222-This is useful to reduce the binary size of executable files. See the [detail information](https://github.com/gin-gonic/gin/pull/1852).223-224-## API Examples225-226-You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples).227-228-### Using GET, POST, PUT, PATCH, DELETE and OPTIONS229-230-```go231-func main() {232- // Creates a gin router with default middleware:233- // logger and recovery (crash-free) middleware234- router := gin.Default()235-236- router.GET("/someGet", getting)237- router.POST("/somePost", posting)238- router.PUT("/somePut", putting)239- router.DELETE("/someDelete", deleting)240- router.PATCH("/somePatch", patching)241- router.HEAD("/someHead", head)242- router.OPTIONS("/someOptions", options)243-244- // By default it serves on :8080 unless a245- // PORT environment variable was defined.246- router.Run()247- // router.Run(":3000") for a hard coded port248-}249-```250-251-### Parameters in path252-253-```go254-func main() {255- router := gin.Default()256-257- // This handler will match /user/john but will not match /user/ or /user258- router.GET("/user/:name", func(c *gin.Context) {259- name := c.Param("name")260- c.String(http.StatusOK, "Hello %s", name)261- })262-263- // However, this one will match /user/john/ and also /user/john/send264- // If no other routers match /user/john, it will redirect to /user/john/265- router.GET("/user/:name/*action", func(c *gin.Context) {266- name := c.Param("name")267- action := c.Param("action")268- message := name + " is " + action269- c.String(http.StatusOK, message)270- })271-272- // For each matched request Context will hold the route definition273- router.POST("/user/:name/*action", func(c *gin.Context) {274- b := c.FullPath() == "/user/:name/*action" // true275- c.String(http.StatusOK, "%t", b)276- })277-278- // This handler will add a new router for /user/groups.279- // Exact routes are resolved before param routes, regardless of the order they were defined.280- // Routes starting with /user/groups are never interpreted as /user/:name/... routes281- router.GET("/user/groups", func(c *gin.Context) {282- c.String(http.StatusOK, "The available groups are [...]")283- })284-285- router.Run(":8080")286-}287-```288-289-### Querystring parameters290-291-```go292-func main() {293- router := gin.Default()294-295- // Query string parameters are parsed using the existing underlying request object.296- // The request responds to an url matching: /welcome?firstname=Jane&lastname=Doe297- router.GET("/welcome", func(c *gin.Context) {298- firstname := c.DefaultQuery("firstname", "Guest")299- lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")300-301- c.String(http.StatusOK, "Hello %s %s", firstname, lastname)302- })303- router.Run(":8080")304-}305-```306-307-### Multipart/Urlencoded Form308-309-```go310-func main() {311- router := gin.Default()312-313- router.POST("/form_post", func(c *gin.Context) {314- message := c.PostForm("message")315- nick := c.DefaultPostForm("nick", "anonymous")316-317- c.JSON(http.StatusOK, gin.H{318- "status": "posted",319- "message": message,320- "nick": nick,321- })322- })323- router.Run(":8080")324-}325-```326-327-### Another example: query + post form328-329-```sh330-POST /post?id=1234&page=1 HTTP/1.1331-Content-Type: application/x-www-form-urlencoded332-333-name=manu&message=this_is_great334-```335-336-```go337-func main() {338- router := gin.Default()339-340- router.POST("/post", func(c *gin.Context) {341-342- id := c.Query("id")343- page := c.DefaultQuery("page", "0")344- name := c.PostForm("name")345- message := c.PostForm("message")346-347- fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)348- })349- router.Run(":8080")350-}351-```352-353-```sh354-id: 1234; page: 1; name: manu; message: this_is_great355-```356-357-### Map as querystring or postform parameters358-359-```sh360-POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1361-Content-Type: application/x-www-form-urlencoded362-363-names[first]=thinkerou&names[second]=tianou364-```365-366-```go367-func main() {368- router := gin.Default()369-370- router.POST("/post", func(c *gin.Context) {371-372- ids := c.QueryMap("ids")373- names := c.PostFormMap("names")374-375- fmt.Printf("ids: %v; names: %v", ids, names)376- })377- router.Run(":8080")378-}379-```380-381-```sh382-ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou]383-```384-385-### Upload files386-387-#### Single file388-389-References 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).390-391-`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)392-393-> 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.394-395-```go396-func main() {397- router := gin.Default()398- // Set a lower memory limit for multipart forms (default is 32 MiB)399- router.MaxMultipartMemory = 8 << 20 // 8 MiB400- router.POST("/upload", func(c *gin.Context) {401- // Single file402- file, _ := c.FormFile("file")403- log.Println(file.Filename)404-405- // Upload the file to specific dst.406- c.SaveUploadedFile(file, dst)407-408- c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))409- })410- router.Run(":8080")411-}412-```413-414-How to `curl`:415-416-```bash417-curl -X POST http://localhost:8080/upload \418- -F "file=@/Users/appleboy/test.zip" \419- -H "Content-Type: multipart/form-data"420-```421-422-#### Multiple files423-424-See the detail [example code](https://github.com/gin-gonic/examples/tree/master/upload-file/multiple).425-426-```go427-func main() {428- router := gin.Default()429- // Set a lower memory limit for multipart forms (default is 32 MiB)430- router.MaxMultipartMemory = 8 << 20 // 8 MiB431- router.POST("/upload", func(c *gin.Context) {432- // Multipart form433- form, _ := c.MultipartForm()434- files := form.File["upload[]"]435-436- for _, file := range files {437- log.Println(file.Filename)438-439- // Upload the file to specific dst.440- c.SaveUploadedFile(file, dst)441- }442- c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))443- })444- router.Run(":8080")445-}446-```447-448-How to `curl`:449-450-```bash451-curl -X POST http://localhost:8080/upload \452- -F "upload[]=@/Users/appleboy/test1.zip" \453- -F "upload[]=@/Users/appleboy/test2.zip" \454- -H "Content-Type: multipart/form-data"455-```456-457-### Grouping routes458-459-```go460-func main() {461- router := gin.Default()462-463- // Simple group: v1464- 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: v2472- 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-483-### Blank Gin without middleware by default484-485-Use486-487-```go488-r := gin.New()489-```490-491-instead of492-493-```go494-// Default With the Logger and Recovery middleware already attached495-r := gin.Default()496-```497-498-### Using middleware499-500-```go501-func main() {502- // Creates a router without any middleware by default503- r := gin.New()504-505- // Global middleware506- // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.507- // By default gin.DefaultWriter = os.Stdout508- r.Use(gin.Logger())509-510- // Recovery middleware recovers from any panics and writes a 500 if there was one.511- r.Use(gin.Recovery())512-513- // Per route middleware, you can add as many as you desire.514- r.GET("/benchmark", MyBenchLogger(), benchEndpoint)515-516- // Authorization group517- // authorized := r.Group("/", AuthRequired())518- // exactly the same as:519- authorized := r.Group("/")520- // per group middleware! in this case we use the custom created521- // AuthRequired() middleware just in the "authorized" group.522- authorized.Use(AuthRequired())523- {524- authorized.POST("/login", loginEndpoint)525- authorized.POST("/submit", submitEndpoint)526- authorized.POST("/read", readEndpoint)527-528- // nested group529- testing := authorized.Group("testing")530- // visit 0.0.0.0:8080/testing/analytics531- testing.GET("/analytics", analyticsEndpoint)532- }533-534- // Listen and serve on 0.0.0.0:8080535- r.Run(":8080")536-}537-```538-539-### Custom Recovery behavior540-541-```go542-func main() {543- // Creates a router without any middleware by default544- r := gin.New()545-546- // Global middleware547- // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.548- // By default gin.DefaultWriter = os.Stdout549- r.Use(gin.Logger())550-551- // Recovery middleware recovers from any panics and writes a 500 if there was one.552- r.Use(gin.CustomRecovery(func(c *gin.Context, recovered interface{}) {553- if err, ok := recovered.(string); ok {554- c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))555- }556- c.AbortWithStatus(http.StatusInternalServerError)557- }))558-559- r.GET("/panic", func(c *gin.Context) {560- // panic with a string -- the custom middleware could save this to a database or report it to the user561- panic("foo")562- })563-564- r.GET("/", func(c *gin.Context) {565- c.String(http.StatusOK, "ohai")566- })567-568- // Listen and serve on 0.0.0.0:8080569- r.Run(":8080")570-}571-```572-573-### How to write log file574-575-```go576-func main() {577- // Disable Console Color, you don't need console color when writing the logs to file.578- gin.DisableConsoleColor()579-580- // Logging to a file.581- f, _ := os.Create("gin.log")582- gin.DefaultWriter = io.MultiWriter(f)583-584- // Use the following code if you need to write the logs to file and console at the same time.585- // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)586-587- router := gin.Default()588- router.GET("/ping", func(c *gin.Context) {589- c.String(http.StatusOK, "pong")590- })591-592- router.Run(":8080")593-}594-```595-596-### Custom Log Format597-598-```go599-func main() {600- router := gin.New()601-602- // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter603- // By default gin.DefaultWriter = os.Stdout604- router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {605-606- // your custom format607- return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",608- param.ClientIP,609- param.TimeStamp.Format(time.RFC1123),610- param.Method,611- param.Path,612- param.Request.Proto,613- param.StatusCode,614- param.Latency,615- param.Request.UserAgent(),616- param.ErrorMessage,617- )618- }))619- router.Use(gin.Recovery())620-621- router.GET("/ping", func(c *gin.Context) {622- c.String(http.StatusOK, "pong")623- })624-625- router.Run(":8080")626-}627-```628-629-Sample Output630-631-```sh632-::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" "633-```634-635-### Controlling Log output coloring636-637-By default, logs output on console should be colorized depending on the detected TTY.638-639-Never colorize logs:640-641-```go642-func main() {643- // Disable log's color644- gin.DisableConsoleColor()645-646- // Creates a gin router with default middleware:647- // logger and recovery (crash-free) middleware648- router := gin.Default()649-650- router.GET("/ping", func(c *gin.Context) {651- c.String(http.StatusOK, "pong")652- })653-654- router.Run(":8080")655-}656-```657-658-Always colorize logs:659-660-```go661-func main() {662- // Force log's color663- gin.ForceConsoleColor()664-665- // Creates a gin router with default middleware:666- // logger and recovery (crash-free) middleware667- router := gin.Default()668-669- router.GET("/ping", func(c *gin.Context) {670- c.String(http.StatusOK, "pong")671- })672-673- router.Run(":8080")674-}675-```676-677-### Model binding and validation678-679-To bind a request body into a type, use model binding. We currently support binding of JSON, XML, YAML, TOML and standard form values (foo=bar&boo=baz).680-681-Gin uses [**go-playground/validator/v10**](https://github.com/go-playground/validator) for validation. Check the full docs on tags usage [here](https://pkg.go.dev/github.com/go-playground/validator#hdr-Baked_In_Validators_and_Tags).682-683-Note 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"`.684-685-Also, Gin provides two sets of methods for binding:686-687-- **Type** - Must bind688- - **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`, `BindHeader`, `BindTOML`689- - **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.690-- **Type** - Should bind691- - **Methods** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindXML`, `ShouldBindQuery`, `ShouldBindYAML`, `ShouldBindHeader`, `ShouldBindTOML`,692- - **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.693-694-When 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`.695-696-You can also specify that specific fields are required. If a field is decorated with `binding:"required"` and has an empty value when binding, an error will be returned.697-698-```go699-// Binding from JSON700-type Login struct {701- User string `form:"user" json:"user" xml:"user" binding:"required"`702- Password string `form:"password" json:"password" xml:"password" binding:"required"`703-}704-705-func main() {706- router := gin.Default()707-708- // Example for binding JSON ({"user": "manu", "password": "123"})709- router.POST("/loginJSON", func(c *gin.Context) {710- var json Login711- if err := c.ShouldBindJSON(&json); err != nil {712- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})713- return714- }715-716- if json.User != "manu" || json.Password != "123" {717- c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})718- return719- }720-721- c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})722- })723-724- // Example for binding XML (725- // <?xml version="1.0" encoding="UTF-8"?>726- // <root>727- // <user>manu</user>728- // <password>123</password>729- // </root>)730- router.POST("/loginXML", func(c *gin.Context) {731- var xml Login732- if err := c.ShouldBindXML(&xml); err != nil {733- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})734- return735- }736-737- if xml.User != "manu" || xml.Password != "123" {738- c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})739- return740- }741-742- c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})743- })744-745- // Example for binding a HTML form (user=manu&password=123)746- router.POST("/loginForm", func(c *gin.Context) {747- var form Login748- // This will infer what binder to use depending on the content-type header.749- if err := c.ShouldBind(&form); err != nil {750- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})751- return752- }753-754- if form.User != "manu" || form.Password != "123" {755- c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})756- return757- }758-759- c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})760- })761-762- // Listen and serve on 0.0.0.0:8080763- router.Run(":8080")764-}765-```766-767-Sample request768-769-```sh770-$ curl -v -X POST \771- http://localhost:8080/loginJSON \772- -H 'content-type: application/json' \773- -d '{ "user": "manu" }'774-> POST /loginJSON HTTP/1.1775-> Host: localhost:8080776-> User-Agent: curl/7.51.0777-> Accept: */*778-> content-type: application/json779-> Content-Length: 18780->781-* upload completely sent off: 18 out of 18 bytes782-< HTTP/1.1 400 Bad Request783-< Content-Type: application/json; charset=utf-8784-< Date: Fri, 04 Aug 2017 03:51:31 GMT785-< Content-Length: 100786-<787-{"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}788-```789-790-Skip validate: when 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.791-792-### Custom Validators793-794-It is also possible to register custom validators. See the [example code](https://github.com/gin-gonic/examples/tree/master/custom-validation/server.go).795-796-```go797-package main798-799-import (800- "net/http"801- "time"802-803- "github.com/gin-gonic/gin"804- "github.com/gin-gonic/gin/binding"805- "github.com/go-playground/validator/v10"806-)807-808-// Booking contains binded and validated data.809-type Booking struct {810- CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`811- CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`812-}813-814-var bookableDate validator.Func = func(fl validator.FieldLevel) bool {815- date, ok := fl.Field().Interface().(time.Time)816- if ok {817- today := time.Now()818- if today.After(date) {819- return false820- }821- }822- return true823-}824-825-func main() {826- route := gin.Default()827-828- if v, ok := binding.Validator.Engine().(*validator.Validate); ok {829- v.RegisterValidation("bookabledate", bookableDate)830- }831-832- route.GET("/bookable", getBookable)833- route.Run(":8085")834-}835-836-func getBookable(c *gin.Context) {837- var b Booking838- if err := c.ShouldBindWith(&b, binding.Query); err == nil {839- c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})840- } else {841- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})842- }843-}844-```845-846-```console847-$ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17"848-{"message":"Booking dates are valid!"}849-850-$ curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09"851-{"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"}852-853-$ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10"854-{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}%855-```856-857-[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way.858-See the [struct-lvl-validation example](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) to learn more.859-860-### Only Bind Query String861-862-`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).863-864-```go865-package main866-867-import (868- "log"869- "net/http"870-871- "github.com/gin-gonic/gin"872-)873-874-type Person struct {875- Name string `form:"name"`876- Address string `form:"address"`877-}878-879-func main() {880- route := gin.Default()881- route.Any("/testing", startPage)882- route.Run(":8085")883-}884-885-func startPage(c *gin.Context) {886- var person Person887- if c.ShouldBindQuery(&person) == nil {888- log.Println("====== Only Bind By Query String ======")889- log.Println(person.Name)890- log.Println(person.Address)891- }892- c.String(http.StatusOK, "Success")893-}894-895-```896-897-### Bind Query String or Post Data898-899-See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292).900-901-```go902-package main903-904-import (905- "log"906- "net/http"907- "time"908-909- "github.com/gin-gonic/gin"910-)911-912-type Person struct {913- Name string `form:"name"`914- Address string `form:"address"`915- Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`916- CreateTime time.Time `form:"createTime" time_format:"unixNano"`917- UnixTime time.Time `form:"unixTime" time_format:"unix"`918-}919-920-func main() {921- route := gin.Default()922- route.GET("/testing", startPage)923- route.Run(":8085")924-}925-926-func startPage(c *gin.Context) {927- var person Person928- // If `GET`, only `Form` binding engine (`query`) used.929- // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).930- // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L88931- if c.ShouldBind(&person) == nil {932- log.Println(person.Name)933- log.Println(person.Address)934- log.Println(person.Birthday)935- log.Println(person.CreateTime)936- log.Println(person.UnixTime)937- }938-939- c.String(http.StatusOK, "Success")940-}941-```942-943-Test it with:944-945-```sh946-curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"947-```948-949-### Bind Uri950-951-See the [detail information](https://github.com/gin-gonic/gin/issues/846).952-953-```go954-package main955-956-import (957- "net/http"958-959- "github.com/gin-gonic/gin"960-)961-962-type Person struct {963- ID string `uri:"id" binding:"required,uuid"`964- Name string `uri:"name" binding:"required"`965-}966-967-func main() {968- route := gin.Default()969- route.GET("/:name/:id", func(c *gin.Context) {970- var person Person971- if err := c.ShouldBindUri(&person); err != nil {972- c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})973- return974- }975- c.JSON(http.StatusOK, gin.H{"name": person.Name, "uuid": person.ID})976- })977- route.Run(":8088")978-}979-```980-981-Test it with:982-983-```sh984-curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3985-curl -v localhost:8088/thinkerou/not-uuid986-```987-988-### Bind Header989-990-```go991-package main992-993-import (994- "fmt"995- "net/http"996-997- "github.com/gin-gonic/gin"998-)999-1000-type testHeader struct {1001- Rate int `header:"Rate"`1002- Domain string `header:"Domain"`1003-}1004-1005-func main() {1006- r := gin.Default()1007- r.GET("/", func(c *gin.Context) {1008- h := testHeader{}1009-1010- if err := c.ShouldBindHeader(&h); err != nil {1011- c.JSON(http.StatusOK, err)1012- }1013-1014- fmt.Printf("%#v\n", h)1015- c.JSON(http.StatusOK, gin.H{"Rate": h.Rate, "Domain": h.Domain})1016- })1017-1018- r.Run()1019-1020-// client1021-// curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/1022-// output1023-// {"Domain":"music","Rate":300}1024-}1025-```1026-1027-### Bind HTML checkboxes1028-1029-See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)1030-1031-main.go1032-1033-```go1034-...1035-1036-type myForm struct {1037- Colors []string `form:"colors[]"`1038-}1039-1040-...1041-1042-func formHandler(c *gin.Context) {1043- var fakeForm myForm1044- c.ShouldBind(&fakeForm)1045- c.JSON(http.StatusOK, gin.H{"color": fakeForm.Colors})1046-}1047-1048-...1049-1050-```1051-1052-form.html1053-1054-```html1055-<form action="/" method="POST">1056- <p>Check some colors</p>1057- <label for="red">Red</label>1058- <input type="checkbox" name="colors[]" value="red" id="red">1059- <label for="green">Green</label>1060- <input type="checkbox" name="colors[]" value="green" id="green">1061- <label for="blue">Blue</label>1062- <input type="checkbox" name="colors[]" value="blue" id="blue">1063- <input type="submit">1064-</form>1065-```1066-1067-result:1068-1069-```json1070-{"color":["red","green","blue"]}1071-```1072-1073-### Multipart/Urlencoded binding1074-1075-```go1076-type ProfileForm struct {1077- Name string `form:"name" binding:"required"`1078- Avatar *multipart.FileHeader `form:"avatar" binding:"required"`1079-1080- // or for multiple files1081- // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"`1082-}1083-1084-func main() {1085- router := gin.Default()1086- router.POST("/profile", func(c *gin.Context) {1087- // you can bind multipart form with explicit binding declaration:1088- // c.ShouldBindWith(&form, binding.Form)1089- // or you can simply use autobinding with ShouldBind method:1090- var form ProfileForm1091- // in this case proper binding will be automatically selected1092- if err := c.ShouldBind(&form); err != nil {1093- c.String(http.StatusBadRequest, "bad request")1094- return1095- }1096-1097- err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename)1098- if err != nil {1099- c.String(http.StatusInternalServerError, "unknown error")1100- return1101- }1102-1103- // db.Save(&form)1104-1105- c.String(http.StatusOK, "ok")1106- })1107- router.Run(":8080")1108-}1109-```1110-1111-Test it with:1112-1113-```sh1114-curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile1115-```1116-1117-### XML, JSON, YAML, TOML and ProtoBuf rendering1118-1119-```go1120-func main() {1121- r := gin.Default()1122-1123- // gin.H is a shortcut for map[string]interface{}1124- r.GET("/someJSON", func(c *gin.Context) {1125- c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1126- })1127-1128- r.GET("/moreJSON", func(c *gin.Context) {1129- // You also can use a struct1130- var msg struct {1131- Name string `json:"user"`1132- Message string1133- Number int1134- }1135- msg.Name = "Lena"1136- msg.Message = "hey"1137- msg.Number = 1231138- // Note that msg.Name becomes "user" in the JSON1139- // Will output : {"user": "Lena", "Message": "hey", "Number": 123}1140- c.JSON(http.StatusOK, msg)1141- })1142-1143- r.GET("/someXML", func(c *gin.Context) {1144- c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1145- })1146-1147- r.GET("/someYAML", func(c *gin.Context) {1148- c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1149- })1150-1151- r.GET("/someTOML", func(c *gin.Context) {1152- c.TOML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1153- })1154-1155- r.GET("/someProtoBuf", func(c *gin.Context) {1156- reps := []int64{int64(1), int64(2)}1157- label := "test"1158- // The specific definition of protobuf is written in the testdata/protoexample file.1159- data := &protoexample.Test{1160- Label: &label,1161- Reps: reps,1162- }1163- // Note that data becomes binary data in the response1164- // Will output protoexample.Test protobuf serialized data1165- c.ProtoBuf(http.StatusOK, data)1166- })1167-1168- // Listen and serve on 0.0.0.0:80801169- r.Run(":8080")1170-}1171-```1172-1173-#### SecureJSON1174-1175-Using SecureJSON to prevent json hijacking. Default prepends `"while(1),"` to response body if the given struct is array values.1176-1177-```go1178-func main() {1179- r := gin.Default()1180-1181- // You can also use your own secure json prefix1182- // r.SecureJsonPrefix(")]}',\n")1183-1184- r.GET("/someJSON", func(c *gin.Context) {1185- names := []string{"lena", "austin", "foo"}1186-1187- // Will output : while(1);["lena","austin","foo"]1188- c.SecureJSON(http.StatusOK, names)1189- })1190-1191- // Listen and serve on 0.0.0.0:80801192- r.Run(":8080")1193-}1194-```1195-1196-#### JSONP1197-1198-Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists.1199-1200-```go1201-func main() {1202- r := gin.Default()1203-1204- r.GET("/JSONP", func(c *gin.Context) {1205- data := gin.H{1206- "foo": "bar",1207- }1208-1209- //callback is x1210- // Will output : x({\"foo\":\"bar\"})1211- c.JSONP(http.StatusOK, data)1212- })1213-1214- // Listen and serve on 0.0.0.0:80801215- r.Run(":8080")1216-1217- // client1218- // curl http://127.0.0.1:8080/JSONP?callback=x1219-}1220-```1221-1222-#### AsciiJSON1223-1224-Using AsciiJSON to Generates ASCII-only JSON with escaped non-ASCII characters.1225-1226-```go1227-func main() {1228- r := gin.Default()1229-1230- r.GET("/someJSON", func(c *gin.Context) {1231- data := gin.H{1232- "lang": "GO语言",1233- "tag": "<br>",1234- }1235-1236- // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}1237- c.AsciiJSON(http.StatusOK, data)1238- })1239-1240- // Listen and serve on 0.0.0.0:80801241- r.Run(":8080")1242-}1243-```1244-1245-#### PureJSON1246-1247-Normally, 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.1248-This feature is unavailable in Go 1.6 and lower.1249-1250-```go1251-func main() {1252- r := gin.Default()1253-1254- // Serves unicode entities1255- r.GET("/json", func(c *gin.Context) {1256- c.JSON(http.StatusOK, gin.H{1257- "html": "<b>Hello, world!</b>",1258- })1259- })1260-1261- // Serves literal characters1262- r.GET("/purejson", func(c *gin.Context) {1263- c.PureJSON(http.StatusOK, gin.H{1264- "html": "<b>Hello, world!</b>",1265- })1266- })1267-1268- // listen and serve on 0.0.0.0:80801269- r.Run(":8080")1270-}1271-```1272-1273-### Serving static files1274-1275-```go1276-func main() {1277- router := gin.Default()1278- router.Static("/assets", "./assets")1279- router.StaticFS("/more_static", http.Dir("my_file_system"))1280- router.StaticFile("/favicon.ico", "./resources/favicon.ico")1281- router.StaticFileFS("/more_favicon.ico", "more_favicon.ico", http.Dir("my_file_system"))1282- 1283- // Listen and serve on 0.0.0.0:80801284- router.Run(":8080")1285-}1286-```1287-1288-### Serving data from file1289-1290-```go1291-func main() {1292- router := gin.Default()1293-1294- router.GET("/local/file", func(c *gin.Context) {1295- c.File("local/file.go")1296- })1297-1298- var fs http.FileSystem = // ...1299- router.GET("/fs/file", func(c *gin.Context) {1300- c.FileFromFS("fs/file.go", fs)1301- })1302-}1303-1304-```1305-1306-### Serving data from reader1307-1308-```go1309-func main() {1310- router := gin.Default()1311- router.GET("/someDataFromReader", func(c *gin.Context) {1312- response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")1313- if err != nil || response.StatusCode != http.StatusOK {1314- c.Status(http.StatusServiceUnavailable)1315- return1316- }1317-1318- reader := response.Body1319- defer reader.Close()1320- contentLength := response.ContentLength1321- contentType := response.Header.Get("Content-Type")1322-1323- extraHeaders := map[string]string{1324- "Content-Disposition": `attachment; filename="gopher.png"`,1325- }1326-1327- c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)1328- })1329- router.Run(":8080")1330-}1331-```1332-1333-### HTML rendering1334-1335-Using LoadHTMLGlob() or LoadHTMLFiles()1336-1337-```go1338-func main() {1339- router := gin.Default()1340- router.LoadHTMLGlob("templates/*")1341- //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")1342- router.GET("/index", func(c *gin.Context) {1343- c.HTML(http.StatusOK, "index.tmpl", gin.H{1344- "title": "Main website",1345- })1346- })1347- router.Run(":8080")1348-}1349-```1350-1351-templates/index.tmpl1352-1353-```html1354-<html>1355- <h1>1356- {{ .title }}1357- </h1>1358-</html>1359-```1360-1361-Using templates with same name in different directories1362-1363-```go1364-func main() {1365- router := gin.Default()1366- router.LoadHTMLGlob("templates/**/*")1367- router.GET("/posts/index", func(c *gin.Context) {1368- c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{1369- "title": "Posts",1370- })1371- })1372- router.GET("/users/index", func(c *gin.Context) {1373- c.HTML(http.StatusOK, "users/index.tmpl", gin.H{1374- "title": "Users",1375- })1376- })1377- router.Run(":8080")1378-}1379-```1380-1381-templates/posts/index.tmpl1382-1383-```html1384-{{ define "posts/index.tmpl" }}1385-<html><h1>1386- {{ .title }}1387-</h1>1388-<p>Using posts/index.tmpl</p>1389-</html>1390-{{ end }}1391-```1392-1393-templates/users/index.tmpl1394-1395-```html1396-{{ define "users/index.tmpl" }}1397-<html><h1>1398- {{ .title }}1399-</h1>1400-<p>Using users/index.tmpl</p>1401-</html>1402-{{ end }}1403-```1404-1405-#### Custom Template renderer1406-1407-You can also use your own html template render1408-1409-```go1410-import "html/template"1411-1412-func main() {1413- router := gin.Default()1414- html := template.Must(template.ParseFiles("file1", "file2"))1415- router.SetHTMLTemplate(html)1416- router.Run(":8080")1417-}1418-```1419-1420-#### Custom Delimiters1421-1422-You may use custom delims1423-1424-```go1425- r := gin.Default()1426- r.Delims("{[{", "}]}")1427- r.LoadHTMLGlob("/path/to/templates")1428-```1429-1430-#### Custom Template Funcs1431-1432-See the detail [example code](https://github.com/gin-gonic/examples/tree/master/template).1433-1434-main.go1435-1436-```go1437-import (1438- "fmt"1439- "html/template"1440- "net/http"1441- "time"1442-1443- "github.com/gin-gonic/gin"1444-)1445-1446-func formatAsDate(t time.Time) string {1447- year, month, day := t.Date()1448- return fmt.Sprintf("%d/%02d/%02d", year, month, day)1449-}1450-1451-func main() {1452- router := gin.Default()1453- router.Delims("{[{", "}]}")1454- router.SetFuncMap(template.FuncMap{1455- "formatAsDate": formatAsDate,1456- })1457- router.LoadHTMLFiles("./testdata/template/raw.tmpl")1458-1459- router.GET("/raw", func(c *gin.Context) {1460- c.HTML(http.StatusOK, "raw.tmpl", gin.H{1461- "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),1462- })1463- })1464-1465- router.Run(":8080")1466-}1467-1468-```1469-1470-raw.tmpl1471-1472-```html1473-Date: {[{.now | formatAsDate}]}1474-```1475-1476-Result:1477-1478-```sh1479-Date: 2017/07/011480-```1481-1482-### Multitemplate1483-1484-Gin 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`.1485-1486-### Redirects1487-1488-Issuing a HTTP redirect is easy. Both internal and external locations are supported.1489-1490-```go1491-r.GET("/test", func(c *gin.Context) {1492- c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")1493-})1494-```1495-1496-Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444)1497-1498-```go1499-r.POST("/test", func(c *gin.Context) {1500- c.Redirect(http.StatusFound, "/foo")1501-})1502-```1503-1504-Issuing a Router redirect, use `HandleContext` like below.1505-1506-``` go1507-r.GET("/test", func(c *gin.Context) {1508- c.Request.URL.Path = "/test2"1509- r.HandleContext(c)1510-})1511-r.GET("/test2", func(c *gin.Context) {1512- c.JSON(http.StatusOK, gin.H{"hello": "world"})1513-})1514-```1515-1516-### Custom Middleware1517-1518-```go1519-func Logger() gin.HandlerFunc {1520- return func(c *gin.Context) {1521- t := time.Now()1522-1523- // Set example variable1524- c.Set("example", "12345")1525-1526- // before request1527-1528- c.Next()1529-1530- // after request1531- latency := time.Since(t)1532- log.Print(latency)1533-1534- // access the status we are sending1535- status := c.Writer.Status()1536- log.Println(status)1537- }1538-}1539-1540-func main() {1541- r := gin.New()1542- r.Use(Logger())1543-1544- r.GET("/test", func(c *gin.Context) {1545- example := c.MustGet("example").(string)1546-1547- // it would print: "12345"1548- log.Println(example)1549- })1550-1551- // Listen and serve on 0.0.0.0:80801552- r.Run(":8080")1553-}1554-```1555-1556-### Using BasicAuth() middleware1557-1558-```go1559-// simulate some private data1560-var secrets = gin.H{1561- "foo": gin.H{"email": "foo@bar.com", "phone": "123433"},1562- "austin": gin.H{"email": "austin@example.com", "phone": "666"},1563- "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},1564-}1565-1566-func main() {1567- r := gin.Default()1568-1569- // Group using gin.BasicAuth() middleware1570- // gin.Accounts is a shortcut for map[string]string1571- authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{1572- "foo": "bar",1573- "austin": "1234",1574- "lena": "hello2",1575- "manu": "4321",1576- }))1577-1578- // /admin/secrets endpoint1579- // hit "localhost:8080/admin/secrets1580- authorized.GET("/secrets", func(c *gin.Context) {1581- // get user, it was set by the BasicAuth middleware1582- user := c.MustGet(gin.AuthUserKey).(string)1583- if secret, ok := secrets[user]; ok {1584- c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})1585- } else {1586- c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})1587- }1588- })1589-1590- // Listen and serve on 0.0.0.0:80801591- r.Run(":8080")1592-}1593-```1594-1595-### Goroutines inside a middleware1596-1597-When 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.1598-1599-```go1600-func main() {1601- r := gin.Default()1602-1603- r.GET("/long_async", func(c *gin.Context) {1604- // create copy to be used inside the goroutine1605- cCp := c.Copy()1606- go func() {1607- // simulate a long task with time.Sleep(). 5 seconds1608- time.Sleep(5 * time.Second)1609-1610- // note that you are using the copied context "cCp", IMPORTANT1611- log.Println("Done! in path " + cCp.Request.URL.Path)1612- }()1613- })1614-1615- r.GET("/long_sync", func(c *gin.Context) {1616- // simulate a long task with time.Sleep(). 5 seconds1617- time.Sleep(5 * time.Second)1618-1619- // since we are NOT using a goroutine, we do not have to copy the context1620- log.Println("Done! in path " + c.Request.URL.Path)1621- })1622-1623- // Listen and serve on 0.0.0.0:80801624- r.Run(":8080")1625-}1626-```1627-1628-### Custom HTTP configuration1629-1630-Use `http.ListenAndServe()` directly, like this:1631-1632-```go1633-func main() {1634- router := gin.Default()1635- http.ListenAndServe(":8080", router)1636-}1637-```1638-1639-or1640-1641-```go1642-func main() {1643- router := gin.Default()1644-1645- s := &http.Server{1646- Addr: ":8080",1647- Handler: router,1648- ReadTimeout: 10 * time.Second,1649- WriteTimeout: 10 * time.Second,1650- MaxHeaderBytes: 1 << 20,1651- }1652- s.ListenAndServe()1653-}1654-```1655-1656-### Support Let's Encrypt1657-1658-example for 1-line LetsEncrypt HTTPS servers.1659-1660-```go1661-package main1662-1663-import (1664- "log"1665- "net/http"1666-1667- "github.com/gin-gonic/autotls"1668- "github.com/gin-gonic/gin"1669-)1670-1671-func main() {1672- r := gin.Default()1673-1674- // Ping handler1675- r.GET("/ping", func(c *gin.Context) {1676- c.String(http.StatusOK, "pong")1677- })1678-1679- log.Fatal(autotls.Run(r, "example1.com", "example2.com"))1680-}1681-```1682-1683-example for custom autocert manager.1684-1685-```go1686-package main1687-1688-import (1689- "log"1690- "net/http"1691-1692- "github.com/gin-gonic/autotls"1693- "github.com/gin-gonic/gin"1694- "golang.org/x/crypto/acme/autocert"1695-)1696-1697-func main() {1698- r := gin.Default()1699-1700- // Ping handler1701- r.GET("/ping", func(c *gin.Context) {1702- c.String(http.StatusOK, "pong")1703- })1704-1705- m := autocert.Manager{1706- Prompt: autocert.AcceptTOS,1707- HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),1708- Cache: autocert.DirCache("/var/www/.cache"),1709- }1710-1711- log.Fatal(autotls.RunWithManager(r, &m))1712-}1713-```1714-1715-### Run multiple service using Gin1716-1717-See the [question](https://github.com/gin-gonic/gin/issues/346) and try the following example:1718-1719-```go1720-package main1721-1722-import (1723- "log"1724- "net/http"1725- "time"1726-1727- "github.com/gin-gonic/gin"1728- "golang.org/x/sync/errgroup"1729-)1730-1731-var (1732- g errgroup.Group1733-)1734-1735-func router01() http.Handler {1736- e := gin.New()1737- e.Use(gin.Recovery())1738- e.GET("/", func(c *gin.Context) {1739- c.JSON(1740- http.StatusOK,1741- gin.H{1742- "code": http.StatusOK,1743- "error": "Welcome server 01",1744- },1745- )1746- })1747-1748- return e1749-}1750-1751-func router02() http.Handler {1752- e := gin.New()1753- e.Use(gin.Recovery())1754- e.GET("/", func(c *gin.Context) {1755- c.JSON(1756- http.StatusOK,1757- gin.H{1758- "code": http.StatusOK,1759- "error": "Welcome server 02",1760- },1761- )1762- })1763-1764- return e1765-}1766-1767-func main() {1768- server01 := &http.Server{1769- Addr: ":8080",1770- Handler: router01(),1771- ReadTimeout: 5 * time.Second,1772- WriteTimeout: 10 * time.Second,1773- }1774-1775- server02 := &http.Server{1776- Addr: ":8081",1777- Handler: router02(),1778- ReadTimeout: 5 * time.Second,1779- WriteTimeout: 10 * time.Second,1780- }1781-1782- g.Go(func() error {1783- err := server01.ListenAndServe()1784- if err != nil && err != http.ErrServerClosed {1785- log.Fatal(err)1786- }1787- return err1788- })1789-1790- g.Go(func() error {1791- err := server02.ListenAndServe()1792- if err != nil && err != http.ErrServerClosed {1793- log.Fatal(err)1794- }1795- return err1796- })1797-1798- if err := g.Wait(); err != nil {1799- log.Fatal(err)1800- }1801-}1802-```1803-1804-### Graceful shutdown or restart1805-1806-There are a few approaches you can use to perform a graceful shutdown or restart. You can make use of third-party packages specifically built for that, or you can manually do the same with the functions and methods from the built-in packages.1807-1808-#### Third-party packages1809-1810-We can use [fvbock/endless](https://github.com/fvbock/endless) to replace the default `ListenAndServe`. Refer to issue [#296](https://github.com/gin-gonic/gin/issues/296) for more details.1811-1812-```go1813-router := gin.Default()1814-router.GET("/", handler)1815-// [...]1816-endless.ListenAndServe(":4242", router)1817-```1818-1819-Alternatives:1820-1821-* [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers.1822-* [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server.1823-* [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully.1824-1825-#### Manually1826-1827-In case you are using Go 1.8 or a later version, you may not need to use those libraries. Consider using `http.Server`'s built-in [Shutdown()](https://pkg.go.dev/net/http#Server.Shutdown) method for graceful shutdowns. The example below describes its usage, and we've got more examples using gin [here](https://github.com/gin-gonic/examples/tree/master/graceful-shutdown).1828-1829-```go1830-// +build go1.81831-1832-package main1833-1834-import (1835- "context"1836- "log"1837- "net/http"1838- "os"1839- "os/signal"1840- "syscall"1841- "time"1842-1843- "github.com/gin-gonic/gin"1844-)1845-1846-func main() {1847- router := gin.Default()1848- router.GET("/", func(c *gin.Context) {1849- time.Sleep(5 * time.Second)1850- c.String(http.StatusOK, "Welcome Gin Server")1851- })1852-1853- srv := &http.Server{1854- Addr: ":8080",1855- Handler: router,1856- }1857-1858- // Initializing the server in a goroutine so that1859- // it won't block the graceful shutdown handling below1860- go func() {1861- if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {1862- log.Printf("listen: %s\n", err)1863- }1864- }()1865-1866- // Wait for interrupt signal to gracefully shutdown the server with1867- // a timeout of 5 seconds.1868- quit := make(chan os.Signal)1869- // kill (no param) default send syscall.SIGTERM1870- // kill -2 is syscall.SIGINT1871- // kill -9 is syscall.SIGKILL but can't be caught, so don't need to add it1872- signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)1873- <-quit1874- log.Println("Shutting down server...")1875-1876- // The context is used to inform the server it has 5 seconds to finish1877- // the request it is currently handling1878- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)1879- defer cancel()1880-1881- if err := srv.Shutdown(ctx); err != nil {1882- log.Fatal("Server forced to shutdown:", err)1883- }1884-1885- log.Println("Server exiting")1886-}1887-```1888-1889-### Build a single binary with templates1890-1891-You can build a server into a single binary containing templates by using the [embed](https://pkg.go.dev/embed) package.1892-1893-```go1894-package main1895-1896-import (1897- "embed"1898- "html/template"1899- "net/http"1900-1901- "github.com/gin-gonic/gin"1902-)1903-1904-//go:embed assets/* templates/*1905-var f embed.FS1906-1907-func main() {1908- router := gin.Default()1909- templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl"))1910- router.SetHTMLTemplate(templ)1911-1912- // example: /public/assets/images/example.png1913- router.StaticFS("/public", http.FS(f))1914-1915- router.GET("/", func(c *gin.Context) {1916- c.HTML(http.StatusOK, "index.tmpl", gin.H{1917- "title": "Main website",1918- })1919- })1920-1921- router.GET("/foo", func(c *gin.Context) {1922- c.HTML(http.StatusOK, "bar.tmpl", gin.H{1923- "title": "Foo website",1924- })1925- })1926-1927- router.GET("favicon.ico", func(c *gin.Context) {1928- file, _ := f.ReadFile("assets/favicon.ico")1929- c.Data(1930- http.StatusOK,1931- "image/x-icon",1932- file,1933- )1934- })1935-1936- router.Run(":8080")1937-}1938-```1939-1940-See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary/example02` directory.1941-1942-### Bind form-data request with custom struct1943-1944-The follow example using custom struct:1945-1946-```go1947-type StructA struct {1948- FieldA string `form:"field_a"`1949-}1950-1951-type StructB struct {1952- NestedStruct StructA1953- FieldB string `form:"field_b"`1954-}1955-1956-type StructC struct {1957- NestedStructPointer *StructA1958- FieldC string `form:"field_c"`1959-}1960-1961-type StructD struct {1962- NestedAnonyStruct struct {1963- FieldX string `form:"field_x"`1964- }1965- FieldD string `form:"field_d"`1966-}1967-1968-func GetDataB(c *gin.Context) {1969- var b StructB1970- c.Bind(&b)1971- c.JSON(http.StatusOK, gin.H{1972- "a": b.NestedStruct,1973- "b": b.FieldB,1974- })1975-}1976-1977-func GetDataC(c *gin.Context) {1978- var b StructC1979- c.Bind(&b)1980- c.JSON(http.StatusOK, gin.H{1981- "a": b.NestedStructPointer,1982- "c": b.FieldC,1983- })1984-}1985-1986-func GetDataD(c *gin.Context) {1987- var b StructD1988- c.Bind(&b)1989- c.JSON(http.StatusOK, gin.H{1990- "x": b.NestedAnonyStruct,1991- "d": b.FieldD,1992- })1993-}1994-1995-func main() {1996- r := gin.Default()1997- r.GET("/getb", GetDataB)1998- r.GET("/getc", GetDataC)1999- r.GET("/getd", GetDataD)2000-2001- r.Run()2002-}2003-```2004-2005-Using the command `curl` command result:2006-2007-```sh2008-$ curl "http://localhost:8080/getb?field_a=hello&field_b=world"2009-{"a":{"FieldA":"hello"},"b":"world"}2010-$ curl "http://localhost:8080/getc?field_a=hello&field_c=world"2011-{"a":{"FieldA":"hello"},"c":"world"}2012-$ curl "http://localhost:8080/getd?field_x=hello&field_d=world"2013-{"d":"world","x":{"FieldX":"hello"}}2014-```2015-2016-### Try to bind body into different structs2017-2018-The normal methods for binding request body consumes `c.Request.Body` and they2019-cannot be called multiple times.2020-2021-```go2022-type formA struct {2023- Foo string `json:"foo" xml:"foo" binding:"required"`2024-}2025-2026-type formB struct {2027- Bar string `json:"bar" xml:"bar" binding:"required"`2028-}2029-2030-func SomeHandler(c *gin.Context) {2031- objA := formA{}2032- objB := formB{}2033- // This c.ShouldBind consumes c.Request.Body and it cannot be reused.2034- if errA := c.ShouldBind(&objA); errA == nil {2035- c.String(http.StatusOK, `the body should be formA`)2036- // Always an error is occurred by this because c.Request.Body is EOF now.2037- } else if errB := c.ShouldBind(&objB); errB == nil {2038- c.String(http.StatusOK, `the body should be formB`)2039- } else {2040- ...2041- }2042-}2043-```2044-2045-For this, you can use `c.ShouldBindBodyWith`.2046-2047-```go2048-func SomeHandler(c *gin.Context) {2049- objA := formA{}2050- objB := formB{}2051- // This reads c.Request.Body and stores the result into the context.2052- if errA := c.ShouldBindBodyWith(&objA, binding.Form); errA == nil {2053- c.String(http.StatusOK, `the body should be formA`)2054- // At this time, it reuses body stored in the context.2055- } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {2056- c.String(http.StatusOK, `the body should be formB JSON`)2057- // And it can accepts other formats2058- } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {2059- c.String(http.StatusOK, `the body should be formB XML`)2060- } else {2061- ...2062- }2063-}2064-```2065-2066-1. `c.ShouldBindBodyWith` stores body into the context before binding. This has2067-a slight impact to performance, so you should not use this method if you are2068-enough to call binding at once.2069-2. This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`,2070-`ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`,2071-can be called by `c.ShouldBind()` multiple times without any damage to2072-performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)).2073-2074-### Bind form-data request with custom struct and custom tag2075-2076-```go2077-const (2078- customerTag = "url"2079- defaultMemory = 32 << 202080-)2081-2082-type customerBinding struct {}2083-2084-func (customerBinding) Name() string {2085- return "form"2086-}2087-2088-func (customerBinding) Bind(req *http.Request, obj interface{}) error {2089- if err := req.ParseForm(); err != nil {2090- return err2091- }2092- if err := req.ParseMultipartForm(defaultMemory); err != nil {2093- if err != http.ErrNotMultipart {2094- return err2095- }2096- }2097- if err := binding.MapFormWithTag(obj, req.Form, customerTag); err != nil {2098- return err2099- }2100- return validate(obj)2101-}2102-2103-func validate(obj interface{}) error {2104- if binding.Validator == nil {2105- return nil2106- }2107- return binding.Validator.ValidateStruct(obj)2108-}2109-2110-// Now we can do this!!!2111-// FormA is an external type that we can't modify it's tag2112-type FormA struct {2113- FieldA string `url:"field_a"`2114-}2115-2116-func ListHandler(s *Service) func(ctx *gin.Context) {2117- return func(ctx *gin.Context) {2118- var urlBinding = customerBinding{}2119- var opt FormA2120- err := ctx.MustBindWith(&opt, urlBinding)2121- if err != nil {2122- ...2123- }2124- ...2125- }2126-}2127-```2128-2129-### http2 server push2130-2131-http.Pusher is supported only **go1.8+**. See the [golang blog](https://go.dev/blog/h2push) for detail information.2132-2133-```go2134-package main2135-2136-import (2137- "html/template"2138- "log"2139- "net/http"2140-2141- "github.com/gin-gonic/gin"2142-)2143-2144-var html = template.Must(template.New("https").Parse(`2145-<html>2146-<head>2147- <title>Https Test</title>2148- <script src="/assets/app.js"></script>2149-</head>2150-<body>2151- <h1 style="color:red;">Welcome, Ginner!</h1>2152-</body>2153-</html>2154-`))2155-2156-func main() {2157- r := gin.Default()2158- r.Static("/assets", "./assets")2159- r.SetHTMLTemplate(html)2160-2161- r.GET("/", func(c *gin.Context) {2162- if pusher := c.Writer.Pusher(); pusher != nil {2163- // use pusher.Push() to do server push2164- if err := pusher.Push("/assets/app.js", nil); err != nil {2165- log.Printf("Failed to push: %v", err)2166- }2167- }2168- c.HTML(http.StatusOK, "https", gin.H{2169- "status": "success",2170- })2171- })2172-2173- // Listen and Server in https://127.0.0.1:80802174- r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")2175-}2176-```2177-2178-### Define format for the log of routes2179-2180-The default log of routes is:2181-2182-```sh2183-[GIN-debug] POST /foo --> main.main.func1 (3 handlers)2184-[GIN-debug] GET /bar --> main.main.func2 (3 handlers)2185-[GIN-debug] GET /status --> main.main.func3 (3 handlers)2186-```2187-2188-If 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`.2189-In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs.2190-2191-```go2192-import (2193- "log"2194- "net/http"2195-2196- "github.com/gin-gonic/gin"2197-)2198-2199-func main() {2200- r := gin.Default()2201- gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {2202- log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers)2203- }2204-2205- r.POST("/foo", func(c *gin.Context) {2206- c.JSON(http.StatusOK, "foo")2207- })2208-2209- r.GET("/bar", func(c *gin.Context) {2210- c.JSON(http.StatusOK, "bar")2211- })2212-2213- r.GET("/status", func(c *gin.Context) {2214- c.JSON(http.StatusOK, "ok")2215- })2216-2217- // Listen and Server in http://0.0.0.0:80802218- r.Run()2219-}2220-```2221-2222-### Set and get a cookie2223-2224-```go2225-import (2226- "fmt"2227-2228- "github.com/gin-gonic/gin"2229-)2230-2231-func main() {2232-2233- router := gin.Default()2234-2235- router.GET("/cookie", func(c *gin.Context) {2236-2237- cookie, err := c.Cookie("gin_cookie")2238-2239- if err != nil {2240- cookie = "NotSet"2241- c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)2242- }2243-2244- fmt.Printf("Cookie value: %s \n", cookie)2245- })2246-2247- router.Run()2248-}2249-```2250-2251-## Don't trust all proxies2252-2253-Gin lets you specify which headers to hold the real client IP (if any),2254-as well as specifying which proxies (or direct clients) you trust to2255-specify one of these headers.2256-2257-Use function `SetTrustedProxies()` on your `gin.Engine` to specify network addresses2258-or network CIDRs from where clients which their request headers related to client2259-IP can be trusted. They can be IPv4 addresses, IPv4 CIDRs, IPv6 addresses or2260-IPv6 CIDRs.2261-2262-**Attention:** Gin trust all proxies by default if you don't specify a trusted 2263-proxy using the function above, **this is NOT safe**. At the same time, if you don't2264-use any proxy, you can disable this feature by using `Engine.SetTrustedProxies(nil)`,2265-then `Context.ClientIP()` will return the remote address directly to avoid some2266-unnecessary computation.2267-2268-```go2269-import (2270- "fmt"2271-2272- "github.com/gin-gonic/gin"2273-)2274-2275-func main() {2276-2277- router := gin.Default()2278- router.SetTrustedProxies([]string{"192.168.1.2"})2279-2280- router.GET("/", func(c *gin.Context) {2281- // If the client is 192.168.1.2, use the X-Forwarded-For2282- // header to deduce the original client IP from the trust-2283- // worthy parts of that header.2284- // Otherwise, simply return the direct client IP2285- fmt.Printf("ClientIP: %s\n", c.ClientIP())2286- })2287- router.Run()2288-}2289-```2290-2291-**Notice:** If you are using a CDN service, you can set the `Engine.TrustedPlatform`2292-to skip TrustedProxies check, it has a higher priority than TrustedProxies. 2293-Look at the example below:2294-2295-```go2296-import (2297- "fmt"2298-2299- "github.com/gin-gonic/gin"2300-)2301-2302-func main() {2303-2304- router := gin.Default()2305- // Use predefined header gin.PlatformXXX2306- router.TrustedPlatform = gin.PlatformGoogleAppEngine2307- // Or set your own trusted request header for another trusted proxy service2308- // Don't set it to any suspect request header, it's unsafe2309- router.TrustedPlatform = "X-CDN-IP"2310-2311- router.GET("/", func(c *gin.Context) {2312- // If you set TrustedPlatform, ClientIP() will resolve the2313- // corresponding header and return IP directly2314- fmt.Printf("ClientIP: %s\n", c.ClientIP())2315- })2316- router.Run()2317-}2318-```2319-2320-## Testing2321-2322-The `net/http/httptest` package is preferable way for HTTP testing.2323-2324-```go2325-package main2326-2327-import (2328- "net/http"2329-2330- "github.com/gin-gonic/gin"2331-)2332-2333-func setupRouter() *gin.Engine {2334- r := gin.Default()2335- r.GET("/ping", func(c *gin.Context) {2336- c.String(http.StatusOK, "pong")2337- })2338- return r2339-}2340-2341-func main() {2342- r := setupRouter()2343- r.Run(":8080")2344-}2345-```2346-2347-Test for code example above:2348-2349-```go2350-package main2351-2352-import (2353- "net/http"2354- "net/http/httptest"2355- "testing"2356-2357- "github.com/stretchr/testify/assert"2358-)2359-2360-func TestPingRoute(t *testing.T) {2361- router := setupRouter()2362-2363- w := httptest.NewRecorder()2364- req, _ := http.NewRequest(http.MethodGet, "/ping", nil)2365- router.ServeHTTP(w, req)2366-2367- assert.Equal(t, http.StatusOK, w.Code)2368- assert.Equal(t, "pong", w.Body.String())2369-}2370-```2371-163 ## Users164 165 Awesome project lists using [Gin](https://github.com/gin-gonic/gin) web framework.166 3 unmodified lines170 * [lura](https://github.com/luraproject/lura): Ultra performant API Gateway with middlewares.171 * [picfit](https://github.com/thoas/picfit): An image resizing server written in Go.172 * [brigade](https://github.com/brigadecore/brigade): Event-based Scripting for Kubernetes.173 * [dkron](https://github.com/distribworks/dkron): Distributed, fault tolerant job scheduling system.174+175+176+## Contributing177+178+Gin is the work of hundreds of contributors. We appreciate your help!179+180+Please see [CONTRIBUTING](CONTRIBUTING.md) for details on submitting patches and the contribution workflow.