Skip to content
Myr

doc.md

This file

Path

docs/doc.md

2,636 lines · 66.6 KiB · Markdown

Last changed by

chore(logger): allow skipping query string output (#4547)Jacob McSwainbefore adoptiondb30908

History of this file

Take it

The walk stopped after 200 commits: lines older than 28e57f5 point at it.

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1–24why, one step back
1# Gin Quick Start
23## 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)

chore(logger): allow skipping query string output (#4547)Jacob McSwainbefore adoptiondb30908

line 25why, one step back
25 - [Avoid logging query strings](#avoid-loging-query-strings)

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 26–29why, one step back
26 - [Model binding and validation](#model-binding-and-validation)
27 - [Custom Validators](#custom-validators)28 - [Only Bind Query String](#only-bind-query-string)29 - [Bind Query String or Post Data](#bind-query-string-or-post-data)

feat(form): Support default values for collections in form binding (#4048)takanuva15before adoptionf05f966

line 30why, one step back
30 - [Bind default value if none provided](#bind-default-value-if-none-provided)

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 31–66why, one step back
31 - [Collection format for arrays](#collection-format-for-arrays)
32 - [Bind Uri](#bind-uri)33 - [Bind custom unmarshaler](#bind-custom-unmarshaler)34 - [Bind Header](#bind-header)35 - [Bind HTML checkboxes](#bind-html-checkboxes)36 - [Multipart/Urlencoded binding](#multiparturlencoded-binding)37 - [XML, JSON, YAML, TOML and ProtoBuf rendering](#xml-json-yaml-toml-and-protobuf-rendering)38 - [SecureJSON](#securejson)39 - [JSONP](#jsonp)40 - [AsciiJSON](#asciijson)41 - [PureJSON](#purejson)42 - [Serving static files](#serving-static-files)43 - [Serving data from file](#serving-data-from-file)44 - [Serving data from reader](#serving-data-from-reader)45 - [HTML rendering](#html-rendering)46 - [Custom Template renderer](#custom-template-renderer)47 - [Custom Delimiters](#custom-delimiters)48 - [Custom Template Funcs](#custom-template-funcs)49 - [Multitemplate](#multitemplate)50 - [Redirects](#redirects)51 - [Custom Middleware](#custom-middleware)52 - [Using BasicAuth() middleware](#using-basicauth-middleware)53 - [Goroutines inside a middleware](#goroutines-inside-a-middleware)54 - [Custom HTTP configuration](#custom-http-configuration)55 - [Support Let's Encrypt](#support-lets-encrypt)56 - [Run multiple service using Gin](#run-multiple-service-using-gin)57 - [Graceful shutdown or restart](#graceful-shutdown-or-restart)58 - [Third-party packages](#third-party-packages)59 - [Manually](#manually)60 - [Build a single binary with templates](#build-a-single-binary-with-templates)61 - [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct)62 - [Try to bind body into different structs](#try-to-bind-body-into-different-structs)63 - [Bind form-data request with custom struct and custom tag](#bind-form-data-request-with-custom-struct-and-custom-tag)64 - [http2 server push](#http2-server-push)65 - [Define format for the log of routes](#define-format-for-the-log-of-routes)66 - [Set and get a cookie](#set-and-get-a-cookie)

feat: support custom json codec at runtime (#3391)Timbefore adoption688a429

line 67why, one step back
67 - [Custom json codec at runtime](#custom-json-codec-at-runtime)

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 68–74why, one step back
68- [Don't trust all proxies](#dont-trust-all-proxies)
69- [Testing](#testing)7071## Build tags7273### Build with json replacement74

docs: Fixing English grammar mistakes and awkward sentence structure in doc/doc.md (#4207)Adlai Bridson-Boyczukbefore adoption1b53a47

line 75why, one step back
75Gin uses `encoding/json` as the default JSON package but you can change it by building from other tags.

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 76–88why, one step back
76
77[jsoniter](https://github.com/json-iterator/go)7879```sh80go build -tags=jsoniter .81```8283[go-json](https://github.com/goccy/go-json)8485```sh86go build -tags=go_json .87```88

fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655

line 89why, one step back
89[sonic](https://github.com/bytedance/sonic)

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 90–91why, one step back
90
91```sh

fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655

line 92why, one step back
92$ go build -tags=sonic .

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 93–124why, one step back
93```
9495### Build without `MsgPack` rendering feature9697Gin enables `MsgPack` rendering feature by default. But you can disable this feature by specifying `nomsgpack` build tag.9899```sh100go build -tags=nomsgpack .101```102103This is useful to reduce the binary size of executable files. See the [detail information](https://github.com/gin-gonic/gin/pull/1852).104105## API Examples106107You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples).108109### Using GET, POST, PUT, PATCH, DELETE and OPTIONS110111```go112func main() {113 // Creates a gin router with default middleware:114 // logger and recovery (crash-free) middleware115 router := gin.Default()116117 router.GET("/someGet", getting)118 router.POST("/somePost", posting)119 router.PUT("/somePut", putting)120 router.DELETE("/someDelete", deleting)121 router.PATCH("/somePatch", patching)122 router.HEAD("/someHead", head)123 router.OPTIONS("/someOptions", options)124

docs: Fixing English grammar mistakes and awkward sentence structure in doc/doc.md (#4207)Adlai Bridson-Boyczukbefore adoption1b53a47

line 125why, one step back
125 // By default, it serves on :8080 unless a

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 126–176why, one step back
126 // PORT environment variable was defined.
127 router.Run()128 // router.Run(":3000") for a hard coded port129}130```131132### Parameters in path133134```go135func main() {136 router := gin.Default()137138 // This handler will match /user/john but will not match /user/ or /user139 router.GET("/user/:name", func(c *gin.Context) {140 name := c.Param("name")141 c.String(http.StatusOK, "Hello %s", name)142 })143144 // However, this one will match /user/john/ and also /user/john/send145 // If no other routers match /user/john, it will redirect to /user/john/146 router.GET("/user/:name/*action", func(c *gin.Context) {147 name := c.Param("name")148 action := c.Param("action")149 message := name + " is " + action150 c.String(http.StatusOK, message)151 })152153 // For each matched request Context will hold the route definition154 router.POST("/user/:name/*action", func(c *gin.Context) {155 b := c.FullPath() == "/user/:name/*action" // true156 c.String(http.StatusOK, "%t", b)157 })158159 // This handler will add a new router for /user/groups.160 // Exact routes are resolved before param routes, regardless of the order they were defined.161 // Routes starting with /user/groups are never interpreted as /user/:name/... routes162 router.GET("/user/groups", func(c *gin.Context) {163 c.String(http.StatusOK, "The available groups are [...]")164 })165166 router.Run(":8080")167}168```169170### Querystring parameters171172```go173func main() {174 router := gin.Default()175176 // Query string parameters are parsed using the existing underlying request object.

docs: Fixing English grammar mistakes and awkward sentence structure in doc/doc.md (#4207)Adlai Bridson-Boyczukbefore adoption1b53a47

line 177why, one step back
177 // The request responds to a URL matching: /welcome?firstname=Jane&lastname=Doe

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 178–304why, one step back
178 router.GET("/welcome", func(c *gin.Context) {
179 firstname := c.DefaultQuery("firstname", "Guest")180 lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")181182 c.String(http.StatusOK, "Hello %s %s", firstname, lastname)183 })184 router.Run(":8080")185}186```187188### Multipart/Urlencoded Form189190```go191func main() {192 router := gin.Default()193194 router.POST("/form_post", func(c *gin.Context) {195 message := c.PostForm("message")196 nick := c.DefaultPostForm("nick", "anonymous")197198 c.JSON(http.StatusOK, gin.H{199 "status": "posted",200 "message": message,201 "nick": nick,202 })203 })204 router.Run(":8080")205}206```207208### Another example: query + post form209210```sh211POST /post?id=1234&page=1 HTTP/1.1212Content-Type: application/x-www-form-urlencoded213214name=manu&message=this_is_great215```216217```go218func main() {219 router := gin.Default()220221 router.POST("/post", func(c *gin.Context) {222223 id := c.Query("id")224 page := c.DefaultQuery("page", "0")225 name := c.PostForm("name")226 message := c.PostForm("message")227228 fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)229 })230 router.Run(":8080")231}232```233234```sh235id: 1234; page: 1; name: manu; message: this_is_great236```237238### Map as querystring or postform parameters239240```sh241POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1242Content-Type: application/x-www-form-urlencoded243244names[first]=thinkerou&names[second]=tianou245```246247```go248func main() {249 router := gin.Default()250251 router.POST("/post", func(c *gin.Context) {252253 ids := c.QueryMap("ids")254 names := c.PostFormMap("names")255256 fmt.Printf("ids: %v; names: %v", ids, names)257 })258 router.Run(":8080")259}260```261262```sh263ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou]264```265266### Upload files267268#### Single file269270References 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).271272`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)273274> 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.275276```go277func main() {278 router := gin.Default()279 // Set a lower memory limit for multipart forms (default is 32 MiB)280 router.MaxMultipartMemory = 8 << 20 // 8 MiB281 router.POST("/upload", func(c *gin.Context) {282 // Single file283 file, _ := c.FormFile("file")284 log.Println(file.Filename)285286 // Upload the file to specific dst.287 c.SaveUploadedFile(file, dst)288289 c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))290 })291 router.Run(":8080")292}293```294295How to `curl`:296297```bash298curl -X POST http://localhost:8080/upload \299 -F "file=@/Users/appleboy/test.zip" \300 -H "Content-Type: multipart/form-data"301```302303#### Multiple files304

docs: Fixing English grammar mistakes and awkward sentence structure in doc/doc.md (#4207)Adlai Bridson-Boyczukbefore adoption1b53a47

line 305why, one step back
305See the detailed [example code](https://github.com/gin-gonic/examples/tree/master/upload-file/multiple).

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 306–345why, one step back
306
307```go308func main() {309 router := gin.Default()310 // Set a lower memory limit for multipart forms (default is 32 MiB)311 router.MaxMultipartMemory = 8 << 20 // 8 MiB312 router.POST("/upload", func(c *gin.Context) {313 // Multipart form314 form, _ := c.MultipartForm()315 files := form.File["upload[]"]316317 for _, file := range files {318 log.Println(file.Filename)319320 // Upload the file to specific dst.321 c.SaveUploadedFile(file, dst)322 }323 c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))324 })325 router.Run(":8080")326}327```328329How to `curl`:330331```bash332curl -X POST http://localhost:8080/upload \333 -F "upload[]=@/Users/appleboy/test1.zip" \334 -F "upload[]=@/Users/appleboy/test2.zip" \335 -H "Content-Type: multipart/form-data"336```337338### Grouping routes339340```go341func main() {342 router := gin.Default()343344 // Simple group: v1345 {

docs: fix route group example code (#4020)demouthbefore adoptionf2c861a

line 346why, one step back
346 v1 := router.Group("/v1")

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 347–353why, one step back
347 v1.POST("/login", loginEndpoint)
348 v1.POST("/submit", submitEndpoint)349 v1.POST("/read", readEndpoint)350 }351352 // Simple group: v2353 {

docs: fix route group example code (#4020)demouthbefore adoptionf2c861a

line 354why, one step back
354 v2 := router.Group("/v2")

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 355–520why, one step back
355 v2.POST("/login", loginEndpoint)
356 v2.POST("/submit", submitEndpoint)357 v2.POST("/read", readEndpoint)358 }359360 router.Run(":8080")361}362```363364### Blank Gin without middleware by default365366Use367368```go369r := gin.New()370```371372instead of373374```go375// Default With the Logger and Recovery middleware already attached376r := gin.Default()377```378379### Using middleware380381```go382func main() {383 // Creates a router without any middleware by default384 r := gin.New()385386 // Global middleware387 // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.388 // By default gin.DefaultWriter = os.Stdout389 r.Use(gin.Logger())390391 // Recovery middleware recovers from any panics and writes a 500 if there was one.392 r.Use(gin.Recovery())393394 // Per route middleware, you can add as many as you desire.395 r.GET("/benchmark", MyBenchLogger(), benchEndpoint)396397 // Authorization group398 // authorized := r.Group("/", AuthRequired())399 // exactly the same as:400 authorized := r.Group("/")401 // per group middleware! in this case we use the custom created402 // AuthRequired() middleware just in the "authorized" group.403 authorized.Use(AuthRequired())404 {405 authorized.POST("/login", loginEndpoint)406 authorized.POST("/submit", submitEndpoint)407 authorized.POST("/read", readEndpoint)408409 // nested group410 testing := authorized.Group("testing")411 // visit 0.0.0.0:8080/testing/analytics412 testing.GET("/analytics", analyticsEndpoint)413 }414415 // Listen and serve on 0.0.0.0:8080416 r.Run(":8080")417}418```419420### Custom Recovery behavior421422```go423func main() {424 // Creates a router without any middleware by default425 r := gin.New()426427 // Global middleware428 // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.429 // By default gin.DefaultWriter = os.Stdout430 r.Use(gin.Logger())431432 // Recovery middleware recovers from any panics and writes a 500 if there was one.433 r.Use(gin.CustomRecovery(func(c *gin.Context, recovered any) {434 if err, ok := recovered.(string); ok {435 c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))436 }437 c.AbortWithStatus(http.StatusInternalServerError)438 }))439440 r.GET("/panic", func(c *gin.Context) {441 // panic with a string -- the custom middleware could save this to a database or report it to the user442 panic("foo")443 })444445 r.GET("/", func(c *gin.Context) {446 c.String(http.StatusOK, "ohai")447 })448449 // Listen and serve on 0.0.0.0:8080450 r.Run(":8080")451}452```453454### How to write log file455456```go457func main() {458 // Disable Console Color, you don't need console color when writing the logs to file.459 gin.DisableConsoleColor()460461 // Logging to a file.462 f, _ := os.Create("gin.log")463 gin.DefaultWriter = io.MultiWriter(f)464465 // Use the following code if you need to write the logs to file and console at the same time.466 // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)467468 router := gin.Default()469 router.GET("/ping", func(c *gin.Context) {470 c.String(http.StatusOK, "pong")471 })472473   router.Run(":8080")474}475```476477### Custom Log Format478479```go480func main() {481 router := gin.New()482483 // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter484 // By default gin.DefaultWriter = os.Stdout485 router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {486487 // your custom format488 return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",489 param.ClientIP,490 param.TimeStamp.Format(time.RFC1123),491 param.Method,492 param.Path,493 param.Request.Proto,494 param.StatusCode,495 param.Latency,496 param.Request.UserAgent(),497 param.ErrorMessage,498 )499 }))500 router.Use(gin.Recovery())501502 router.GET("/ping", func(c *gin.Context) {503 c.String(http.StatusOK, "pong")504 })505506 router.Run(":8080")507}508```509510Sample Output511512```sh513::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" "514```515516### Skip logging517518```go519func main() {520 router := gin.New()

docs: trimmed some white spaces (#4070)tsukasa-inobefore adoption299c6f3

line 521why, one step back
521

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 522–523why, one step back
522 // skip logging for desired paths by setting SkipPaths in LoggerConfig
523 loggerConfig := gin.LoggerConfig{SkipPaths: []string{"/metrics"}}

docs: trimmed some white spaces (#4070)tsukasa-inobefore adoption299c6f3

line 524why, one step back
524

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 525–529why, one step back
525 // skip logging based on your logic by setting Skip func in LoggerConfig
526 loggerConfig.Skip = func(c *gin.Context) bool {527 // as an example skip non server side errors528 return c.Writer.Status() < http.StatusInternalServerError529 }

docs: trimmed some white spaces (#4070)tsukasa-inobefore adoption299c6f3

line 530why, one step back
530

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 531–532why, one step back
531 router.Use(gin.LoggerWithConfig(loggerConfig))
532 router.Use(gin.Recovery())

docs: trimmed some white spaces (#4070)tsukasa-inobefore adoption299c6f3

line 533why, one step back
533

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 534–547why, one step back
534 // skipped
535 router.GET("/metrics", func(c *gin.Context) {536 c.Status(http.StatusNotImplemented)537 })538539 // skipped540 router.GET("/ping", func(c *gin.Context) {541 c.String(http.StatusOK, "pong")542 })543544 // not skipped545 router.GET("/data", func(c *gin.Context) {546 c.Status(http.StatusNotImplemented)547 })

docs: trimmed some white spaces (#4070)tsukasa-inobefore adoption299c6f3

line 548why, one step back
548

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 549–592why, one step back
549 router.Run(":8080")
550}551552```553554### Controlling Log output coloring555556By default, logs output on console should be colorized depending on the detected TTY.557558Never colorize logs:559560```go561func main() {562 // Disable log's color563 gin.DisableConsoleColor()564565 // Creates a gin router with default middleware:566 // logger and recovery (crash-free) middleware567 router := gin.Default()568569 router.GET("/ping", func(c *gin.Context) {570 c.String(http.StatusOK, "pong")571 })572573 router.Run(":8080")574}575```576577Always colorize logs:578579```go580func main() {581 // Force log's color582 gin.ForceConsoleColor()583584 // Creates a gin router with default middleware:585 // logger and recovery (crash-free) middleware586 router := gin.Default()587588 router.GET("/ping", func(c *gin.Context) {589 c.String(http.StatusOK, "pong")590 })591592 router.Run(":8080")

chore(logger): allow skipping query string output (#4547)Jacob McSwainbefore adoptiondb30908

lines 593–606why, one step back
593}
594```595596### Avoid logging query strings597598```go599func main() {600 router := gin.New()601 602 // SkipQueryString indicates that the logger should not log the query string.603 // For example, /path?q=1 will be logged as /path604 loggerConfig := gin.LoggerConfig{SkipQueryString: true}605 606 router.Use(gin.LoggerWithConfig(loggerConfig))

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 607–633why, one step back
607}
608```609610### Model binding and validation611612To 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).613614Gin 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).615616Note 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"`.617618Also, Gin provides two sets of methods for binding:619620- **Type** - Must bind621 - **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`, `BindHeader`, `BindTOML`622 - **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.623- **Type** - Should bind624 - **Methods** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindXML`, `ShouldBindQuery`, `ShouldBindYAML`, `ShouldBindHeader`, `ShouldBindTOML`,625 - **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.626627When 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`.628629You 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.630631```go632// Binding from JSON633type Login struct {

docs: trimmed some white spaces (#4070)tsukasa-inobefore adoption299c6f3

line 634why, one step back
634 User string `form:"user" json:"user" xml:"user" binding:"required"`

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 635–722why, one step back
635 Password string `form:"password" json:"password" xml:"password" binding:"required"`
636}637638func main() {639 router := gin.Default()640641 // Example for binding JSON ({"user": "manu", "password": "123"})642 router.POST("/loginJSON", func(c *gin.Context) {643 var json Login644 if err := c.ShouldBindJSON(&json); err != nil {645 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})646 return647 }648649 if json.User != "manu" || json.Password != "123" {650 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})651 return652 }653654 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})655 })656657 // Example for binding XML (658 // <?xml version="1.0" encoding="UTF-8"?>659 // <root>660 // <user>manu</user>661 // <password>123</password>662 // </root>)663 router.POST("/loginXML", func(c *gin.Context) {664 var xml Login665 if err := c.ShouldBindXML(&xml); err != nil {666 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})667 return668 }669670 if xml.User != "manu" || xml.Password != "123" {671 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})672 return673 }674675 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})676 })677678 // Example for binding a HTML form (user=manu&password=123)679 router.POST("/loginForm", func(c *gin.Context) {680 var form Login681 // This will infer what binder to use depending on the content-type header.682 if err := c.ShouldBind(&form); err != nil {683 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})684 return685 }686687 if form.User != "manu" || form.Password != "123" {688 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})689 return690 }691692 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})693 })694695 // Listen and serve on 0.0.0.0:8080696 router.Run(":8080")697}698```699700Sample request701702```sh703$ curl -v -X POST \704 http://localhost:8080/loginJSON \705 -H 'content-type: application/json' \706 -d '{ "user": "manu" }'707> POST /loginJSON HTTP/1.1708> Host: localhost:8080709> User-Agent: curl/7.51.0710> Accept: */*711> content-type: application/json712> Content-Length: 18713>714* upload completely sent off: 18 out of 18 bytes715< HTTP/1.1 400 Bad Request716< Content-Type: application/json; charset=utf-8717< Date: Fri, 04 Aug 2017 03:51:31 GMT718< Content-Length: 100719<720{"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}721```722

docs: Fixing English grammar mistakes and awkward sentence structure in doc/doc.md (#4207)Adlai Bridson-Boyczukbefore adoption1b53a47

line 723why, one step back
723Skip-validation: Running the example above using the `curl` command returns an error. This is because the example uses `binding:"required"` for `Password`. If instead, you use `binding:"-"` for `Password`, then it will not return an error when you run the example again.

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 724–850why, one step back
724
725### Custom Validators726727It is also possible to register custom validators. See the [example code](https://github.com/gin-gonic/examples/tree/master/custom-validation/server.go).728729```go730package main731732import (733 "net/http"734 "time"735736 "github.com/gin-gonic/gin"737 "github.com/gin-gonic/gin/binding"738 "github.com/go-playground/validator/v10"739)740741// Booking contains binded and validated data.742type Booking struct {743 CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`744 CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`745}746747var bookableDate validator.Func = func(fl validator.FieldLevel) bool {748 date, ok := fl.Field().Interface().(time.Time)749 if ok {750 today := time.Now()751 if today.After(date) {752 return false753 }754 }755 return true756}757758func main() {759 route := gin.Default()760761 if v, ok := binding.Validator.Engine().(*validator.Validate); ok {762 v.RegisterValidation("bookabledate", bookableDate)763 }764765 route.GET("/bookable", getBookable)766 route.Run(":8085")767}768769func getBookable(c *gin.Context) {770 var b Booking771 if err := c.ShouldBindWith(&b, binding.Query); err == nil {772 c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})773 } else {774 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})775 }776}777```778779```console780$ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17"781{"message":"Booking dates are valid!"}782783$ curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09"784{"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"}785786$ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10"787{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}%788```789790[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way.791See the [struct-lvl-validation example](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) to learn more.792793### Only Bind Query String794795`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).796797```go798package main799800import (801 "log"802 "net/http"803804 "github.com/gin-gonic/gin"805)806807type Person struct {808 Name string `form:"name"`809 Address string `form:"address"`810}811812func main() {813 route := gin.Default()814 route.Any("/testing", startPage)815 route.Run(":8085")816}817818func startPage(c *gin.Context) {819 var person Person820 if c.ShouldBindQuery(&person) == nil {821 log.Println("====== Only Bind By Query String ======")822 log.Println(person.Name)823 log.Println(person.Address)824 }825 c.String(http.StatusOK, "Success")826}827828```829830### Bind Query String or Post Data831832See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292).833834```go835package main836837import (838 "log"839 "net/http"840 "time"841842 "github.com/gin-gonic/gin"843)844845type Person struct {846 Name string `form:"name"`847 Address string `form:"address"`848 Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`849 CreateTime time.Time `form:"createTime" time_format:"unixNano"`850 UnixTime time.Time `form:"unixTime" time_format:"unix"`

feat(binding): add support for unixMilli and unixMicro (#4190)takanuva15before adoption4ccfa7c

lines 851–852why, one step back
851 UnixMilliTime time.Time `form:"unixMilliTime" time_format:"unixmilli"`
852 UnixMicroTime time.Time `form:"unixMicroTime" time_format:"uNiXmIcRo"` // case does not matter for "unix*" time formats

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 853–871why, one step back
853}
854855func main() {856 route := gin.Default()857 route.GET("/testing", startPage)858 route.Run(":8085")859}860861func startPage(c *gin.Context) {862 var person Person863 // If `GET`, only `Form` binding engine (`query`) used.864 // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).865 // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L88866 if c.ShouldBind(&person) == nil {867 log.Println(person.Name)868 log.Println(person.Address)869 log.Println(person.Birthday)870 log.Println(person.CreateTime)871 log.Println(person.UnixTime)

feat(binding): add support for unixMilli and unixMicro (#4190)takanuva15before adoption4ccfa7c

lines 872–873why, one step back
872 log.Println(person.UnixMilliTime)
873 log.Println(person.UnixMicroTime)

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 874–882why, one step back
874 }
875876 c.String(http.StatusOK, "Success")877}878```879880Test it with:881882```sh

feat(binding): add support for unixMilli and unixMicro (#4190)takanuva15before adoption4ccfa7c

line 883why, one step back
883curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033&unixMilliTime=1562400033001&unixMicroTime=1562400033000012"

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

line 884why, one step back
884```

feat(form): Support default values for collections in form binding (#4048)takanuva15before adoptionf05f966

lines 885–890why, one step back
885
886887### Bind default value if none provided888889If the server should bind a default value to a field when the client does not provide one, specify the default value using the `default` key within the `form` tag:890

fix(docs): missing go markdown codeblock (#4266)Victor Dusartbefore adoptiondd33ff7

line 891why, one step back
891```go

feat(form): Support default values for collections in form binding (#4048)takanuva15before adoptionf05f966

lines 892–928why, one step back
892package main
893894import (895 "net/http"896897 "github.com/gin-gonic/gin"898)899900type Person struct {901 Name string `form:"name,default=William"`902 Age int `form:"age,default=10"`903 Friends []string `form:"friends,default=Will;Bill"`904 Addresses [2]string `form:"addresses,default=foo bar" collection_format:"ssv"`905 LapTimes []int `form:"lap_times,default=1;2;3" collection_format:"csv"`906}907908func main() {909 g := gin.Default()910 g.POST("/person", func(c *gin.Context) {911 var req Person912 if err := c.ShouldBindQuery(&req); err != nil {913 c.JSON(http.StatusBadRequest, err)914 return915 }916 c.JSON(http.StatusOK, req)917 })918 _ = g.Run("localhost:8080")919}920```921922```923curl -X POST http://localhost:8080/person924{"Name":"William","Age":10,"Friends":["Will","Bill"],"Colors":["red","blue"],"LapTimes":[1,2,3]}925```926927NOTE: For default [collection values](#collection-format-for-arrays), the following rules apply:928- Since commas are used to delimit tag options, they are not supported within a default value and will result in undefined behavior

feat(binding): add support for encoding.UnmarshalText in uri/query binding (#4203)takanuva15before adoption192ac89

line 929why, one step back
929- For the collection formats "multi" and "csv", a semicolon should be used in place of a comma to delimit default values

feat(form): Support default values for collections in form binding (#4048)takanuva15before adoptionf05f966

lines 930–931why, one step back
930- Since semicolons are used to delimit default values for "multi" and "csv", they are not supported within a default value for "multi" and "csv"
931

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 932–1026why, one step back
932
933#### Collection format for arrays934935| Format | Description | Example |936| --------------- | --------------------------------------------------------- | ----------------------- |937| multi (default) | Multiple parameter instances rather than multiple values. | key=foo&key=bar&key=baz |938| csv | Comma-separated values. | foo,bar,baz |939| ssv | Space-separated values. | foo bar baz |940| tsv | Tab-separated values. | "foo\tbar\tbaz" |941| pipes | Pipe-separated values. | foo\|bar\|baz |942943```go944package main945946import (947 "log"948 "time"949 "github.com/gin-gonic/gin"950)951952type Person struct {953 Name string `form:"name"`954 Addresses []string `form:"addresses" collection_format:"csv"`955 Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`956 CreateTime time.Time `form:"createTime" time_format:"unixNano"`957 UnixTime time.Time `form:"unixTime" time_format:"unix"`958}959960func main() {961 route := gin.Default()962 route.GET("/testing", startPage)963 route.Run(":8085")964}965func startPage(c *gin.Context) {966 var person Person967 // If `GET`, only `Form` binding engine (`query`) used.968 // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).969 // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48970 if c.ShouldBind(&person) == nil {971 log.Println(person.Name)972 log.Println(person.Addresses)973 log.Println(person.Birthday)974 log.Println(person.CreateTime)975 log.Println(person.UnixTime)976 }977 c.String(200, "Success")978}979```980981Test it with:982```sh983$ curl -X GET "localhost:8085/testing?name=appleboy&addresses=foo,bar&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"984```985986### Bind Uri987988See the [detail information](https://github.com/gin-gonic/gin/issues/846).989990```go991package main992993import (994 "net/http"995996 "github.com/gin-gonic/gin"997)998999type Person struct {1000 ID string `uri:"id" binding:"required,uuid"`1001 Name string `uri:"name" binding:"required"`1002}10031004func main() {1005 route := gin.Default()1006 route.GET("/:name/:id", func(c *gin.Context) {1007 var person Person1008 if err := c.ShouldBindUri(&person); err != nil {1009 c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})1010 return1011 }1012 c.JSON(http.StatusOK, gin.H{"name": person.Name, "uuid": person.ID})1013 })1014 route.Run(":8088")1015}1016```10171018Test it with:10191020```sh1021curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f31022curl -v localhost:8088/thinkerou/not-uuid1023```10241025### Bind custom unmarshaler1026

feat(binding): add support for encoding.UnmarshalText in uri/query binding (#4203)takanuva15before adoption192ac89

lines 1027–1028why, one step back
1027To override gin's default binding logic, define a function on your type that satisfies the `encoding.TextUnmarshaler` interface from the Golang standard library. Then specify `parser=encoding.TextUnmarshaler` in the `uri`/`form` tag of the field being bound.
1028

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1029–1032why, one step back
1029```go
1030package main10311032import (

feat(binding): add support for encoding.UnmarshalText in uri/query binding (#4203)takanuva15before adoption192ac89

lines 1033–1035why, one step back
1033 "encoding"
1034 "strings"1035

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

line 1036why, one step back
1036 "github.com/gin-gonic/gin"

feat(binding): add support for encoding.UnmarshalText in uri/query binding (#4203)takanuva15before adoption192ac89

lines 1037–1084why, one step back
1037)
10381039type Birthday string10401041func (b *Birthday) UnmarshalText(text []byte) error {1042 *b = Birthday(strings.Replace(string(text), "-", "/", -1))1043 return nil1044}10451046var _ encoding.TextUnmarshaler = (*Birthday)(nil) //assert Birthday implements encoding.TextUnmarshaler10471048func main() {1049 route := gin.Default()1050 var request struct {1051 Birthday Birthday `form:"birthday,parser=encoding.TextUnmarshaler"`1052 Birthdays []Birthday `form:"birthdays,parser=encoding.TextUnmarshaler" collection_format:"csv"`1053 BirthdaysDefault []Birthday `form:"birthdaysDef,default=2020-09-01;2020-09-02,parser=encoding.TextUnmarshaler" collection_format:"csv"`1054 }1055 route.GET("/test", func(ctx *gin.Context) {1056 _ = ctx.BindQuery(&request)1057 ctx.JSON(200, request)1058 })1059 _ = route.Run(":8088")1060}1061```10621063Test it with:10641065```sh1066curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02'1067```1068Result1069```sh1070{"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]}1071```10721073Note:1074- If `parser=encoding.TextUnmarshaler` is specified for a type that does **not** implement `encoding.TextUnmarshaler`, gin will ignore it and proceed with its default binding logic.1075- If `parser=encoding.TextUnmarshaler` is specified for a type and that type's implementation of `encoding.TextUnmarshaler` returns an error, gin will stop binding and return the error to the client.10761077---10781079If a type already implements `encoding.TextUnmarshaler` but you want to customize how gin binds the type differently (eg to change what error message is returned), you can implement the dedicated `BindUnmarshaler` interface provided by gin instead.10801081```go1082package main10831084import (

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

line 1085why, one step back
1085 "strings"

feat(binding): add support for encoding.UnmarshalText in uri/query binding (#4203)takanuva15before adoption192ac89

lines 1086–1088why, one step back
1086
1087 "github.com/gin-gonic/gin"1088 "github.com/gin-gonic/gin/binding"

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1089–1097why, one step back
1089)
10901091type Birthday string10921093func (b *Birthday) UnmarshalParam(param string) error {1094 *b = Birthday(strings.Replace(param, "-", "/", -1))1095 return nil1096}1097

feat(binding): add support for encoding.UnmarshalText in uri/query binding (#4203)takanuva15before adoption192ac89

lines 1098–1099why, one step back
1098var _ binding.BindUnmarshaler = (*Birthday)(nil) //assert Birthday implements binding.BindUnmarshaler
1099

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1100–1102why, one step back
1100func main() {
1101 route := gin.Default()1102 var request struct {

feat(binding): add support for encoding.UnmarshalText in uri/query binding (#4203)takanuva15before adoption192ac89

lines 1103–1105why, one step back
1103 Birthday Birthday `form:"birthday"`
1104 Birthdays []Birthday `form:"birthdays" collection_format:"csv"`1105 BirthdaysDefault []Birthday `form:"birthdaysDef,default=2020-09-01;2020-09-02" collection_format:"csv"`

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1106–1108why, one step back
1106 }
1107 route.GET("/test", func(ctx *gin.Context) {1108 _ = ctx.BindQuery(&request)

feat(binding): add support for encoding.UnmarshalText in uri/query binding (#4203)takanuva15before adoption192ac89

line 1109why, one step back
1109 ctx.JSON(200, request)

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

line 1110why, one step back
1110 })

feat(binding): add support for encoding.UnmarshalText in uri/query binding (#4203)takanuva15before adoption192ac89

line 1111why, one step back
1111 _ = route.Run(":8088")

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1112–1117why, one step back
1112}
1113```11141115Test it with:11161117```sh

feat(binding): add support for encoding.UnmarshalText in uri/query binding (#4203)takanuva15before adoption192ac89

line 1118why, one step back
1118curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02'

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1119–1121why, one step back
1119```
1120Result1121```sh

feat(binding): add support for encoding.UnmarshalText in uri/query binding (#4203)takanuva15before adoption192ac89

line 1122why, one step back
1122{"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]}

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

line 1123why, one step back
1123```

feat(binding): add support for encoding.UnmarshalText in uri/query binding (#4203)takanuva15before adoption192ac89

lines 1124–1127why, one step back
1124
1125Note:1126- If a type implements both `encoding.TextUnmarshaler` and `BindUnmarshaler`, gin will use `BindUnmarshaler` by default unless you specify `parser=encoding.TextUnmarshaler` in the binding tag.1127- If a type returns an error from its implementation of `BindUnmarshaler`, gin will stop binding and return the error to the client.

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1128–1269why, one step back
1128
1129### Bind Header11301131```go1132package main11331134import (1135 "fmt"1136 "net/http"11371138 "github.com/gin-gonic/gin"1139)11401141type testHeader struct {1142 Rate int `header:"Rate"`1143 Domain string `header:"Domain"`1144}11451146func main() {1147 r := gin.Default()1148 r.GET("/", func(c *gin.Context) {1149 h := testHeader{}11501151 if err := c.ShouldBindHeader(&h); err != nil {1152 c.JSON(http.StatusOK, err)1153 }11541155 fmt.Printf("%#v\n", h)1156 c.JSON(http.StatusOK, gin.H{"Rate": h.Rate, "Domain": h.Domain})1157 })11581159 r.Run()11601161// client1162// curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/1163// output1164// {"Domain":"music","Rate":300}1165}1166```11671168### Bind HTML checkboxes11691170See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)11711172main.go11731174```go1175...11761177type myForm struct {1178 Colors []string `form:"colors[]"`1179}11801181...11821183func formHandler(c *gin.Context) {1184 var fakeForm myForm1185 c.ShouldBind(&fakeForm)1186 c.JSON(http.StatusOK, gin.H{"color": fakeForm.Colors})1187}11881189...11901191```11921193form.html11941195```html1196<form action="/" method="POST">1197 <p>Check some colors</p>1198 <label for="red">Red</label>1199 <input type="checkbox" name="colors[]" value="red" id="red">1200 <label for="green">Green</label>1201 <input type="checkbox" name="colors[]" value="green" id="green">1202 <label for="blue">Blue</label>1203 <input type="checkbox" name="colors[]" value="blue" id="blue">1204 <input type="submit">1205</form>1206```12071208result:12091210```json1211{"color":["red","green","blue"]}1212```12131214### Multipart/Urlencoded binding12151216```go1217type ProfileForm struct {1218 Name string `form:"name" binding:"required"`1219 Avatar *multipart.FileHeader `form:"avatar" binding:"required"`12201221 // or for multiple files1222 // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"`1223}12241225func main() {1226 router := gin.Default()1227 router.POST("/profile", func(c *gin.Context) {1228 // you can bind multipart form with explicit binding declaration:1229 // c.ShouldBindWith(&form, binding.Form)1230 // or you can simply use autobinding with ShouldBind method:1231 var form ProfileForm1232 // in this case proper binding will be automatically selected1233 if err := c.ShouldBind(&form); err != nil {1234 c.String(http.StatusBadRequest, "bad request")1235 return1236 }12371238 err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename)1239 if err != nil {1240 c.String(http.StatusInternalServerError, "unknown error")1241 return1242 }12431244 // db.Save(&form)12451246 c.String(http.StatusOK, "ok")1247 })1248 router.Run(":8080")1249}1250```12511252Test it with:12531254```sh1255curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile1256```12571258### XML, JSON, YAML, TOML and ProtoBuf rendering12591260```go1261func main() {1262 r := gin.Default()12631264 // gin.H is a shortcut for map[string]any1265 r.GET("/someJSON", func(c *gin.Context) {1266 c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1267 })12681269 r.GET("/moreJSON", func(c *gin.Context) {

docs: Fixing English grammar mistakes and awkward sentence structure in doc/doc.md (#4207)Adlai Bridson-Boyczukbefore adoption1b53a47

line 1270why, one step back
1270 // You can also use a struct

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1271–1338why, one step back
1271 var msg struct {
1272 Name string `json:"user"`1273 Message string1274 Number int1275 }1276 msg.Name = "Lena"1277 msg.Message = "hey"1278 msg.Number = 1231279 // Note that msg.Name becomes "user" in the JSON1280 // Will output : {"user": "Lena", "Message": "hey", "Number": 123}1281 c.JSON(http.StatusOK, msg)1282 })12831284 r.GET("/someXML", func(c *gin.Context) {1285 c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1286 })12871288 r.GET("/someYAML", func(c *gin.Context) {1289 c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1290 })12911292 r.GET("/someTOML", func(c *gin.Context) {1293 c.TOML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1294 })12951296 r.GET("/someProtoBuf", func(c *gin.Context) {1297 reps := []int64{int64(1), int64(2)}1298 label := "test"1299 // The specific definition of protobuf is written in the testdata/protoexample file.1300 data := &protoexample.Test{1301 Label: &label,1302 Reps: reps,1303 }1304 // Note that data becomes binary data in the response1305 // Will output protoexample.Test protobuf serialized data1306 c.ProtoBuf(http.StatusOK, data)1307 })13081309 // Listen and serve on 0.0.0.0:80801310 r.Run(":8080")1311}1312```13131314#### SecureJSON13151316Using SecureJSON to prevent json hijacking. Default prepends `"while(1),"` to response body if the given struct is array values.13171318```go1319func main() {1320 r := gin.Default()13211322 // You can also use your own secure json prefix1323 // r.SecureJsonPrefix(")]}',\n")13241325 r.GET("/someJSON", func(c *gin.Context) {1326 names := []string{"lena", "austin", "foo"}13271328 // Will output : while(1);["lena","austin","foo"]1329 c.SecureJSON(http.StatusOK, names)1330 })13311332 // Listen and serve on 0.0.0.0:80801333 r.Run(":8080")1334}1335```13361337#### JSONP1338

docs: trimmed some white spaces (#4070)tsukasa-inobefore adoption299c6f3

line 1339why, one step back
1339Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists.

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1340–1387why, one step back
1340
1341```go1342func main() {1343 r := gin.Default()13441345 r.GET("/JSONP", func(c *gin.Context) {1346 data := gin.H{1347 "foo": "bar",1348 }13491350 //callback is x1351 // Will output : x({\"foo\":\"bar\"})1352 c.JSONP(http.StatusOK, data)1353 })13541355 // Listen and serve on 0.0.0.0:80801356 r.Run(":8080")13571358 // client1359 // curl http://127.0.0.1:8080/JSONP?callback=x1360}1361```13621363#### AsciiJSON13641365Using AsciiJSON to Generates ASCII-only JSON with escaped non-ASCII characters.13661367```go1368func main() {1369 r := gin.Default()13701371 r.GET("/someJSON", func(c *gin.Context) {1372 data := gin.H{1373 "lang": "GO语言",1374 "tag": "<br>",1375 }13761377 // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}1378 c.AsciiJSON(http.StatusOK, data)1379 })13801381 // Listen and serve on 0.0.0.0:80801382 r.Run(":8080")1383}1384```13851386#### PureJSON1387

docs: trimmed some white spaces (#4070)tsukasa-inobefore adoption299c6f3

line 1388why, one step back
1388Normally, 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.

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1389–1422why, one step back
1389This feature is unavailable in Go 1.6 and lower.
13901391```go1392func main() {1393 r := gin.Default()13941395 // Serves unicode entities1396 r.GET("/json", func(c *gin.Context) {1397 c.JSON(http.StatusOK, gin.H{1398 "html": "<b>Hello, world!</b>",1399 })1400 })14011402 // Serves literal characters1403 r.GET("/purejson", func(c *gin.Context) {1404 c.PureJSON(http.StatusOK, gin.H{1405 "html": "<b>Hello, world!</b>",1406 })1407 })14081409 // listen and serve on 0.0.0.0:80801410 r.Run(":8080")1411}1412```14131414### Serving static files14151416```go1417func main() {1418 router := gin.Default()1419 router.Static("/assets", "./assets")1420 router.StaticFS("/more_static", http.Dir("my_file_system"))1421 router.StaticFile("/favicon.ico", "./resources/favicon.ico")1422 router.StaticFileFS("/more_favicon.ico", "more_favicon.ico", http.Dir("my_file_system"))

docs: trimmed some white spaces (#4070)tsukasa-inobefore adoption299c6f3

line 1423why, one step back
1423

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1424–1475why, one step back
1424 // Listen and serve on 0.0.0.0:8080
1425 router.Run(":8080")1426}1427```14281429### Serving data from file14301431```go1432func main() {1433 router := gin.Default()14341435 router.GET("/local/file", func(c *gin.Context) {1436 c.File("local/file.go")1437 })14381439 var fs http.FileSystem = // ...1440 router.GET("/fs/file", func(c *gin.Context) {1441 c.FileFromFS("fs/file.go", fs)1442 })1443}14441445```14461447### Serving data from reader14481449```go1450func main() {1451 router := gin.Default()1452 router.GET("/someDataFromReader", func(c *gin.Context) {1453 response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")1454 if err != nil || response.StatusCode != http.StatusOK {1455 c.Status(http.StatusServiceUnavailable)1456 return1457 }14581459 reader := response.Body1460 defer reader.Close()1461 contentLength := response.ContentLength1462 contentType := response.Header.Get("Content-Type")14631464 extraHeaders := map[string]string{1465 "Content-Disposition": `attachment; filename="gopher.png"`,1466 }14671468 c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)1469 })1470 router.Run(":8080")1471}1472```14731474### HTML rendering1475

feat(fs): Implement loading HTML from http.FileSystem (#4053)sunshineplanbefore adoption71496ab

line 1476why, one step back
1476Using LoadHTMLGlob() or LoadHTMLFiles() or LoadHTMLFS()

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1477–1478why, one step back
1477
1478```go

feat(fs): Implement loading HTML from http.FileSystem (#4053)sunshineplanbefore adoption71496ab

lines 1479–1481why, one step back
1479//go:embed templates/*
1480var templates embed.FS1481

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1482–1485why, one step back
1482func main() {
1483 router := gin.Default()1484 router.LoadHTMLGlob("templates/*")1485 //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")

feat(fs): Implement loading HTML from http.FileSystem (#4053)sunshineplanbefore adoption71496ab

lines 1486–1488why, one step back
1486 //router.LoadHTMLFS(http.Dir("templates"), "template1.html", "template2.html")
1487 //or1488 //router.LoadHTMLFS(http.FS(templates), "templates/template1.html", "templates/template2.html")

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1489–1578why, one step back
1489 router.GET("/index", func(c *gin.Context) {
1490 c.HTML(http.StatusOK, "index.tmpl", gin.H{1491 "title": "Main website",1492 })1493 })1494 router.Run(":8080")1495}1496```14971498templates/index.tmpl14991500```html1501<html>1502 <h1>1503 {{ .title }}1504 </h1>1505</html>1506```15071508Using templates with same name in different directories15091510```go1511func main() {1512 router := gin.Default()1513 router.LoadHTMLGlob("templates/**/*")1514 router.GET("/posts/index", func(c *gin.Context) {1515 c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{1516 "title": "Posts",1517 })1518 })1519 router.GET("/users/index", func(c *gin.Context) {1520 c.HTML(http.StatusOK, "users/index.tmpl", gin.H{1521 "title": "Users",1522 })1523 })1524 router.Run(":8080")1525}1526```15271528templates/posts/index.tmpl15291530```html1531{{ define "posts/index.tmpl" }}1532<html><h1>1533 {{ .title }}1534</h1>1535<p>Using posts/index.tmpl</p>1536</html>1537{{ end }}1538```15391540templates/users/index.tmpl15411542```html1543{{ define "users/index.tmpl" }}1544<html><h1>1545 {{ .title }}1546</h1>1547<p>Using users/index.tmpl</p>1548</html>1549{{ end }}1550```15511552#### Custom Template renderer15531554You can also use your own html template render15551556```go1557import "html/template"15581559func main() {1560 router := gin.Default()1561 html := template.Must(template.ParseFiles("file1", "file2"))1562 router.SetHTMLTemplate(html)1563 router.Run(":8080")1564}1565```15661567#### Custom Delimiters15681569You may use custom delims15701571```go1572 r := gin.Default()1573 r.Delims("{[{", "}]}")1574 r.LoadHTMLGlob("/path/to/templates")1575```15761577#### Custom Template Funcs1578

docs: Fixing English grammar mistakes and awkward sentence structure in doc/doc.md (#4207)Adlai Bridson-Boyczukbefore adoption1b53a47

line 1579why, one step back
1579See the detailed [example code](https://github.com/gin-gonic/examples/tree/master/template).

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1580–1630why, one step back
1580
1581main.go15821583```go1584import (1585 "fmt"1586 "html/template"1587 "net/http"1588 "time"15891590 "github.com/gin-gonic/gin"1591)15921593func formatAsDate(t time.Time) string {1594 year, month, day := t.Date()1595 return fmt.Sprintf("%d/%02d/%02d", year, month, day)1596}15971598func main() {1599 router := gin.Default()1600 router.Delims("{[{", "}]}")1601 router.SetFuncMap(template.FuncMap{1602 "formatAsDate": formatAsDate,1603 })1604 router.LoadHTMLFiles("./testdata/template/raw.tmpl")16051606 router.GET("/raw", func(c *gin.Context) {1607 c.HTML(http.StatusOK, "raw.tmpl", gin.H{1608 "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),1609 })1610 })16111612 router.Run(":8080")1613}16141615```16161617raw.tmpl16181619```html1620Date: {[{.now | formatAsDate}]}1621```16221623Result:16241625```sh1626Date: 2017/07/011627```16281629### Multitemplate1630

docs: Fixing English grammar mistakes and awkward sentence structure in doc/doc.md (#4207)Adlai Bridson-Boyczukbefore adoption1b53a47

line 1631why, one step back
1631Gin allows only one html.Template by default. Check [a multitemplate render](https://github.com/gin-contrib/multitemplate) for using features like go 1.6 `block template`.

fix(form): Set default value for form fields (#4047)Ahmad Saeed Godabefore adoption28e57f5

lines 1632–2179why, one step back
1632
1633### Redirects16341635Issuing a HTTP redirect is easy. Both internal and external locations are supported.16361637```go1638r.GET("/test", func(c *gin.Context) {1639 c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")1640})1641```16421643Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444)16441645```go1646r.POST("/test", func(c *gin.Context) {1647 c.Redirect(http.StatusFound, "/foo")1648})1649```16501651Issuing a Router redirect, use `HandleContext` like below.16521653``` go1654r.GET("/test", func(c *gin.Context) {1655 c.Request.URL.Path = "/test2"1656 r.HandleContext(c)1657})1658r.GET("/test2", func(c *gin.Context) {1659 c.JSON(http.StatusOK, gin.H{"hello": "world"})1660})1661```16621663### Custom Middleware16641665```go1666func Logger() gin.HandlerFunc {1667 return func(c *gin.Context) {1668 t := time.Now()16691670 // Set example variable1671 c.Set("example", "12345")16721673 // before request16741675 c.Next()16761677 // after request1678 latency := time.Since(t)1679 log.Print(latency)16801681 // access the status we are sending1682 status := c.Writer.Status()1683 log.Println(status)1684 }1685}16861687func main() {1688 r := gin.New()1689 r.Use(Logger())16901691 r.GET("/test", func(c *gin.Context) {1692 example := c.MustGet("example").(string)16931694 // it would print: "12345"1695 log.Println(example)1696 })16971698 // Listen and serve on 0.0.0.0:80801699 r.Run(":8080")1700}1701```17021703### Using BasicAuth() middleware17041705```go1706// simulate some private data1707var secrets = gin.H{1708 "foo": gin.H{"email": "foo@bar.com", "phone": "123433"},1709 "austin": gin.H{"email": "austin@example.com", "phone": "666"},1710 "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},1711}17121713func main() {1714 r := gin.Default()17151716 // Group using gin.BasicAuth() middleware1717 // gin.Accounts is a shortcut for map[string]string1718 authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{1719 "foo": "bar",1720 "austin": "1234",1721 "lena": "hello2",1722 "manu": "4321",1723 }))17241725 // /admin/secrets endpoint1726 // hit "localhost:8080/admin/secrets1727 authorized.GET("/secrets", func(c *gin.Context) {1728 // get user, it was set by the BasicAuth middleware1729 user := c.MustGet(gin.AuthUserKey).(string)1730 if secret, ok := secrets[user]; ok {1731 c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})1732 } else {1733 c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})1734 }1735 })17361737 // Listen and serve on 0.0.0.0:80801738 r.Run(":8080")1739}1740```17411742### Goroutines inside a middleware17431744When 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.17451746```go1747func main() {1748 r := gin.Default()17491750 r.GET("/long_async", func(c *gin.Context) {1751 // create copy to be used inside the goroutine1752 cCp := c.Copy()1753 go func() {1754 // simulate a long task with time.Sleep(). 5 seconds1755 time.Sleep(5 * time.Second)17561757 // note that you are using the copied context "cCp", IMPORTANT1758 log.Println("Done! in path " + cCp.Request.URL.Path)1759 }()1760 })17611762 r.GET("/long_sync", func(c *gin.Context) {1763 // simulate a long task with time.Sleep(). 5 seconds1764 time.Sleep(5 * time.Second)17651766 // since we are NOT using a goroutine, we do not have to copy the context1767 log.Println("Done! in path " + c.Request.URL.Path)1768 })17691770 // Listen and serve on 0.0.0.0:80801771 r.Run(":8080")1772}1773```17741775### Custom HTTP configuration17761777Use `http.ListenAndServe()` directly, like this:17781779```go1780func main() {1781 router := gin.Default()1782 http.ListenAndServe(":8080", router)1783}1784```17851786or17871788```go1789func main() {1790 router := gin.Default()17911792 s := &http.Server{1793 Addr: ":8080",1794 Handler: router,1795 ReadTimeout: 10 * time.Second,1796 WriteTimeout: 10 * time.Second,1797 MaxHeaderBytes: 1 << 20,1798 }1799 s.ListenAndServe()1800}1801```18021803### Support Let's Encrypt18041805example for 1-line LetsEncrypt HTTPS servers.18061807```go1808package main18091810import (1811 "log"1812 "net/http"18131814 "github.com/gin-gonic/autotls"1815 "github.com/gin-gonic/gin"1816)18171818func main() {1819 r := gin.Default()18201821 // Ping handler1822 r.GET("/ping", func(c *gin.Context) {1823 c.String(http.StatusOK, "pong")1824 })18251826 log.Fatal(autotls.Run(r, "example1.com", "example2.com"))1827}1828```18291830example for custom autocert manager.18311832```go1833package main18341835import (1836 "log"1837 "net/http"18381839 "github.com/gin-gonic/autotls"1840 "github.com/gin-gonic/gin"1841 "golang.org/x/crypto/acme/autocert"1842)18431844func main() {1845 r := gin.Default()18461847 // Ping handler1848 r.GET("/ping", func(c *gin.Context) {1849 c.String(http.StatusOK, "pong")1850 })18511852 m := autocert.Manager{1853 Prompt: autocert.AcceptTOS,1854 HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),1855 Cache: autocert.DirCache("/var/www/.cache"),1856 }18571858 log.Fatal(autotls.RunWithManager(r, &m))1859}1860```18611862### Run multiple service using Gin18631864See the [question](https://github.com/gin-gonic/gin/issues/346) and try the following example:18651866```go1867package main18681869import (1870 "log"1871 "net/http"1872 "time"18731874 "github.com/gin-gonic/gin"1875 "golang.org/x/sync/errgroup"1876)18771878var (1879 g errgroup.Group1880)18811882func router01() http.Handler {1883 e := gin.New()1884 e.Use(gin.Recovery())1885 e.GET("/", func(c *gin.Context) {1886 c.JSON(1887 http.StatusOK,1888 gin.H{1889 "code": http.StatusOK,1890 "error": "Welcome server 01",1891 },1892 )1893 })18941895 return e1896}18971898func router02() http.Handler {1899 e := gin.New()1900 e.Use(gin.Recovery())1901 e.GET("/", func(c *gin.Context) {1902 c.JSON(1903 http.StatusOK,1904 gin.H{1905 "code": http.StatusOK,1906 "error": "Welcome server 02",1907 },1908 )1909 })19101911 return e1912}19131914func main() {1915 server01 := &http.Server{1916 Addr: ":8080",1917 Handler: router01(),1918 ReadTimeout: 5 * time.Second,1919 WriteTimeout: 10 * time.Second,1920 }19211922 server02 := &http.Server{1923 Addr: ":8081",1924 Handler: router02(),1925 ReadTimeout: 5 * time.Second,1926 WriteTimeout: 10 * time.Second,1927 }19281929 g.Go(func() error {1930 err := server01.ListenAndServe()1931 if err != nil && err != http.ErrServerClosed {1932 log.Fatal(err)1933 }1934 return err1935 })19361937 g.Go(func() error {1938 err := server02.ListenAndServe()1939 if err != nil && err != http.ErrServerClosed {1940 log.Fatal(err)1941 }1942 return err1943 })19441945 if err := g.Wait(); err != nil {1946 log.Fatal(err)1947 }1948}1949```19501951### Graceful shutdown or restart19521953There 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.19541955#### Third-party packages19561957We 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.19581959```go1960router := gin.Default()1961router.GET("/", handler)1962// [...]1963endless.ListenAndServe(":4242", router)1964```19651966Alternatives:19671968* [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers.1969* [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server.1970* [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully.19711972#### Manually19731974In 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).19751976```go1977// +build go1.819781979package main19801981import (1982 "context"1983 "log"1984 "net/http"1985 "os"1986 "os/signal"1987 "syscall"1988 "time"19891990 "github.com/gin-gonic/gin"1991)19921993func main() {1994 router := gin.Default()1995 router.GET("/", func(c *gin.Context) {1996 time.Sleep(5 * time.Second)1997 c.String(http.StatusOK, "Welcome Gin Server")1998 })19992000 srv := &http.Server{

The first 2,000 of 2,636 lines.