Skip to content
Myr

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

2 files+2316 added−2272 removed

added:docs/doc.md+2246 added
1# 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.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 }))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() {453 // Disable Console Color, you don't need console color when writing the logs to file.454 gin.DisableConsoleColor()455456 // Logging to a file.457 f, _ := os.Create("gin.log")458 gin.DefaultWriter = io.MultiWriter(f)459460 // 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)462463 router := gin.Default()464 router.GET("/ping", func(c *gin.Context) {465 c.String(http.StatusOK, "pong")466 })467468    router.Run(":8080")469}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() {519 // Disable log's color520 gin.DisableConsoleColor()521522 // Creates a gin router with default middleware:523 // logger and recovery (crash-free) middleware524 router := gin.Default()525526 router.GET("/ping", func(c *gin.Context) {527 c.String(http.StatusOK, "pong")528 })529530 router.Run(":8080")531}532```533534Always colorize logs:535536```go537func main() {538 // Force log's color539 gin.ForceConsoleColor()540541 // Creates a gin router with default middleware:542 // logger and recovery (crash-free) middleware543 router := gin.Default()544545 router.GET("/ping", func(c *gin.Context) {546 c.String(http.StatusOK, "pong")547 })548549 router.Run(":8080")550}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 {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}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#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 }814815 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()998999 // 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 })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 (1314 "fmt"1315 "html/template"1316 "net/http"1317 "time"13181319 "github.com/gin-gonic/gin"1320)13211322func formatAsDate(t time.Time) string {1323 year, month, day := t.Date()1324 return fmt.Sprintf("%d/%02d/%02d", year, month, day)1325}13261327func main() {1328 router := gin.Default()1329 router.Delims("{[{", "}]}")1330 router.SetFuncMap(template.FuncMap{1331 "formatAsDate": formatAsDate,1332 })1333 router.LoadHTMLFiles("./testdata/template/raw.tmpl")13341335 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 })13401341 router.Run(":8080")1342}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}19631964func (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}19781979func validate(obj interface{}) error {1980 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 ...2001 }2002}2003```20042005### http2 server push20062007http.Pusher is supported only **go1.8+**. See the [golang blog](https://go.dev/blog/h2push) for detail information.20082009```go2010package main20112012import (2013 "html/template"2014 "log"2015 "net/http"20162017 "github.com/gin-gonic/gin"2018)20192020var 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`))20312032func main() {2033 r := gin.Default()2034 r.Static("/assets", "./assets")2035 r.SetHTMLTemplate(html)20362037 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 })20482049 // Listen and Server in https://127.0.0.1:80802050 r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")2051}2052```20532054### Define format for the log of routes20552056The default log of routes is:20572058```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```20632064If 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`.2065In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs.20662067```go2068import (2069 "log"2070 "net/http"20712072 "github.com/gin-gonic/gin"2073)20742075func 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 }20802081 r.POST("/foo", func(c *gin.Context) {2082 c.JSON(http.StatusOK, "foo")2083 })20842085 r.GET("/bar", func(c *gin.Context) {2086 c.JSON(http.StatusOK, "bar")2087 })20882089 r.GET("/status", func(c *gin.Context) {2090 c.JSON(http.StatusOK, "ok")2091 })20922093 // Listen and Server in http://0.0.0.0:80802094 r.Run()2095}2096```20972098### Set and get a cookie20992100```go2101import (2102 "fmt"21032104 "github.com/gin-gonic/gin"2105)21062107func main() {21082109 router := gin.Default()21102111 router.GET("/cookie", func(c *gin.Context) {21122113 cookie, err := c.Cookie("gin_cookie")21142115 if err != nil {2116 cookie = "NotSet"2117 c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)2118 }21192120 fmt.Printf("Cookie value: %s \n", cookie)2121 })21222123 router.Run()2124}2125```21262127## Don't trust all proxies21282129Gin lets you specify which headers to hold the real client IP (if any),2130as well as specifying which proxies (or direct clients) you trust to2131specify one of these headers.21322133Use function `SetTrustedProxies()` on your `gin.Engine` to specify network addresses2134or network CIDRs from where clients which their request headers related to client2135IP can be trusted. They can be IPv4 addresses, IPv4 CIDRs, IPv6 addresses or2136IPv6 CIDRs.21372138**Attention:** Gin trust all proxies by default if you don't specify a trusted 2139proxy using the function above, **this is NOT safe**. At the same time, if you don't2140use any proxy, you can disable this feature by using `Engine.SetTrustedProxies(nil)`,2141then `Context.ClientIP()` will return the remote address directly to avoid some2142unnecessary computation.21432144```go2145import (2146 "fmt"21472148 "github.com/gin-gonic/gin"2149)21502151func main() {21522153 router := gin.Default()2154 router.SetTrustedProxies([]string{"192.168.1.2"})21552156 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```21662167**Notice:** If you are using a CDN service, you can set the `Engine.TrustedPlatform`2168to skip TrustedProxies check, it has a higher priority than TrustedProxies. 2169Look at the example below:21702171```go2172import (2173 "fmt"21742175 "github.com/gin-gonic/gin"2176)21772178func main() {21792180 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"21862187 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```21952196## Testing21972198The `net/http/httptest` package is preferable way for HTTP testing.21992200```go2201package main22022203import (2204 "net/http"22052206 "github.com/gin-gonic/gin"2207)22082209func 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}22162217func main() {2218 r := setupRouter()2219 r.Run(":8080")2220}2221```22222223Test for code example above:22242225```go2226package main22272228import (2229 "net/http"2230 "net/http/httptest"2231 "testing"22322233 "github.com/stretchr/testify/assert"2234)22352236func TestPingRoute(t *testing.T) {2237 router := setupRouter()22382239 w := httptest.NewRecorder()2240 req, _ := http.NewRequest(http.MethodGet, "/ping", nil)2241 router.ServeHTTP(w, req)22422243 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 lines
11[![Open Source Helpers](https://www.codetriage.com/gin-gonic/gin/badges/users.svg)](https://www.codetriage.com/gin-gonic/gin)12[![Release](https://img.shields.io/github/release/gin-gonic/gin.svg?style=flat-square)](https://github.com/gin-gonic/gin/releases)13[![TODOs](https://badgen.net/https/api.tickgit.com/badgen/github.com/gin-gonic/gin)](https://www.tickgit.com/browse?repo=github.com/gin-gonic/gin)1415Gin 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.15Gin 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.1617## Contents17**The key features of Gin are:**1819- [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- Extendable2886## Installation2988To install Gin package, you need to install Go and set your Go workspace first.30## Getting started31901. 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### Prerequisites3392```sh93go 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).35962. Import it in your code:36### Getting Gin3738With [Go module](https://github.com/golang/go/wiki/Modules) support, simply add the following import3998```go40```41import "github.com/gin-gonic/gin"42```431023. (Optional) Import `net/http`. This is required for example if using constants such as `http.StatusOK`.44to your code, and then `go [build|run|test]` will automatically fetch the necessary dependencies.45104```go105import "net/http"106```46Otherwise, run the following Go command to install the `gin` package:47108## Quick start10948```sh111# assume the following codes in example.go file112$ cat example.go49$ go get -u github.com/gin-gonic/gin50```5152### Running Gin5354First you need to import Gin package for using Gin, one simplest example likes the follow `example.go`:5556```go57package main5859import (
12 unmodified lines
72 r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")73}74```7576And use the Go command to run the demo:7778```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```82140## Benchmarks83### Learn more examples84142Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter)85#### Quick Start86144[See all benchmarks](/BENCHMARKS.md)87Learn and practice more examples, please read the [Gin Quick Start](docs/doc.md) which includes API examples and builds tag.8889#### Examples9091A number of ready-to-run examples demonstrating various use cases of Gin on the [Gin examples](https://github.com/gin-gonic/examples) repository.929394## Documentation9596See [API documentation and descriptions](https://godoc.org/github.com/gin-gonic/gin) for package.9798All documentation is available on the Gin website.99100- [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/)108109### Articles about Gin110111A curated list of awesome Gin framework.112113- [Tutorial: Developing a RESTful API with Go and Gin](https://go.dev/doc/tutorial/web-service-gin)114115## Benchmarks116117Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter), [see all benchmarks details](/BENCHMARKS.md).118119| 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 lines
153- (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 better156184## Gin v1. stable157186- [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## Middlewares159192## Build with json replacement160You can find many useful Gin middlewares at [gin-contrib](https://github.com/gin-contrib).161194Gin uses `encoding/json` as default json package but you can change it by build from other tags.162196[jsoniter](https://github.com/json-iterator/go)197198```sh199go build -tags=jsoniter .200```201202[go-json](https://github.com/goccy/go-json)203204```sh205go build -tags=go_json .206```207208[sonic](https://github.com/bytedance/sonic) (you have to ensure that your cpu support avx instruction.)209210```sh211$ go build -tags="sonic avx" .212```213214## Build without `MsgPack` rendering feature215216Gin enables `MsgPack` rendering feature by default. But you can disable this feature by specifying `nomsgpack` build tag.217218```sh219go build -tags=nomsgpack .220```221222This is useful to reduce the binary size of executable files. See the [detail information](https://github.com/gin-gonic/gin/pull/1852).223224## API Examples225226You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples).227228### Using GET, POST, PUT, PATCH, DELETE and OPTIONS229230```go231func main() {232 // Creates a gin router with default middleware:233 // logger and recovery (crash-free) middleware234 router := gin.Default()235236 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)243244 // 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```250251### Parameters in path252253```go254func main() {255 router := gin.Default()256257 // 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 })262263 // 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 })271272 // 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 })277278 // 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 })284285 router.Run(":8080")286}287```288289### Querystring parameters290291```go292func main() {293 router := gin.Default()294295 // 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")300301 c.String(http.StatusOK, "Hello %s %s", firstname, lastname)302 })303 router.Run(":8080")304}305```306307### Multipart/Urlencoded Form308309```go310func main() {311 router := gin.Default()312313 router.POST("/form_post", func(c *gin.Context) {314 message := c.PostForm("message")315 nick := c.DefaultPostForm("nick", "anonymous")316317 c.JSON(http.StatusOK, gin.H{318 "status": "posted",319 "message": message,320 "nick": nick,321 })322 })323 router.Run(":8080")324}325```326327### Another example: query + post form328329```sh330POST /post?id=1234&page=1 HTTP/1.1331Content-Type: application/x-www-form-urlencoded332333name=manu&message=this_is_great334```335336```go337func main() {338 router := gin.Default()339340 router.POST("/post", func(c *gin.Context) {341342 id := c.Query("id")343 page := c.DefaultQuery("page", "0")344 name := c.PostForm("name")345 message := c.PostForm("message")346347 fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)348 })349 router.Run(":8080")350}351```352353```sh354id: 1234; page: 1; name: manu; message: this_is_great355```356357### Map as querystring or postform parameters358359```sh360POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1361Content-Type: application/x-www-form-urlencoded362363names[first]=thinkerou&names[second]=tianou364```365366```go367func main() {368 router := gin.Default()369370 router.POST("/post", func(c *gin.Context) {371372 ids := c.QueryMap("ids")373 names := c.PostFormMap("names")374375 fmt.Printf("ids: %v; names: %v", ids, names)376 })377 router.Run(":8080")378}379```380381```sh382ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou]383```384385### Upload files386387#### Single file388389References 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).390391`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)392393> 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.394395```go396func main() {397 router := gin.Default()398 // Set a lower memory limit for multipart forms (default is 32 MiB)399 router.MaxMultipartMemory = 8 << 20 // 8 MiB400 router.POST("/upload", func(c *gin.Context) {401 // Single file402 file, _ := c.FormFile("file")403 log.Println(file.Filename)404405 // Upload the file to specific dst.406 c.SaveUploadedFile(file, dst)407408 c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))409 })410 router.Run(":8080")411}412```413414How to `curl`:415416```bash417curl -X POST http://localhost:8080/upload \418 -F "file=@/Users/appleboy/test.zip" \419 -H "Content-Type: multipart/form-data"420```421422#### Multiple files423424See the detail [example code](https://github.com/gin-gonic/examples/tree/master/upload-file/multiple).425426```go427func 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[]"]435436 for _, file := range files {437 log.Println(file.Filename)438439 // 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```447448How to `curl`:449450```bash451curl -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```456457### Grouping routes458459```go460func main() {461 router := gin.Default()462463 // Simple group: v1464 v1 := router.Group("/v1")465 {466 v1.POST("/login", loginEndpoint)467 v1.POST("/submit", submitEndpoint)468 v1.POST("/read", readEndpoint)469 }470471 // Simple group: v2472 v2 := router.Group("/v2")473 {474 v2.POST("/login", loginEndpoint)475 v2.POST("/submit", submitEndpoint)476 v2.POST("/read", readEndpoint)477 }478479 router.Run(":8080")480}481```482483### Blank Gin without middleware by default484485Use486487```go488r := gin.New()489```490491instead of492493```go494// Default With the Logger and Recovery middleware already attached495r := gin.Default()496```497498### Using middleware499500```go501func main() {502 // Creates a router without any middleware by default503 r := gin.New()504505 // 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())509510 // Recovery middleware recovers from any panics and writes a 500 if there was one.511 r.Use(gin.Recovery())512513 // Per route middleware, you can add as many as you desire.514 r.GET("/benchmark", MyBenchLogger(), benchEndpoint)515516 // 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)527528 // nested group529 testing := authorized.Group("testing")530 // visit 0.0.0.0:8080/testing/analytics531 testing.GET("/analytics", analyticsEndpoint)532 }533534 // Listen and serve on 0.0.0.0:8080535 r.Run(":8080")536}537```538539### Custom Recovery behavior540541```go542func main() {543 // Creates a router without any middleware by default544 r := gin.New()545546 // 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())550551 // 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 }))558559 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 })563564 r.GET("/", func(c *gin.Context) {565 c.String(http.StatusOK, "ohai")566 })567568 // Listen and serve on 0.0.0.0:8080569 r.Run(":8080")570}571```572573### How to write log file574575```go576func main() {577 // Disable Console Color, you don't need console color when writing the logs to file.578 gin.DisableConsoleColor()579580 // Logging to a file.581 f, _ := os.Create("gin.log")582 gin.DefaultWriter = io.MultiWriter(f)583584 // 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)586587 router := gin.Default()588 router.GET("/ping", func(c *gin.Context) {589 c.String(http.StatusOK, "pong")590 })591592    router.Run(":8080")593}594```595596### Custom Log Format597598```go599func main() {600 router := gin.New()601602 // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter603 // By default gin.DefaultWriter = os.Stdout604 router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {605606 // 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())620621 router.GET("/ping", func(c *gin.Context) {622 c.String(http.StatusOK, "pong")623 })624625 router.Run(":8080")626}627```628629Sample Output630631```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```634635### Controlling Log output coloring636637By default, logs output on console should be colorized depending on the detected TTY.638639Never colorize logs:640641```go642func main() {643 // Disable log's color644 gin.DisableConsoleColor()645646 // Creates a gin router with default middleware:647 // logger and recovery (crash-free) middleware648 router := gin.Default()649650 router.GET("/ping", func(c *gin.Context) {651 c.String(http.StatusOK, "pong")652 })653654 router.Run(":8080")655}656```657658Always colorize logs:659660```go661func main() {662 // Force log's color663 gin.ForceConsoleColor()664665 // Creates a gin router with default middleware:666 // logger and recovery (crash-free) middleware667 router := gin.Default()668669 router.GET("/ping", func(c *gin.Context) {670 c.String(http.StatusOK, "pong")671 })672673 router.Run(":8080")674}675```676677### Model binding and validation678679To 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).680681Gin 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).682683Note 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"`.684685Also, Gin provides two sets of methods for binding:686687- **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.693694When 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`.695696You 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.697698```go699// Binding from JSON700type 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}704705func main() {706 router := gin.Default()707708 // 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 }715716 if json.User != "manu" || json.Password != "123" {717 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})718 return719 }720721 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})722 })723724 // 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 }736737 if xml.User != "manu" || xml.Password != "123" {738 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})739 return740 }741742 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})743 })744745 // 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 }753754 if form.User != "manu" || form.Password != "123" {755 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})756 return757 }758759 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})760 })761762 // Listen and serve on 0.0.0.0:8080763 router.Run(":8080")764}765```766767Sample request768769```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```789790Skip 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.791792### Custom Validators793794It is also possible to register custom validators. See the [example code](https://github.com/gin-gonic/examples/tree/master/custom-validation/server.go).795796```go797package main798799import (800 "net/http"801 "time"802803 "github.com/gin-gonic/gin"804 "github.com/gin-gonic/gin/binding"805 "github.com/go-playground/validator/v10"806)807808// Booking contains binded and validated data.809type 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}813814var 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}824825func main() {826 route := gin.Default()827828 if v, ok := binding.Validator.Engine().(*validator.Validate); ok {829 v.RegisterValidation("bookabledate", bookableDate)830 }831832 route.GET("/bookable", getBookable)833 route.Run(":8085")834}835836func 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```845846```console847$ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17"848{"message":"Booking dates are valid!"}849850$ 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"}852853$ 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```856857[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way.858See the [struct-lvl-validation example](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) to learn more.859860### Only Bind Query String861862`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).863864```go865package main866867import (868 "log"869 "net/http"870871 "github.com/gin-gonic/gin"872)873874type Person struct {875 Name string `form:"name"`876 Address string `form:"address"`877}878879func main() {880 route := gin.Default()881 route.Any("/testing", startPage)882 route.Run(":8085")883}884885func 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}894895```896897### Bind Query String or Post Data898899See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292).900901```go902package main903904import (905 "log"906 "net/http"907 "time"908909 "github.com/gin-gonic/gin"910)911912type 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}919920func main() {921 route := gin.Default()922 route.GET("/testing", startPage)923 route.Run(":8085")924}925926func 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 }938939 c.String(http.StatusOK, "Success")940}941```942943Test it with:944945```sh946curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"947```948949### Bind Uri950951See the [detail information](https://github.com/gin-gonic/gin/issues/846).952953```go954package main955956import (957 "net/http"958959 "github.com/gin-gonic/gin"960)961962type Person struct {963 ID string `uri:"id" binding:"required,uuid"`964 Name string `uri:"name" binding:"required"`965}966967func 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```980981Test it with:982983```sh984curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3985curl -v localhost:8088/thinkerou/not-uuid986```987988### Bind Header989990```go991package main992993import (994 "fmt"995 "net/http"996997 "github.com/gin-gonic/gin"998)9991000type testHeader struct {1001 Rate int `header:"Rate"`1002 Domain string `header:"Domain"`1003}10041005func main() {1006 r := gin.Default()1007 r.GET("/", func(c *gin.Context) {1008 h := testHeader{}10091010 if err := c.ShouldBindHeader(&h); err != nil {1011 c.JSON(http.StatusOK, err)1012 }10131014 fmt.Printf("%#v\n", h)1015 c.JSON(http.StatusOK, gin.H{"Rate": h.Rate, "Domain": h.Domain})1016 })10171018 r.Run()10191020// client1021// curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/1022// output1023// {"Domain":"music","Rate":300}1024}1025```10261027### Bind HTML checkboxes10281029See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)10301031main.go10321033```go1034...10351036type myForm struct {1037 Colors []string `form:"colors[]"`1038}10391040...10411042func formHandler(c *gin.Context) {1043 var fakeForm myForm1044 c.ShouldBind(&fakeForm)1045 c.JSON(http.StatusOK, gin.H{"color": fakeForm.Colors})1046}10471048...10491050```10511052form.html10531054```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```10661067result:10681069```json1070{"color":["red","green","blue"]}1071```10721073### Multipart/Urlencoded binding10741075```go1076type ProfileForm struct {1077 Name string `form:"name" binding:"required"`1078 Avatar *multipart.FileHeader `form:"avatar" binding:"required"`10791080 // or for multiple files1081 // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"`1082}10831084func 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 }10961097 err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename)1098 if err != nil {1099 c.String(http.StatusInternalServerError, "unknown error")1100 return1101 }11021103 // db.Save(&form)11041105 c.String(http.StatusOK, "ok")1106 })1107 router.Run(":8080")1108}1109```11101111Test it with:11121113```sh1114curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile1115```11161117### XML, JSON, YAML, TOML and ProtoBuf rendering11181119```go1120func main() {1121 r := gin.Default()11221123 // 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 })11271128 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 })11421143 r.GET("/someXML", func(c *gin.Context) {1144 c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1145 })11461147 r.GET("/someYAML", func(c *gin.Context) {1148 c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1149 })11501151 r.GET("/someTOML", func(c *gin.Context) {1152 c.TOML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1153 })11541155 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 })11671168 // Listen and serve on 0.0.0.0:80801169 r.Run(":8080")1170}1171```11721173#### SecureJSON11741175Using SecureJSON to prevent json hijacking. Default prepends `"while(1),"` to response body if the given struct is array values.11761177```go1178func main() {1179 r := gin.Default()11801181 // You can also use your own secure json prefix1182 // r.SecureJsonPrefix(")]}',\n")11831184 r.GET("/someJSON", func(c *gin.Context) {1185 names := []string{"lena", "austin", "foo"}11861187 // Will output : while(1);["lena","austin","foo"]1188 c.SecureJSON(http.StatusOK, names)1189 })11901191 // Listen and serve on 0.0.0.0:80801192 r.Run(":8080")1193}1194```11951196#### JSONP11971198Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists.11991200```go1201func main() {1202 r := gin.Default()12031204 r.GET("/JSONP", func(c *gin.Context) {1205 data := gin.H{1206 "foo": "bar",1207 }12081209 //callback is x1210 // Will output : x({\"foo\":\"bar\"})1211 c.JSONP(http.StatusOK, data)1212 })12131214 // Listen and serve on 0.0.0.0:80801215 r.Run(":8080")12161217 // client1218 // curl http://127.0.0.1:8080/JSONP?callback=x1219}1220```12211222#### AsciiJSON12231224Using AsciiJSON to Generates ASCII-only JSON with escaped non-ASCII characters.12251226```go1227func main() {1228 r := gin.Default()12291230 r.GET("/someJSON", func(c *gin.Context) {1231 data := gin.H{1232 "lang": "GO语言",1233 "tag": "<br>",1234 }12351236 // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}1237 c.AsciiJSON(http.StatusOK, data)1238 })12391240 // Listen and serve on 0.0.0.0:80801241 r.Run(":8080")1242}1243```12441245#### PureJSON12461247Normally, 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.1248This feature is unavailable in Go 1.6 and lower.12491250```go1251func main() {1252 r := gin.Default()12531254 // 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 })12601261 // 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 })12671268 // listen and serve on 0.0.0.0:80801269 r.Run(":8080")1270}1271```12721273### Serving static files12741275```go1276func 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```12871288### Serving data from file12891290```go1291func main() {1292 router := gin.Default()12931294 router.GET("/local/file", func(c *gin.Context) {1295 c.File("local/file.go")1296 })12971298 var fs http.FileSystem = // ...1299 router.GET("/fs/file", func(c *gin.Context) {1300 c.FileFromFS("fs/file.go", fs)1301 })1302}13031304```13051306### Serving data from reader13071308```go1309func 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 }13171318 reader := response.Body1319 defer reader.Close()1320 contentLength := response.ContentLength1321 contentType := response.Header.Get("Content-Type")13221323 extraHeaders := map[string]string{1324 "Content-Disposition": `attachment; filename="gopher.png"`,1325 }13261327 c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)1328 })1329 router.Run(":8080")1330}1331```13321333### HTML rendering13341335Using LoadHTMLGlob() or LoadHTMLFiles()13361337```go1338func 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```13501351templates/index.tmpl13521353```html1354<html>1355 <h1>1356 {{ .title }}1357 </h1>1358</html>1359```13601361Using templates with same name in different directories13621363```go1364func 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```13801381templates/posts/index.tmpl13821383```html1384{{ define "posts/index.tmpl" }}1385<html><h1>1386 {{ .title }}1387</h1>1388<p>Using posts/index.tmpl</p>1389</html>1390{{ end }}1391```13921393templates/users/index.tmpl13941395```html1396{{ define "users/index.tmpl" }}1397<html><h1>1398 {{ .title }}1399</h1>1400<p>Using users/index.tmpl</p>1401</html>1402{{ end }}1403```14041405#### Custom Template renderer14061407You can also use your own html template render14081409```go1410import "html/template"14111412func main() {1413 router := gin.Default()1414 html := template.Must(template.ParseFiles("file1", "file2"))1415 router.SetHTMLTemplate(html)1416 router.Run(":8080")1417}1418```14191420#### Custom Delimiters14211422You may use custom delims14231424```go1425 r := gin.Default()1426 r.Delims("{[{", "}]}")1427 r.LoadHTMLGlob("/path/to/templates")1428```14291430#### Custom Template Funcs14311432See the detail [example code](https://github.com/gin-gonic/examples/tree/master/template).14331434main.go14351436```go1437import (1438 "fmt"1439 "html/template"1440 "net/http"1441 "time"14421443 "github.com/gin-gonic/gin"1444)14451446func formatAsDate(t time.Time) string {1447 year, month, day := t.Date()1448 return fmt.Sprintf("%d/%02d/%02d", year, month, day)1449}14501451func main() {1452 router := gin.Default()1453 router.Delims("{[{", "}]}")1454 router.SetFuncMap(template.FuncMap{1455 "formatAsDate": formatAsDate,1456 })1457 router.LoadHTMLFiles("./testdata/template/raw.tmpl")14581459 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 })14641465 router.Run(":8080")1466}14671468```14691470raw.tmpl14711472```html1473Date: {[{.now | formatAsDate}]}1474```14751476Result:14771478```sh1479Date: 2017/07/011480```14811482### Multitemplate14831484Gin 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`.14851486### Redirects14871488Issuing a HTTP redirect is easy. Both internal and external locations are supported.14891490```go1491r.GET("/test", func(c *gin.Context) {1492 c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")1493})1494```14951496Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444)14971498```go1499r.POST("/test", func(c *gin.Context) {1500 c.Redirect(http.StatusFound, "/foo")1501})1502```15031504Issuing a Router redirect, use `HandleContext` like below.15051506``` go1507r.GET("/test", func(c *gin.Context) {1508 c.Request.URL.Path = "/test2"1509 r.HandleContext(c)1510})1511r.GET("/test2", func(c *gin.Context) {1512 c.JSON(http.StatusOK, gin.H{"hello": "world"})1513})1514```15151516### Custom Middleware15171518```go1519func Logger() gin.HandlerFunc {1520 return func(c *gin.Context) {1521 t := time.Now()15221523 // Set example variable1524 c.Set("example", "12345")15251526 // before request15271528 c.Next()15291530 // after request1531 latency := time.Since(t)1532 log.Print(latency)15331534 // access the status we are sending1535 status := c.Writer.Status()1536 log.Println(status)1537 }1538}15391540func main() {1541 r := gin.New()1542 r.Use(Logger())15431544 r.GET("/test", func(c *gin.Context) {1545 example := c.MustGet("example").(string)15461547 // it would print: "12345"1548 log.Println(example)1549 })15501551 // Listen and serve on 0.0.0.0:80801552 r.Run(":8080")1553}1554```15551556### Using BasicAuth() middleware15571558```go1559// simulate some private data1560var 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}15651566func main() {1567 r := gin.Default()15681569 // 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 }))15771578 // /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 })15891590 // Listen and serve on 0.0.0.0:80801591 r.Run(":8080")1592}1593```15941595### Goroutines inside a middleware15961597When 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.15981599```go1600func main() {1601 r := gin.Default()16021603 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)16091610 // note that you are using the copied context "cCp", IMPORTANT1611 log.Println("Done! in path " + cCp.Request.URL.Path)1612 }()1613 })16141615 r.GET("/long_sync", func(c *gin.Context) {1616 // simulate a long task with time.Sleep(). 5 seconds1617 time.Sleep(5 * time.Second)16181619 // 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 })16221623 // Listen and serve on 0.0.0.0:80801624 r.Run(":8080")1625}1626```16271628### Custom HTTP configuration16291630Use `http.ListenAndServe()` directly, like this:16311632```go1633func main() {1634 router := gin.Default()1635 http.ListenAndServe(":8080", router)1636}1637```16381639or16401641```go1642func main() {1643 router := gin.Default()16441645 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```16551656### Support Let's Encrypt16571658example for 1-line LetsEncrypt HTTPS servers.16591660```go1661package main16621663import (1664 "log"1665 "net/http"16661667 "github.com/gin-gonic/autotls"1668 "github.com/gin-gonic/gin"1669)16701671func main() {1672 r := gin.Default()16731674 // Ping handler1675 r.GET("/ping", func(c *gin.Context) {1676 c.String(http.StatusOK, "pong")1677 })16781679 log.Fatal(autotls.Run(r, "example1.com", "example2.com"))1680}1681```16821683example for custom autocert manager.16841685```go1686package main16871688import (1689 "log"1690 "net/http"16911692 "github.com/gin-gonic/autotls"1693 "github.com/gin-gonic/gin"1694 "golang.org/x/crypto/acme/autocert"1695)16961697func main() {1698 r := gin.Default()16991700 // Ping handler1701 r.GET("/ping", func(c *gin.Context) {1702 c.String(http.StatusOK, "pong")1703 })17041705 m := autocert.Manager{1706 Prompt: autocert.AcceptTOS,1707 HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),1708 Cache: autocert.DirCache("/var/www/.cache"),1709 }17101711 log.Fatal(autotls.RunWithManager(r, &m))1712}1713```17141715### Run multiple service using Gin17161717See the [question](https://github.com/gin-gonic/gin/issues/346) and try the following example:17181719```go1720package main17211722import (1723 "log"1724 "net/http"1725 "time"17261727 "github.com/gin-gonic/gin"1728 "golang.org/x/sync/errgroup"1729)17301731var (1732 g errgroup.Group1733)17341735func 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 })17471748 return e1749}17501751func 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 })17631764 return e1765}17661767func main() {1768 server01 := &http.Server{1769 Addr: ":8080",1770 Handler: router01(),1771 ReadTimeout: 5 * time.Second,1772 WriteTimeout: 10 * time.Second,1773 }17741775 server02 := &http.Server{1776 Addr: ":8081",1777 Handler: router02(),1778 ReadTimeout: 5 * time.Second,1779 WriteTimeout: 10 * time.Second,1780 }17811782 g.Go(func() error {1783 err := server01.ListenAndServe()1784 if err != nil && err != http.ErrServerClosed {1785 log.Fatal(err)1786 }1787 return err1788 })17891790 g.Go(func() error {1791 err := server02.ListenAndServe()1792 if err != nil && err != http.ErrServerClosed {1793 log.Fatal(err)1794 }1795 return err1796 })17971798 if err := g.Wait(); err != nil {1799 log.Fatal(err)1800 }1801}1802```18031804### Graceful shutdown or restart18051806There 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.18071808#### Third-party packages18091810We 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.18111812```go1813router := gin.Default()1814router.GET("/", handler)1815// [...]1816endless.ListenAndServe(":4242", router)1817```18181819Alternatives:18201821* [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.18241825#### Manually18261827In 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).18281829```go1830// +build go1.818311832package main18331834import (1835 "context"1836 "log"1837 "net/http"1838 "os"1839 "os/signal"1840 "syscall"1841 "time"18421843 "github.com/gin-gonic/gin"1844)18451846func 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 })18521853 srv := &http.Server{1854 Addr: ":8080",1855 Handler: router,1856 }18571858 // 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 }()18651866 // 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...")18751876 // 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()18801881 if err := srv.Shutdown(ctx); err != nil {1882 log.Fatal("Server forced to shutdown:", err)1883 }18841885 log.Println("Server exiting")1886}1887```18881889### Build a single binary with templates18901891You can build a server into a single binary containing templates by using the [embed](https://pkg.go.dev/embed) package.18921893```go1894package main18951896import (1897 "embed"1898 "html/template"1899 "net/http"19001901 "github.com/gin-gonic/gin"1902)19031904//go:embed assets/* templates/*1905var f embed.FS19061907func main() {1908 router := gin.Default()1909 templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl"))1910 router.SetHTMLTemplate(templ)19111912 // example: /public/assets/images/example.png1913 router.StaticFS("/public", http.FS(f))19141915 router.GET("/", func(c *gin.Context) {1916 c.HTML(http.StatusOK, "index.tmpl", gin.H{1917 "title": "Main website",1918 })1919 })19201921 router.GET("/foo", func(c *gin.Context) {1922 c.HTML(http.StatusOK, "bar.tmpl", gin.H{1923 "title": "Foo website",1924 })1925 })19261927 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 })19351936 router.Run(":8080")1937}1938```19391940See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary/example02` directory.19411942### Bind form-data request with custom struct19431944The follow example using custom struct:19451946```go1947type StructA struct {1948 FieldA string `form:"field_a"`1949}19501951type StructB struct {1952 NestedStruct StructA1953 FieldB string `form:"field_b"`1954}19551956type StructC struct {1957 NestedStructPointer *StructA1958 FieldC string `form:"field_c"`1959}19601961type StructD struct {1962 NestedAnonyStruct struct {1963 FieldX string `form:"field_x"`1964 }1965 FieldD string `form:"field_d"`1966}19671968func 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}19761977func 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}19851986func 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}19941995func main() {1996 r := gin.Default()1997 r.GET("/getb", GetDataB)1998 r.GET("/getc", GetDataC)1999 r.GET("/getd", GetDataD)20002001 r.Run()2002}2003```20042005Using the command `curl` command result:20062007```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```20152016### Try to bind body into different structs20172018The normal methods for binding request body consumes `c.Request.Body` and they2019cannot be called multiple times.20202021```go2022type formA struct {2023 Foo string `json:"foo" xml:"foo" binding:"required"`2024}20252026type formB struct {2027 Bar string `json:"bar" xml:"bar" binding:"required"`2028}20292030func 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```20442045For this, you can use `c.ShouldBindBodyWith`.20462047```go2048func 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```206520661. `c.ShouldBindBodyWith` stores body into the context before binding. This has2067a slight impact to performance, so you should not use this method if you are2068enough to call binding at once.20692. This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`,2070`ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`,2071can be called by `c.ShouldBind()` multiple times without any damage to2072performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)).20732074### Bind form-data request with custom struct and custom tag20752076```go2077const (2078 customerTag = "url"2079 defaultMemory = 32 << 202080)20812082type customerBinding struct {}20832084func (customerBinding) Name() string {2085 return "form"2086}20872088func (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}21022103func validate(obj interface{}) error {2104 if binding.Validator == nil {2105 return nil2106 }2107 return binding.Validator.ValidateStruct(obj)2108}21092110// Now we can do this!!!2111// FormA is an external type that we can't modify it's tag2112type FormA struct {2113 FieldA string `url:"field_a"`2114}21152116func 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```21282129### http2 server push21302131http.Pusher is supported only **go1.8+**. See the [golang blog](https://go.dev/blog/h2push) for detail information.21322133```go2134package main21352136import (2137 "html/template"2138 "log"2139 "net/http"21402141 "github.com/gin-gonic/gin"2142)21432144var 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`))21552156func main() {2157 r := gin.Default()2158 r.Static("/assets", "./assets")2159 r.SetHTMLTemplate(html)21602161 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 })21722173 // Listen and Server in https://127.0.0.1:80802174 r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")2175}2176```21772178### Define format for the log of routes21792180The default log of routes is:21812182```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```21872188If 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`.2189In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs.21902191```go2192import (2193 "log"2194 "net/http"21952196 "github.com/gin-gonic/gin"2197)21982199func 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 }22042205 r.POST("/foo", func(c *gin.Context) {2206 c.JSON(http.StatusOK, "foo")2207 })22082209 r.GET("/bar", func(c *gin.Context) {2210 c.JSON(http.StatusOK, "bar")2211 })22122213 r.GET("/status", func(c *gin.Context) {2214 c.JSON(http.StatusOK, "ok")2215 })22162217 // Listen and Server in http://0.0.0.0:80802218 r.Run()2219}2220```22212222### Set and get a cookie22232224```go2225import (2226 "fmt"22272228 "github.com/gin-gonic/gin"2229)22302231func main() {22322233 router := gin.Default()22342235 router.GET("/cookie", func(c *gin.Context) {22362237 cookie, err := c.Cookie("gin_cookie")22382239 if err != nil {2240 cookie = "NotSet"2241 c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)2242 }22432244 fmt.Printf("Cookie value: %s \n", cookie)2245 })22462247 router.Run()2248}2249```22502251## Don't trust all proxies22522253Gin lets you specify which headers to hold the real client IP (if any),2254as well as specifying which proxies (or direct clients) you trust to2255specify one of these headers.22562257Use function `SetTrustedProxies()` on your `gin.Engine` to specify network addresses2258or network CIDRs from where clients which their request headers related to client2259IP can be trusted. They can be IPv4 addresses, IPv4 CIDRs, IPv6 addresses or2260IPv6 CIDRs.22612262**Attention:** Gin trust all proxies by default if you don't specify a trusted 2263proxy using the function above, **this is NOT safe**. At the same time, if you don't2264use any proxy, you can disable this feature by using `Engine.SetTrustedProxies(nil)`,2265then `Context.ClientIP()` will return the remote address directly to avoid some2266unnecessary computation.22672268```go2269import (2270 "fmt"22712272 "github.com/gin-gonic/gin"2273)22742275func main() {22762277 router := gin.Default()2278 router.SetTrustedProxies([]string{"192.168.1.2"})22792280 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```22902291**Notice:** If you are using a CDN service, you can set the `Engine.TrustedPlatform`2292to skip TrustedProxies check, it has a higher priority than TrustedProxies. 2293Look at the example below:22942295```go2296import (2297 "fmt"22982299 "github.com/gin-gonic/gin"2300)23012302func main() {23032304 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"23102311 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```23192320## Testing23212322The `net/http/httptest` package is preferable way for HTTP testing.23232324```go2325package main23262327import (2328 "net/http"23292330 "github.com/gin-gonic/gin"2331)23322333func 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}23402341func main() {2342 r := setupRouter()2343 r.Run(":8080")2344}2345```23462347Test for code example above:23482349```go2350package main23512352import (2353 "net/http"2354 "net/http/httptest"2355 "testing"23562357 "github.com/stretchr/testify/assert"2358)23592360func TestPingRoute(t *testing.T) {2361 router := setupRouter()23622363 w := httptest.NewRecorder()2364 req, _ := http.NewRequest(http.MethodGet, "/ping", nil)2365 router.ServeHTTP(w, req)23662367 assert.Equal(t, http.StatusOK, w.Code)2368 assert.Equal(t, "pong", w.Body.String())2369}2370```2371163## Users164165Awesome project lists using [Gin](https://github.com/gin-gonic/gin) web framework.166
3 unmodified lines
170* [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.174175176## Contributing177178Gin is the work of hundreds of contributors. We appreciate your help!179180Please see [CONTRIBUTING](CONTRIBUTING.md) for details on submitting patches and the contribution workflow.