doc.md
This file
Path
docs/doc.md
2,243 lines · 54.6 KiB · Markdown
Last changed by
chore: support min go version 1.18 (#3511)thinkeroubefore adoption1e1f0b1
History of this fileTake it
docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
lines 1–427why, one step back1# Gin Quick Start23## Contents45- [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)6566## Build tags6768### Build with json replacement6970Gin uses `encoding/json` as default json package but you can change it by build from other tags.7172[jsoniter](https://github.com/json-iterator/go)7374```sh75go build -tags=jsoniter .76```7778[go-json](https://github.com/goccy/go-json)7980```sh81go build -tags=go_json .82```8384[sonic](https://github.com/bytedance/sonic) (you have to ensure that your cpu support avx instruction.)8586```sh87$ go build -tags="sonic avx" .88```8990### Build without `MsgPack` rendering feature9192Gin enables `MsgPack` rendering feature by default. But you can disable this feature by specifying `nomsgpack` build tag.9394```sh95go build -tags=nomsgpack .96```9798This is useful to reduce the binary size of executable files. See the [detail information](https://github.com/gin-gonic/gin/pull/1852).99100## API Examples101102You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples).103104### Using GET, POST, PUT, PATCH, DELETE and OPTIONS105106```go107func main() {108 // Creates a gin router with default middleware:109 // logger and recovery (crash-free) middleware110 router := gin.Default()111112 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)119120 // 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```126127### Parameters in path128129```go130func main() {131 router := gin.Default()132133 // 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 })138139 // 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 })147148 // 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 })153154 // 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 })160161 router.Run(":8080")162}163```164165### Querystring parameters166167```go168func main() {169 router := gin.Default()170171 // 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")176177 c.String(http.StatusOK, "Hello %s %s", firstname, lastname)178 })179 router.Run(":8080")180}181```182183### Multipart/Urlencoded Form184185```go186func main() {187 router := gin.Default()188189 router.POST("/form_post", func(c *gin.Context) {190 message := c.PostForm("message")191 nick := c.DefaultPostForm("nick", "anonymous")192193 c.JSON(http.StatusOK, gin.H{194 "status": "posted",195 "message": message,196 "nick": nick,197 })198 })199 router.Run(":8080")200}201```202203### Another example: query + post form204205```sh206POST /post?id=1234&page=1 HTTP/1.1207Content-Type: application/x-www-form-urlencoded208209name=manu&message=this_is_great210```211212```go213func main() {214 router := gin.Default()215216 router.POST("/post", func(c *gin.Context) {217218 id := c.Query("id")219 page := c.DefaultQuery("page", "0")220 name := c.PostForm("name")221 message := c.PostForm("message")222223 fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)224 })225 router.Run(":8080")226}227```228229```sh230id: 1234; page: 1; name: manu; message: this_is_great231```232233### Map as querystring or postform parameters234235```sh236POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1237Content-Type: application/x-www-form-urlencoded238239names[first]=thinkerou&names[second]=tianou240```241242```go243func main() {244 router := gin.Default()245246 router.POST("/post", func(c *gin.Context) {247248 ids := c.QueryMap("ids")249 names := c.PostFormMap("names")250251 fmt.Printf("ids: %v; names: %v", ids, names)252 })253 router.Run(":8080")254}255```256257```sh258ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou]259```260261### Upload files262263#### Single file264265References 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).266267`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)268269> 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.270271```go272func 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)280281 // Upload the file to specific dst.282 c.SaveUploadedFile(file, dst)283284 c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))285 })286 router.Run(":8080")287}288```289290How to `curl`:291292```bash293curl -X POST http://localhost:8080/upload \294 -F "file=@/Users/appleboy/test.zip" \295 -H "Content-Type: multipart/form-data"296```297298#### Multiple files299300See the detail [example code](https://github.com/gin-gonic/examples/tree/master/upload-file/multiple).301302```go303func 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[]"]311312 for _, file := range files {313 log.Println(file.Filename)314315 // 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```323324How to `curl`:325326```bash327curl -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```332333### Grouping routes334335```go336func main() {337 router := gin.Default()338339 // Simple group: v1340 v1 := router.Group("/v1")341 {342 v1.POST("/login", loginEndpoint)343 v1.POST("/submit", submitEndpoint)344 v1.POST("/read", readEndpoint)345 }346347 // Simple group: v2348 v2 := router.Group("/v2")349 {350 v2.POST("/login", loginEndpoint)351 v2.POST("/submit", submitEndpoint)352 v2.POST("/read", readEndpoint)353 }354355 router.Run(":8080")356}357```358359### Blank Gin without middleware by default360361Use362363```go364r := gin.New()365```366367instead of368369```go370// Default With the Logger and Recovery middleware already attached371r := gin.Default()372```373374### Using middleware375376```go377func main() {378 // Creates a router without any middleware by default379 r := gin.New()380381 // 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())385386 // Recovery middleware recovers from any panics and writes a 500 if there was one.387 r.Use(gin.Recovery())388389 // Per route middleware, you can add as many as you desire.390 r.GET("/benchmark", MyBenchLogger(), benchEndpoint)391392 // 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)403404 // nested group405 testing := authorized.Group("testing")406 // visit 0.0.0.0:8080/testing/analytics407 testing.GET("/analytics", analyticsEndpoint)408 }409410 // Listen and serve on 0.0.0.0:8080411 r.Run(":8080")412}413```414415### Custom Recovery behavior416417```go418func main() {419 // Creates a router without any middleware by default420 r := gin.New()421422 // 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())426427 // Recovery middleware recovers from any panics and writes a 500 if there was one.chore: support min go version 1.18 (#3511)thinkeroubefore adoption1e1f0b1
line 428why, one step back428 r.Use(gin.CustomRecovery(func(c *gin.Context, recovered any) {docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
lines 429–452why, one step back429 if err, ok := recovered.(string); ok {430 c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))431 }432 c.AbortWithStatus(http.StatusInternalServerError)433 }))434435 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 })439440 r.GET("/", func(c *gin.Context) {441 c.String(http.StatusOK, "ohai")442 })443444 // Listen and serve on 0.0.0.0:8080445 r.Run(":8080")446}447```448449### How to write log file450451```go452func main() {docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 453–454why, one step back453 // Disable Console Color, you don't need console color when writing the logs to file.454 gin.DisableConsoleColor()docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
line 455why, one step back455docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 456–458why, one step back456 // Logging to a file.457 f, _ := os.Create("gin.log")458 gin.DefaultWriter = io.MultiWriter(f)docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
line 459why, one step back459docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 460–461why, one step back460 // 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)docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
line 462why, one step back462docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 463–466why, one step back463 router := gin.Default()464 router.GET("/ping", func(c *gin.Context) {465 c.String(http.StatusOK, "pong")466 })docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
line 467why, one step back467docs: update markdown format (#3446)apriil15before adoptionc58e0d5
line 468why, one step back468 router.Run(":8080")docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
lines 469–518why, one step back469}470```471472### Custom Log Format473474```go475func main() {476 router := gin.New()477478 // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter479 // By default gin.DefaultWriter = os.Stdout480 router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {481482 // 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())496497 router.GET("/ping", func(c *gin.Context) {498 c.String(http.StatusOK, "pong")499 })500501 router.Run(":8080")502}503```504505Sample Output506507```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```510511### Controlling Log output coloring512513By default, logs output on console should be colorized depending on the detected TTY.514515Never colorize logs:516517```go518func main() {docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 519–520why, one step back519 // Disable log's color520 gin.DisableConsoleColor()docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
line 521why, one step back521docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 522–524why, one step back522 // Creates a gin router with default middleware:523 // logger and recovery (crash-free) middleware524 router := gin.Default()docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
line 525why, one step back525docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 526–528why, one step back526 router.GET("/ping", func(c *gin.Context) {527 c.String(http.StatusOK, "pong")528 })docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
line 529why, one step back529docs: update markdown format (#3446)apriil15before adoptionc58e0d5
line 530why, one step back530 router.Run(":8080")docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
lines 531–537why, one step back531}532```533534Always colorize logs:535536```go537func main() {docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 538–539why, one step back538 // Force log's color539 gin.ForceConsoleColor()docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
line 540why, one step back540docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 541–543why, one step back541 // Creates a gin router with default middleware:542 // logger and recovery (crash-free) middleware543 router := gin.Default()docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
line 544why, one step back544docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 545–547why, one step back545 router.GET("/ping", func(c *gin.Context) {546 c.String(http.StatusOK, "pong")547 })docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
line 548why, one step back548docs: update markdown format (#3446)apriil15before adoptionc58e0d5
line 549why, one step back549 router.Run(":8080")docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
lines 550–788why, one step back550}551```552553### Model binding and validation554555To 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).556557Gin 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).558559Note 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"`.560561Also, Gin provides two sets of methods for binding:562563- **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.569570When 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`.571572You 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.573574```go575// Binding from JSON576type 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}580581func main() {582 router := gin.Default()583584 // 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 }591592 if json.User != "manu" || json.Password != "123" {593 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})594 return595 }596597 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})598 })599600 // 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 }612613 if xml.User != "manu" || xml.Password != "123" {614 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})615 return616 }617618 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})619 })620621 // 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 }629630 if form.User != "manu" || form.Password != "123" {631 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})632 return633 }634635 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})636 })637638 // Listen and serve on 0.0.0.0:8080639 router.Run(":8080")640}641```642643Sample request644645```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```665666Skip 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.667668### Custom Validators669670It is also possible to register custom validators. See the [example code](https://github.com/gin-gonic/examples/tree/master/custom-validation/server.go).671672```go673package main674675import (676 "net/http"677 "time"678679 "github.com/gin-gonic/gin"680 "github.com/gin-gonic/gin/binding"681 "github.com/go-playground/validator/v10"682)683684// Booking contains binded and validated data.685type 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}689690var 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}700701func main() {702 route := gin.Default()703704 if v, ok := binding.Validator.Engine().(*validator.Validate); ok {705 v.RegisterValidation("bookabledate", bookableDate)706 }707708 route.GET("/bookable", getBookable)709 route.Run(":8085")710}711712func 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```721722```console723$ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17"724{"message":"Booking dates are valid!"}725726$ 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"}728729$ 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```732733[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way.734See the [struct-lvl-validation example](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) to learn more.735736### Only Bind Query String737738`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).739740```go741package main742743import (744 "log"745 "net/http"746747 "github.com/gin-gonic/gin"748)749750type Person struct {751 Name string `form:"name"`752 Address string `form:"address"`753}754755func main() {756 route := gin.Default()757 route.Any("/testing", startPage)758 route.Run(":8085")759}760761func 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}770771```772773### Bind Query String or Post Data774775See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292).776777```go778package main779780import (781 "log"782 "net/http"783 "time"784785 "github.com/gin-gonic/gin"786)787788type Person struct {docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 789–793why, one step back789 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"`docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
lines 794–806why, one step back794}795796func main() {797 route := gin.Default()798 route.GET("/testing", startPage)799 route.Run(":8085")800}801802func 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#L88docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 807–813why, one step back807 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 }docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
lines 814–998why, one step back814815 c.String(http.StatusOK, "Success")816}817```818819Test it with:820821```sh822curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"823```824825### Bind Uri826827See the [detail information](https://github.com/gin-gonic/gin/issues/846).828829```go830package main831832import (833 "net/http"834835 "github.com/gin-gonic/gin"836)837838type Person struct {839 ID string `uri:"id" binding:"required,uuid"`840 Name string `uri:"name" binding:"required"`841}842843func 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```856857Test it with:858859```sh860curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3861curl -v localhost:8088/thinkerou/not-uuid862```863864### Bind Header865866```go867package main868869import (870 "fmt"871 "net/http"872873 "github.com/gin-gonic/gin"874)875876type testHeader struct {877 Rate int `header:"Rate"`878 Domain string `header:"Domain"`879}880881func main() {882 r := gin.Default()883 r.GET("/", func(c *gin.Context) {884 h := testHeader{}885886 if err := c.ShouldBindHeader(&h); err != nil {887 c.JSON(http.StatusOK, err)888 }889890 fmt.Printf("%#v\n", h)891 c.JSON(http.StatusOK, gin.H{"Rate": h.Rate, "Domain": h.Domain})892 })893894 r.Run()895896// client897// curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/898// output899// {"Domain":"music","Rate":300}900}901```902903### Bind HTML checkboxes904905See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)906907main.go908909```go910...911912type myForm struct {913 Colors []string `form:"colors[]"`914}915916...917918func formHandler(c *gin.Context) {919 var fakeForm myForm920 c.ShouldBind(&fakeForm)921 c.JSON(http.StatusOK, gin.H{"color": fakeForm.Colors})922}923924...925926```927928form.html929930```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```942943result:944945```json946{"color":["red","green","blue"]}947```948949### Multipart/Urlencoded binding950951```go952type ProfileForm struct {953 Name string `form:"name" binding:"required"`954 Avatar *multipart.FileHeader `form:"avatar" binding:"required"`955956 // or for multiple files957 // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"`958}959960func 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 }972973 err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename)974 if err != nil {975 c.String(http.StatusInternalServerError, "unknown error")976 return977 }978979 // db.Save(&form)980981 c.String(http.StatusOK, "ok")982 })983 router.Run(":8080")984}985```986987Test it with:988989```sh990curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile991```992993### XML, JSON, YAML, TOML and ProtoBuf rendering994995```go996func main() {997 r := gin.Default()998chore: support min go version 1.18 (#3511)thinkeroubefore adoption1e1f0b1
line 999why, one step back999 // gin.H is a shortcut for map[string]anydocs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
lines 1000–1313why, one step back1000 r.GET("/someJSON", func(c *gin.Context) {1001 c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1002 })10031004 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 })10181019 r.GET("/someXML", func(c *gin.Context) {1020 c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1021 })10221023 r.GET("/someYAML", func(c *gin.Context) {1024 c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1025 })10261027 r.GET("/someTOML", func(c *gin.Context) {1028 c.TOML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1029 })10301031 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 })10431044 // Listen and serve on 0.0.0.0:80801045 r.Run(":8080")1046}1047```10481049#### SecureJSON10501051Using SecureJSON to prevent json hijacking. Default prepends `"while(1),"` to response body if the given struct is array values.10521053```go1054func main() {1055 r := gin.Default()10561057 // You can also use your own secure json prefix1058 // r.SecureJsonPrefix(")]}',\n")10591060 r.GET("/someJSON", func(c *gin.Context) {1061 names := []string{"lena", "austin", "foo"}10621063 // Will output : while(1);["lena","austin","foo"]1064 c.SecureJSON(http.StatusOK, names)1065 })10661067 // Listen and serve on 0.0.0.0:80801068 r.Run(":8080")1069}1070```10711072#### JSONP10731074Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists.10751076```go1077func main() {1078 r := gin.Default()10791080 r.GET("/JSONP", func(c *gin.Context) {1081 data := gin.H{1082 "foo": "bar",1083 }10841085 //callback is x1086 // Will output : x({\"foo\":\"bar\"})1087 c.JSONP(http.StatusOK, data)1088 })10891090 // Listen and serve on 0.0.0.0:80801091 r.Run(":8080")10921093 // client1094 // curl http://127.0.0.1:8080/JSONP?callback=x1095}1096```10971098#### AsciiJSON10991100Using AsciiJSON to Generates ASCII-only JSON with escaped non-ASCII characters.11011102```go1103func main() {1104 r := gin.Default()11051106 r.GET("/someJSON", func(c *gin.Context) {1107 data := gin.H{1108 "lang": "GO语言",1109 "tag": "<br>",1110 }11111112 // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}1113 c.AsciiJSON(http.StatusOK, data)1114 })11151116 // Listen and serve on 0.0.0.0:80801117 r.Run(":8080")1118}1119```11201121#### PureJSON11221123Normally, 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.1124This feature is unavailable in Go 1.6 and lower.11251126```go1127func main() {1128 r := gin.Default()11291130 // 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 })11361137 // 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 })11431144 // listen and serve on 0.0.0.0:80801145 r.Run(":8080")1146}1147```11481149### Serving static files11501151```go1152func 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```11631164### Serving data from file11651166```go1167func main() {1168 router := gin.Default()11691170 router.GET("/local/file", func(c *gin.Context) {1171 c.File("local/file.go")1172 })11731174 var fs http.FileSystem = // ...1175 router.GET("/fs/file", func(c *gin.Context) {1176 c.FileFromFS("fs/file.go", fs)1177 })1178}11791180```11811182### Serving data from reader11831184```go1185func 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 }11931194 reader := response.Body1195 defer reader.Close()1196 contentLength := response.ContentLength1197 contentType := response.Header.Get("Content-Type")11981199 extraHeaders := map[string]string{1200 "Content-Disposition": `attachment; filename="gopher.png"`,1201 }12021203 c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)1204 })1205 router.Run(":8080")1206}1207```12081209### HTML rendering12101211Using LoadHTMLGlob() or LoadHTMLFiles()12121213```go1214func 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```12261227templates/index.tmpl12281229```html1230<html>1231 <h1>1232 {{ .title }}1233 </h1>1234</html>1235```12361237Using templates with same name in different directories12381239```go1240func 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```12561257templates/posts/index.tmpl12581259```html1260{{ define "posts/index.tmpl" }}1261<html><h1>1262 {{ .title }}1263</h1>1264<p>Using posts/index.tmpl</p>1265</html>1266{{ end }}1267```12681269templates/users/index.tmpl12701271```html1272{{ define "users/index.tmpl" }}1273<html><h1>1274 {{ .title }}1275</h1>1276<p>Using users/index.tmpl</p>1277</html>1278{{ end }}1279```12801281#### Custom Template renderer12821283You can also use your own html template render12841285```go1286import "html/template"12871288func main() {1289 router := gin.Default()1290 html := template.Must(template.ParseFiles("file1", "file2"))1291 router.SetHTMLTemplate(html)1292 router.Run(":8080")1293}1294```12951296#### Custom Delimiters12971298You may use custom delims12991300```go1301 r := gin.Default()1302 r.Delims("{[{", "}]}")1303 r.LoadHTMLGlob("/path/to/templates")1304```13051306#### Custom Template Funcs13071308See the detail [example code](https://github.com/gin-gonic/examples/tree/master/template).13091310main.go13111312```go1313import (docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 1314–1317why, one step back1314 "fmt"1315 "html/template"1316 "net/http"1317 "time"docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
line 1318why, one step back1318docs: update markdown format (#3446)apriil15before adoptionc58e0d5
line 1319why, one step back1319 "github.com/gin-gonic/gin"docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
lines 1320–1322why, one step back1320)13211322func formatAsDate(t time.Time) string {docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 1323–1324why, one step back1323 year, month, day := t.Date()1324 return fmt.Sprintf("%d/%02d/%02d", year, month, day)docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
lines 1325–1327why, one step back1325}13261327func main() {docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 1328–1333why, one step back1328 router := gin.Default()1329 router.Delims("{[{", "}]}")1330 router.SetFuncMap(template.FuncMap{1331 "formatAsDate": formatAsDate,1332 })1333 router.LoadHTMLFiles("./testdata/template/raw.tmpl")docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
line 1334why, one step back1334docs: update markdown format (#3446)apriil15before adoptionc58e0d5
lines 1335–1339why, one step back1335 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 })docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
line 1340why, one step back1340docs: update markdown format (#3446)apriil15before adoptionc58e0d5
line 1341why, one step back1341 router.Run(":8080")docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
lines 1342–1963why, one step back1342}13431344```13451346raw.tmpl13471348```html1349Date: {[{.now | formatAsDate}]}1350```13511352Result:13531354```sh1355Date: 2017/07/011356```13571358### Multitemplate13591360Gin 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`.13611362### Redirects13631364Issuing a HTTP redirect is easy. Both internal and external locations are supported.13651366```go1367r.GET("/test", func(c *gin.Context) {1368 c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")1369})1370```13711372Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444)13731374```go1375r.POST("/test", func(c *gin.Context) {1376 c.Redirect(http.StatusFound, "/foo")1377})1378```13791380Issuing a Router redirect, use `HandleContext` like below.13811382``` go1383r.GET("/test", func(c *gin.Context) {1384 c.Request.URL.Path = "/test2"1385 r.HandleContext(c)1386})1387r.GET("/test2", func(c *gin.Context) {1388 c.JSON(http.StatusOK, gin.H{"hello": "world"})1389})1390```13911392### Custom Middleware13931394```go1395func Logger() gin.HandlerFunc {1396 return func(c *gin.Context) {1397 t := time.Now()13981399 // Set example variable1400 c.Set("example", "12345")14011402 // before request14031404 c.Next()14051406 // after request1407 latency := time.Since(t)1408 log.Print(latency)14091410 // access the status we are sending1411 status := c.Writer.Status()1412 log.Println(status)1413 }1414}14151416func main() {1417 r := gin.New()1418 r.Use(Logger())14191420 r.GET("/test", func(c *gin.Context) {1421 example := c.MustGet("example").(string)14221423 // it would print: "12345"1424 log.Println(example)1425 })14261427 // Listen and serve on 0.0.0.0:80801428 r.Run(":8080")1429}1430```14311432### Using BasicAuth() middleware14331434```go1435// simulate some private data1436var 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}14411442func main() {1443 r := gin.Default()14441445 // 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 }))14531454 // /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 })14651466 // Listen and serve on 0.0.0.0:80801467 r.Run(":8080")1468}1469```14701471### Goroutines inside a middleware14721473When 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.14741475```go1476func main() {1477 r := gin.Default()14781479 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)14851486 // note that you are using the copied context "cCp", IMPORTANT1487 log.Println("Done! in path " + cCp.Request.URL.Path)1488 }()1489 })14901491 r.GET("/long_sync", func(c *gin.Context) {1492 // simulate a long task with time.Sleep(). 5 seconds1493 time.Sleep(5 * time.Second)14941495 // 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 })14981499 // Listen and serve on 0.0.0.0:80801500 r.Run(":8080")1501}1502```15031504### Custom HTTP configuration15051506Use `http.ListenAndServe()` directly, like this:15071508```go1509func main() {1510 router := gin.Default()1511 http.ListenAndServe(":8080", router)1512}1513```15141515or15161517```go1518func main() {1519 router := gin.Default()15201521 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```15311532### Support Let's Encrypt15331534example for 1-line LetsEncrypt HTTPS servers.15351536```go1537package main15381539import (1540 "log"1541 "net/http"15421543 "github.com/gin-gonic/autotls"1544 "github.com/gin-gonic/gin"1545)15461547func main() {1548 r := gin.Default()15491550 // Ping handler1551 r.GET("/ping", func(c *gin.Context) {1552 c.String(http.StatusOK, "pong")1553 })15541555 log.Fatal(autotls.Run(r, "example1.com", "example2.com"))1556}1557```15581559example for custom autocert manager.15601561```go1562package main15631564import (1565 "log"1566 "net/http"15671568 "github.com/gin-gonic/autotls"1569 "github.com/gin-gonic/gin"1570 "golang.org/x/crypto/acme/autocert"1571)15721573func main() {1574 r := gin.Default()15751576 // Ping handler1577 r.GET("/ping", func(c *gin.Context) {1578 c.String(http.StatusOK, "pong")1579 })15801581 m := autocert.Manager{1582 Prompt: autocert.AcceptTOS,1583 HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),1584 Cache: autocert.DirCache("/var/www/.cache"),1585 }15861587 log.Fatal(autotls.RunWithManager(r, &m))1588}1589```15901591### Run multiple service using Gin15921593See the [question](https://github.com/gin-gonic/gin/issues/346) and try the following example:15941595```go1596package main15971598import (1599 "log"1600 "net/http"1601 "time"16021603 "github.com/gin-gonic/gin"1604 "golang.org/x/sync/errgroup"1605)16061607var (1608 g errgroup.Group1609)16101611func 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 })16231624 return e1625}16261627func 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 })16391640 return e1641}16421643func main() {1644 server01 := &http.Server{1645 Addr: ":8080",1646 Handler: router01(),1647 ReadTimeout: 5 * time.Second,1648 WriteTimeout: 10 * time.Second,1649 }16501651 server02 := &http.Server{1652 Addr: ":8081",1653 Handler: router02(),1654 ReadTimeout: 5 * time.Second,1655 WriteTimeout: 10 * time.Second,1656 }16571658 g.Go(func() error {1659 err := server01.ListenAndServe()1660 if err != nil && err != http.ErrServerClosed {1661 log.Fatal(err)1662 }1663 return err1664 })16651666 g.Go(func() error {1667 err := server02.ListenAndServe()1668 if err != nil && err != http.ErrServerClosed {1669 log.Fatal(err)1670 }1671 return err1672 })16731674 if err := g.Wait(); err != nil {1675 log.Fatal(err)1676 }1677}1678```16791680### Graceful shutdown or restart16811682There 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.16831684#### Third-party packages16851686We 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.16871688```go1689router := gin.Default()1690router.GET("/", handler)1691// [...]1692endless.ListenAndServe(":4242", router)1693```16941695Alternatives:16961697* [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.17001701#### Manually17021703In 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).17041705```go1706// +build go1.817071708package main17091710import (1711 "context"1712 "log"1713 "net/http"1714 "os"1715 "os/signal"1716 "syscall"1717 "time"17181719 "github.com/gin-gonic/gin"1720)17211722func 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 })17281729 srv := &http.Server{1730 Addr: ":8080",1731 Handler: router,1732 }17331734 // 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 }()17411742 // 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...")17511752 // 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()17561757 if err := srv.Shutdown(ctx); err != nil {1758 log.Fatal("Server forced to shutdown:", err)1759 }17601761 log.Println("Server exiting")1762}1763```17641765### Build a single binary with templates17661767You can build a server into a single binary containing templates by using the [embed](https://pkg.go.dev/embed) package.17681769```go1770package main17711772import (1773 "embed"1774 "html/template"1775 "net/http"17761777 "github.com/gin-gonic/gin"1778)17791780//go:embed assets/* templates/*1781var f embed.FS17821783func main() {1784 router := gin.Default()1785 templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl"))1786 router.SetHTMLTemplate(templ)17871788 // example: /public/assets/images/example.png1789 router.StaticFS("/public", http.FS(f))17901791 router.GET("/", func(c *gin.Context) {1792 c.HTML(http.StatusOK, "index.tmpl", gin.H{1793 "title": "Main website",1794 })1795 })17961797 router.GET("/foo", func(c *gin.Context) {1798 c.HTML(http.StatusOK, "bar.tmpl", gin.H{1799 "title": "Foo website",1800 })1801 })18021803 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 })18111812 router.Run(":8080")1813}1814```18151816See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary/example02` directory.18171818### Bind form-data request with custom struct18191820The follow example using custom struct:18211822```go1823type StructA struct {1824 FieldA string `form:"field_a"`1825}18261827type StructB struct {1828 NestedStruct StructA1829 FieldB string `form:"field_b"`1830}18311832type StructC struct {1833 NestedStructPointer *StructA1834 FieldC string `form:"field_c"`1835}18361837type StructD struct {1838 NestedAnonyStruct struct {1839 FieldX string `form:"field_x"`1840 }1841 FieldD string `form:"field_d"`1842}18431844func 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}18521853func 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}18611862func 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}18701871func main() {1872 r := gin.Default()1873 r.GET("/getb", GetDataB)1874 r.GET("/getc", GetDataC)1875 r.GET("/getd", GetDataD)18761877 r.Run()1878}1879```18801881Using the command `curl` command result:18821883```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```18911892### Try to bind body into different structs18931894The normal methods for binding request body consumes `c.Request.Body` and they1895cannot be called multiple times.18961897```go1898type formA struct {1899 Foo string `json:"foo" xml:"foo" binding:"required"`1900}19011902type formB struct {1903 Bar string `json:"bar" xml:"bar" binding:"required"`1904}19051906func 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```19201921For this, you can use `c.ShouldBindBodyWith`.19221923```go1924func 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```194119421. `c.ShouldBindBodyWith` stores body into the context before binding. This has1943a slight impact to performance, so you should not use this method if you are1944enough to call binding at once.19452. This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`,1946`ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`,1947can be called by `c.ShouldBind()` multiple times without any damage to1948performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)).19491950### Bind form-data request with custom struct and custom tag19511952```go1953const (1954 customerTag = "url"1955 defaultMemory = 32 << 201956)19571958type customerBinding struct {}19591960func (customerBinding) Name() string {1961 return "form"1962}1963chore: support min go version 1.18 (#3511)thinkeroubefore adoption1e1f0b1
line 1964why, one step back1964func (customerBinding) Bind(req *http.Request, obj any) error {docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
lines 1965–1978why, one step back1965 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}1978chore: support min go version 1.18 (#3511)thinkeroubefore adoption1e1f0b1
line 1979why, one step back1979func validate(obj any) error {docs(readme): move more example to docs/doc.md (#3449)thinkeroubefore adoption82e1c53
lines 1980–2101why, one step back1980 if binding.Validator == nil {1981 return nil1982 }1983 return binding.Validator.ValidateStruct(obj)1984}19851986// Now we can do this!!!1987// FormA is an external type that we can't modify it's tag1988type FormA struct {1989 FieldA string `url:"field_a"`1990}19911992func 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 ...The first 2,000 of 2,243 lines.