Skip to content
Myr

docs: reorganize doc.md TOC into thematic groups (#4579)

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

The flat TOC under a single "API Examples" heading made it hard to scan and find relevant content. Reorganize 40+ sections into 7 logical groups (Routing, Middleware, Logging, Request Binding & Validation, Response Rendering, Server Configuration, Testing) with description lines for each group. Move scattered sections into their correct groups and fix the "avoid-loging-query-strings" anchor typo.

authored by Bo-Yi Wu · committed by GitHub · parent 3e44fdc · Browse files · 1 file+581 added−551 removed
This commit

State

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

Trailers

  • Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>

Diff stats

1 file+581 added−551 removed

  • other:+581 added−551 removed

1 file+581 added−551 removed

modified:docs/doc.md+581 added-551 removed
2 unmodified lines
3## 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)7 - [Build without MsgPack rendering feature](#build-without-msgpack-rendering-feature)8- [Routing](#routing)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)
2 unmodified lines
15 - [Upload files](#upload-files)16 - [Single file](#single-file)17 - [Multiple files](#multiple-files)18 - [Grouping routes](#grouping-routes)19 - [Redirects](#redirects)20- [Middleware](#middleware)21 - [Blank Gin without middleware by default](#blank-gin-without-middleware-by-default)22 - [Using middleware](#using-middleware)23 - [Custom Middleware](#custom-middleware)24 - [Custom Recovery behavior](#custom-recovery-behavior)25 - [Using BasicAuth() middleware](#using-basicauth-middleware)26 - [Goroutines inside a middleware](#goroutines-inside-a-middleware)27- [Logging](#logging)28 - [How to write log file](#how-to-write-log-file)29 - [Custom Log Format](#custom-log-format)30 - [Skip logging](#skip-logging)31 - [Controlling Log output coloring](#controlling-log-output-coloring)25 - [Avoid logging query strings](#avoid-loging-query-strings)32 - [Avoid logging query strings](#avoid-logging-query-strings)33 - [Define format for the log of routes](#define-format-for-the-log-of-routes)34- [Request Binding & Validation](#request-binding--validation)35 - [Model binding and validation](#model-binding-and-validation)36 - [Custom Validators](#custom-validators)37 - [Only Bind Query String](#only-bind-query-string)38 - [Bind Query String or Post Data](#bind-query-string-or-post-data)39 - [Bind default value if none provided](#bind-default-value-if-none-provided)31 - [Collection format for arrays](#collection-format-for-arrays)40 - [Collection format for arrays](#collection-format-for-arrays)41 - [Bind Uri](#bind-uri)42 - [Bind custom unmarshaler](#bind-custom-unmarshaler)43 - [Bind Header](#bind-header)44 - [Bind HTML checkboxes](#bind-html-checkboxes)45 - [Multipart/Urlencoded binding](#multiparturlencoded-binding)46 - [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct)47 - [Try to bind body into different structs](#try-to-bind-body-into-different-structs)48 - [Bind form-data request with custom struct and custom tag](#bind-form-data-request-with-custom-struct-and-custom-tag)49- [Response Rendering](#response-rendering)50 - [XML, JSON, YAML, TOML and ProtoBuf rendering](#xml-json-yaml-toml-and-protobuf-rendering)51 - [SecureJSON](#securejson)52 - [JSONP](#jsonp)53 - [AsciiJSON](#asciijson)
5 unmodified lines
59 - [Custom Template renderer](#custom-template-renderer)60 - [Custom Delimiters](#custom-delimiters)61 - [Custom Template Funcs](#custom-template-funcs)62 - [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)63 - [Build a single binary with templates](#build-a-single-binary-with-templates)64- [Server Configuration](#server-configuration)65 - [Custom HTTP configuration](#custom-http-configuration)66 - [Custom json codec at runtime](#custom-json-codec-at-runtime)67 - [Support Let's Encrypt](#support-lets-encrypt)68 - [Run multiple service using Gin](#run-multiple-service-using-gin)69 - [Graceful shutdown or restart](#graceful-shutdown-or-restart)70 - [Third-party packages](#third-party-packages)71 - [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)72 - [http2 server push](#http2-server-push)65 - [Define format for the log of routes](#define-format-for-the-log-of-routes)73 - [Set and get a cookie](#set-and-get-a-cookie)67 - [Custom json codec at runtime](#custom-json-codec-at-runtime)68- [Don't trust all proxies](#dont-trust-all-proxies)74 - [Don't trust all proxies](#dont-trust-all-proxies)75- [Testing](#testing)7677You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples).7879## Build tags8081### Build with json replacement82
13 unmodified lines
9697[sonic](https://github.com/bytedance/sonic)9899```sh92$ go build -tags=sonic .100go build -tags=sonic .101```102103### Build without `MsgPack` rendering feature104
4 unmodified lines
109```110111This is useful to reduce the binary size of executable files. See the [detail information](https://github.com/gin-gonic/gin/pull/1852).112105## API Examples113## Routing114107You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples).115> Learn how to define routes, handle parameters, and organize endpoints.116117### Using GET, POST, PUT, PATCH, DELETE and OPTIONS118119```go
248 unmodified lines
368 router.Run(":8080")369}370```371372### Redirects373374Issuing a HTTP redirect is easy. Both internal and external locations are supported.375376```go377r.GET("/test", func(c *gin.Context) {378 c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")379})380```381382Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444)383384```go385r.POST("/test", func(c *gin.Context) {386 c.Redirect(http.StatusFound, "/foo")387})388```389390Issuing a Router redirect, use `HandleContext` like below.391392```go393r.GET("/test", func(c *gin.Context) {394 c.Request.URL.Path = "/test2"395 r.HandleContext(c)396})397r.GET("/test2", func(c *gin.Context) {398 c.JSON(http.StatusOK, gin.H{"hello": "world"})399})400```401402## Middleware403404> Configure middleware for request processing, authentication, and error recovery.405406### Blank Gin without middleware by default407408Use409
48 unmodified lines
458 r.Run(":8080")459}460```461462### Custom Middleware463464```go465func Logger() gin.HandlerFunc {466 return func(c *gin.Context) {467 t := time.Now()468469 // Set example variable470 c.Set("example", "12345")471472 // before request473474 c.Next()475476 // after request477 latency := time.Since(t)478 log.Print(latency)479480 // access the status we are sending481 status := c.Writer.Status()482 log.Println(status)483 }484}485486func main() {487 r := gin.New()488 r.Use(Logger())489490 r.GET("/test", func(c *gin.Context) {491 example := c.MustGet("example").(string)492493 // it would print: "12345"494 log.Println(example)495 })496497 // Listen and serve on 0.0.0.0:8080498 r.Run(":8080")499}500```501502### Custom Recovery behavior503504```go505func main() {
26 unmodified lines
532 r.Run(":8080")533}534```535536### Using BasicAuth() middleware537538```go539// simulate some private data540var secrets = gin.H{541 "foo": gin.H{"email": "foo@bar.com", "phone": "123433"},542 "austin": gin.H{"email": "austin@example.com", "phone": "666"},543 "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},544}545546func main() {547 r := gin.Default()548549 // Group using gin.BasicAuth() middleware550 // gin.Accounts is a shortcut for map[string]string551 authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{552 "foo": "bar",553 "austin": "1234",554 "lena": "hello2",555 "manu": "4321",556 }))557558 // /admin/secrets endpoint559 // hit "localhost:8080/admin/secrets560 authorized.GET("/secrets", func(c *gin.Context) {561 // get user, it was set by the BasicAuth middleware562 user := c.MustGet(gin.AuthUserKey).(string)563 if secret, ok := secrets[user]; ok {564 c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})565 } else {566 c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})567 }568 })569570 // Listen and serve on 0.0.0.0:8080571 r.Run(":8080")572}573```574575### Goroutines inside a middleware576577When 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.578579```go580func main() {581 r := gin.Default()582583 r.GET("/long_async", func(c *gin.Context) {584 // create copy to be used inside the goroutine585 cCp := c.Copy()586 go func() {587 // simulate a long task with time.Sleep(). 5 seconds588 time.Sleep(5 * time.Second)589590 // note that you are using the copied context "cCp", IMPORTANT591 log.Println("Done! in path " + cCp.Request.URL.Path)592 }()593 })594595 r.GET("/long_sync", func(c *gin.Context) {596 // simulate a long task with time.Sleep(). 5 seconds597 time.Sleep(5 * time.Second)598599 // since we are NOT using a goroutine, we do not have to copy the context600 log.Println("Done! in path " + c.Request.URL.Path)601 })602603 // Listen and serve on 0.0.0.0:8080604 r.Run(":8080")605}606```607608## Logging609610> Control log output, formatting, and filtering.611612### How to write log file613614```go615func main() {
11 unmodified lines
627 router.GET("/ping", func(c *gin.Context) {628 c.String(http.StatusOK, "pong")629 })630473   router.Run(":8080")631 router.Run(":8080")632}633```634635### Custom Log Format
119 unmodified lines
755756```go757func main() {758 router := gin.New()601 759760 // SkipQueryString indicates that the logger should not log the query string.761 // For example, /path?q=1 will be logged as /path762 loggerConfig := gin.LoggerConfig{SkipQueryString: true}605 763764 router.Use(gin.LoggerWithConfig(loggerConfig))765}766```767768### Define format for the log of routes769770The default log of routes is:771772```sh773[GIN-debug] POST /foo --> main.main.func1 (3 handlers)774[GIN-debug] GET /bar --> main.main.func2 (3 handlers)775[GIN-debug] GET /status --> main.main.func3 (3 handlers)776```777778If 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`.779In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs.780781```go782import (783 "log"784 "net/http"785786 "github.com/gin-gonic/gin"787)788789func main() {790 r := gin.Default()791 gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {792 log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers)793 }794795 r.POST("/foo", func(c *gin.Context) {796 c.JSON(http.StatusOK, "foo")797 })798799 r.GET("/bar", func(c *gin.Context) {800 c.JSON(http.StatusOK, "bar")801 })802803 r.GET("/status", func(c *gin.Context) {804 c.JSON(http.StatusOK, "ok")805 })806807 // Listen and Server in http://0.0.0.0:8080808 r.Run()809}810```811812## Request Binding & Validation813814> Bind and validate request data from query strings, forms, JSON, and more.815816### Model binding and validation817818To 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).819
268 unmodified lines
1088```sh1089curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033&unixMilliTime=1562400033001&unixMicroTime=1562400033000012"1090```10918861092### Bind default value if none provided10931094If 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:10951096```go1097package main10981099import (895 "net/http"1100 "net/http"1101897 "github.com/gin-gonic/gin"1102 "github.com/gin-gonic/gin"1103)11041105type 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"`1106 Name string `form:"name,default=William"`1107 Age int `form:"age,default=10"`1108 Friends []string `form:"friends,default=Will;Bill"`1109 Addresses [2]string `form:"addresses,default=foo bar" collection_format:"ssv"`1110 LapTimes []int `form:"lap_times,default=1;2;3" collection_format:"csv"`1111}11121113func 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")1114 g := gin.Default()1115 g.POST("/person", func(c *gin.Context) {1116 var req Person1117 if err := c.ShouldBindQuery(&req); err != nil {1118 c.JSON(http.StatusBadRequest, err)1119 return1120 }1121 c.JSON(http.StatusOK, req)1122 })1123 _ = g.Run("localhost:8080")1124}1125```1126922```1127```sh1128curl -X POST http://localhost:8080/person1129{"Name":"William","Age":10,"Friends":["Will","Bill"],"Colors":["red","blue"],"LapTimes":[1,2,3]}1130```11311132NOTE: For default [collection values](#collection-format-for-arrays), the following rules apply:11331134- Since commas are used to delimit tag options, they are not supported within a default value and will result in undefined behavior1135- For the collection formats "multi" and "csv", a semicolon should be used in place of a comma to delimit default values1136- Since semicolons are used to delimit default values for "multi" and "csv", they are not supported within a default value for "multi" and "csv"11379321138#### Collection format for arrays11391140| Format | Description | Example |1141| --------------- | --------------------------------------------------------- | ----------------------- |
6 unmodified lines
1148```go1149package main11501151import (947 "log"948 "time"949 "github.com/gin-gonic/gin"1152 "log"1153 "time"1154 "github.com/gin-gonic/gin"1155)11561157type 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"`1158 Name string `form:"name"`1159 Addresses []string `form:"addresses" collection_format:"csv"`1160 Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`1161 CreateTime time.Time `form:"createTime" time_format:"unixNano"`1162 UnixTime time.Time `form:"unixTime" time_format:"unix"`1163}11641165func main() {961 route := gin.Default()962 route.GET("/testing", startPage)963 route.Run(":8085")1166 route := gin.Default()1167 route.GET("/testing", startPage)1168 route.Run(":8085")1169}1170func 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#L481171 var person Person1172 // If `GET`, only `Form` binding engine (`query`) used.1173 // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).1174 // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L481175 if c.ShouldBind(&person) == nil {1176 log.Println(person.Name)1177 log.Println(person.Addresses)1178 log.Println(person.Birthday)1179 log.Println(person.CreateTime)1180 log.Println(person.UnixTime)1181 }977 c.String(200, "Success")1182 c.String(200, "Success")1183}1184```11851186Test it with:11871188```sh983$ curl -X GET "localhost:8085/testing?name=appleboy&addresses=foo,bar&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"1189curl -X GET "localhost:8085/testing?name=appleboy&addresses=foo,bar&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"1190```11911192### Bind Uri1193
76 unmodified lines
12701271```sh1272curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02'1273```12741275Result12761277```sh1278{"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]}1279```12801281Note:12821283- 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.1284- 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.12851286---
38 unmodified lines
13251326```sh1327curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02'1328```13291330Result13311332```sh1333{"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]}1334```13351336Note:13371338- 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.1339- If a type returns an error from its implementation of `BindUnmarshaler`, gin will stop binding and return the error to the client.13401341### Bind Header
63 unmodified lines
1405form.html14061407```html1408<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">1409 <p>Check some colors</p>1410 <label for="red">Red</label>1411 <input type="checkbox" name="colors[]" value="red" id="red" />1412 <label for="green">Green</label>1413 <input type="checkbox" name="colors[]" value="green" id="green" />1414 <label for="blue">Blue</label>1415 <input type="checkbox" name="colors[]" value="blue" id="blue" />1416 <input type="submit" />1417</form>1418```14191420result:14211422```json1211{"color":["red","green","blue"]}1423{ "color": ["red", "green", "blue"] }1424```14251426### Multipart/Urlencoded binding1427
38 unmodified lines
1466```sh1467curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile1468```14691470### Bind form-data request with custom struct14711472The follow example using custom struct:14731474```go1475type StructA struct {1476 FieldA string `form:"field_a"`1477}14781479type StructB struct {1480 NestedStruct StructA1481 FieldB string `form:"field_b"`1482}14831484type StructC struct {1485 NestedStructPointer *StructA1486 FieldC string `form:"field_c"`1487}14881489type StructD struct {1490 NestedAnonyStruct struct {1491 FieldX string `form:"field_x"`1492 }1493 FieldD string `form:"field_d"`1494}14951496func GetDataB(c *gin.Context) {1497 var b StructB1498 c.Bind(&b)1499 c.JSON(http.StatusOK, gin.H{1500 "a": b.NestedStruct,1501 "b": b.FieldB,1502 })1503}15041505func GetDataC(c *gin.Context) {1506 var b StructC1507 c.Bind(&b)1508 c.JSON(http.StatusOK, gin.H{1509 "a": b.NestedStructPointer,1510 "c": b.FieldC,1511 })1512}15131514func GetDataD(c *gin.Context) {1515 var b StructD1516 c.Bind(&b)1517 c.JSON(http.StatusOK, gin.H{1518 "x": b.NestedAnonyStruct,1519 "d": b.FieldD,1520 })1521}15221523func main() {1524 r := gin.Default()1525 r.GET("/getb", GetDataB)1526 r.GET("/getc", GetDataC)1527 r.GET("/getd", GetDataD)15281529 r.Run()1530}1531```15321533Using the command `curl` command result:15341535```sh1536$ curl "http://localhost:8080/getb?field_a=hello&field_b=world"1537{"a":{"FieldA":"hello"},"b":"world"}1538$ curl "http://localhost:8080/getc?field_a=hello&field_c=world"1539{"a":{"FieldA":"hello"},"c":"world"}1540$ curl "http://localhost:8080/getd?field_x=hello&field_d=world"1541{"d":"world","x":{"FieldX":"hello"}}1542```15431544### Try to bind body into different structs15451546The normal methods for binding request body consumes `c.Request.Body` and they1547cannot be called multiple times.15481549```go1550type formA struct {1551 Foo string `json:"foo" xml:"foo" binding:"required"`1552}15531554type formB struct {1555 Bar string `json:"bar" xml:"bar" binding:"required"`1556}15571558func SomeHandler(c *gin.Context) {1559 objA := formA{}1560 objB := formB{}1561 // Calling c.ShouldBind consumes c.Request.Body and it cannot be reused.1562 if errA := c.ShouldBind(&objA); errA == nil {1563 c.String(http.StatusOK, `the body should be formA`)1564 // Always an error is occurred by this because c.Request.Body is EOF now.1565 } else if errB := c.ShouldBind(&objB); errB == nil {1566 c.String(http.StatusOK, `the body should be formB`)1567 } else {1568 ...1569 }1570}1571```15721573For this, you can use `c.ShouldBindBodyWith` or shortcuts.15741575- `c.ShouldBindBodyWithJSON` is a shortcut for c.ShouldBindBodyWith(obj, binding.JSON).1576- `c.ShouldBindBodyWithXML` is a shortcut for c.ShouldBindBodyWith(obj, binding.XML).1577- `c.ShouldBindBodyWithYAML` is a shortcut for c.ShouldBindBodyWith(obj, binding.YAML).1578- `c.ShouldBindBodyWithTOML` is a shortcut for c.ShouldBindBodyWith(obj, binding.TOML).15791580```go1581func SomeHandler(c *gin.Context) {1582 objA := formA{}1583 objB := formB{}1584 // This reads c.Request.Body and stores the result into the context.1585 if errA := c.ShouldBindBodyWith(&objA, binding.Form); errA == nil {1586 c.String(http.StatusOK, `the body should be formA`)1587 // At this time, it reuses body stored in the context.1588 } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {1589 c.String(http.StatusOK, `the body should be formB JSON`)1590 // And it can accepts other formats1591 } else if errB2 := c.ShouldBindBodyWithXML(&objB); errB2 == nil {1592 c.String(http.StatusOK, `the body should be formB XML`)1593 } else {1594 ...1595 }1596}1597```159815991. `c.ShouldBindBodyWith` stores body into the context before binding. This has1600 a slight impact to performance, so you should not use this method if you are1601 enough to call binding at once.16022. This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`,1603 `ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`,1604 can be called by `c.ShouldBind()` multiple times without any damage to1605 performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)).16061607### Bind form-data request with custom struct and custom tag16081609```go1610const (1611 customerTag = "url"1612 defaultMemory = 32 << 201613)16141615type customerBinding struct {}16161617func (customerBinding) Name() string {1618 return "form"1619}16201621func (customerBinding) Bind(req *http.Request, obj any) error {1622 if err := req.ParseForm(); err != nil {1623 return err1624 }1625 if err := req.ParseMultipartForm(defaultMemory); err != nil {1626 if err != http.ErrNotMultipart {1627 return err1628 }1629 }1630 if err := binding.MapFormWithTag(obj, req.Form, customerTag); err != nil {1631 return err1632 }1633 return validate(obj)1634}16351636func validate(obj any) error {1637 if binding.Validator == nil {1638 return nil1639 }1640 return binding.Validator.ValidateStruct(obj)1641}16421643// Now we can do this!!!1644// FormA is an external type that we can't modify it's tag1645type FormA struct {1646 FieldA string `url:"field_a"`1647}16481649func ListHandler(s *Service) func(ctx *gin.Context) {1650 return func(ctx *gin.Context) {1651 var urlBinding = customerBinding{}1652 var opt FormA1653 err := ctx.MustBindWith(&opt, urlBinding)1654 if err != nil {1655 ...1656 }1657 ...1658 }1659}1660```16611662## Response Rendering16631664> Render responses in various formats including JSON, XML, HTML, and more.16651666### XML, JSON, YAML, TOML and ProtoBuf rendering16671668```go1669func main() {
236 unmodified lines
1906templates/index.tmpl19071908```html1909<html>1502 <h1>1503 {{ .title }}1504 </h1>1910 <h1>{{ .title }}</h1>1911</html>1912```19131914Using templates with same name in different directories
19 unmodified lines
1934templates/posts/index.tmpl19351936```html1937{{ define "posts/index.tmpl" }}1532<html><h1>1533 {{ .title }}1534</h1>1535<p>Using posts/index.tmpl</p>1938<html>1939 <h1>{{ .title }}</h1>1940 <p>Using posts/index.tmpl</p>1941</html>1942{{ end }}1943```19441945templates/users/index.tmpl19461947```html1948{{ define "users/index.tmpl" }}1544<html><h1>1545 {{ .title }}1546</h1>1547<p>Using users/index.tmpl</p>1949<html>1950 <h1>{{ .title }}</h1>1951 <p>Using users/index.tmpl</p>1952</html>1953{{ end }}1954```1955
77 unmodified lines
2033### Multitemplate20342035Gin 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`.20361633### Redirects2037### Build a single binary with templates20381635Issuing a HTTP redirect is easy. Both internal and external locations are supported.2039You can build a server into a single binary containing templates by using the [embed](https://pkg.go.dev/embed) package.20402041```go1638r.GET("/test", func(c *gin.Context) {1639 c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")1640})1641```2042package main20431643Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444)2044import (2045 "embed"2046 "html/template"2047 "net/http"20481645```go1646r.POST("/test", func(c *gin.Context) {1647 c.Redirect(http.StatusFound, "/foo")1648})1649```2049 "github.com/gin-gonic/gin"2050)20511651Issuing a Router redirect, use `HandleContext` like below.2052//go:embed assets/* templates/*2053var f embed.FS20541653``` 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}16862055func main() {1688 r := gin.New()1689 r.Use(Logger())2056 router := gin.Default()2057 templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl"))2058 router.SetHTMLTemplate(templ)20591691 r.GET("/test", func(c *gin.Context) {1692 example := c.MustGet("example").(string)2060 // example: /public/assets/images/example.png2061 router.StaticFS("/public", http.FS(f))20621694 // it would print: "12345"1695 log.Println(example)2063 router.GET("/", func(c *gin.Context) {2064 c.HTML(http.StatusOK, "index.tmpl", gin.H{2065 "title": "Main website",2066 })2067 })20681698 // Listen and serve on 0.0.0.0:80801699 r.Run(":8080")1700}1701```2069 router.GET("/foo", func(c *gin.Context) {2070 c.HTML(http.StatusOK, "bar.tmpl", gin.H{2071 "title": "Foo website",2072 })2073 })20741703### 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 }2075 router.GET("favicon.ico", func(c *gin.Context) {2076 file, _ := f.ReadFile("assets/favicon.ico")2077 c.Data(2078 http.StatusOK,2079 "image/x-icon",2080 file,2081 )2082 })20831737 // Listen and serve on 0.0.0.0:80801738 r.Run(":8080")2084 router.Run(":8080")2085}2086```20871742### Goroutines inside a middleware2088See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary/example02` directory.20891744When 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.2090## Server Configuration20911746```go1747func main() {1748 r := gin.Default()2092> Configure HTTP servers, TLS, proxies, and runtime settings.20931750 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```17742094### Custom HTTP configuration20952096Use `http.ListenAndServe()` directly, like this:2097
20 unmodified lines
2118 s.ListenAndServe()2119}2120```21212122### Custom json codec at runtime21232124Gin support custom json serialization and deserialization logic without using compile tags.212521261. Define a custom struct implements the `json.Core` interface.212721282. Before your engine starts, assign values to `json.API` using the custom struct.21292130```go2131package main21322133import (2134 "io"21352136 "github.com/gin-gonic/gin"2137 "github.com/gin-gonic/gin/codec/json"2138 jsoniter "github.com/json-iterator/go"2139)21402141var customConfig = jsoniter.Config{2142 EscapeHTML: true,2143 SortMapKeys: true,2144 ValidateJsonRawMessage: true,2145}.Froze()21462147// implement api.JsonApi2148type customJsonApi struct {2149}21502151func (j customJsonApi) Marshal(v any) ([]byte, error) {2152 return customConfig.Marshal(v)2153}21542155func (j customJsonApi) Unmarshal(data []byte, v any) error {2156 return customConfig.Unmarshal(data, v)2157}21582159func (j customJsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {2160 return customConfig.MarshalIndent(v, prefix, indent)2161}21622163func (j customJsonApi) NewEncoder(writer io.Writer) json.Encoder {2164 return customConfig.NewEncoder(writer)2165}21662167func (j customJsonApi) NewDecoder(reader io.Reader) json.Decoder {2168 return customConfig.NewDecoder(reader)2169}21702171func main() {2172 //Replace the default json api2173 json.API = customJsonApi{}21742175 //Start your gin engine2176 router := gin.Default()2177 router.Run(":8080")2178}2179```21802181### Support Let's Encrypt21822183example for 1-line LetsEncrypt HTTPS servers.2184
157 unmodified lines
2342```23432344Alternatives:23451968* [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.2346- [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers.2347- [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server.2348- [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully.23492350#### Manually23512352In 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).
57 unmodified lines
2410 log.Println("Server exiting")2411}2412```24132036### Build a single binary with templates20372038You can build a server into a single binary containing templates by using the [embed](https://pkg.go.dev/embed) package.20392040```go2041package main20422043import (2044 "embed"2045 "html/template"2046 "net/http"20472048 "github.com/gin-gonic/gin"2049)20502051//go:embed assets/* templates/*2052var f embed.FS20532054func main() {2055 router := gin.Default()2056 templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl"))2057 router.SetHTMLTemplate(templ)20582059 // example: /public/assets/images/example.png2060 router.StaticFS("/public", http.FS(f))20612062 router.GET("/", func(c *gin.Context) {2063 c.HTML(http.StatusOK, "index.tmpl", gin.H{2064 "title": "Main website",2065 })2066 })20672068 router.GET("/foo", func(c *gin.Context) {2069 c.HTML(http.StatusOK, "bar.tmpl", gin.H{2070 "title": "Foo website",2071 })2072 })20732074 router.GET("favicon.ico", func(c *gin.Context) {2075 file, _ := f.ReadFile("assets/favicon.ico")2076 c.Data(2077 http.StatusOK,2078 "image/x-icon",2079 file,2080 )2081 })20822083 router.Run(":8080")2084}2085```20862087See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary/example02` directory.20882089### Bind form-data request with custom struct20902091The follow example using custom struct:20922093```go2094type StructA struct {2095 FieldA string `form:"field_a"`2096}20972098type StructB struct {2099 NestedStruct StructA2100 FieldB string `form:"field_b"`2101}21022103type StructC struct {2104 NestedStructPointer *StructA2105 FieldC string `form:"field_c"`2106}21072108type StructD struct {2109 NestedAnonyStruct struct {2110 FieldX string `form:"field_x"`2111 }2112 FieldD string `form:"field_d"`2113}21142115func GetDataB(c *gin.Context) {2116 var b StructB2117 c.Bind(&b)2118 c.JSON(http.StatusOK, gin.H{2119 "a": b.NestedStruct,2120 "b": b.FieldB,2121 })2122}21232124func GetDataC(c *gin.Context) {2125 var b StructC2126 c.Bind(&b)2127 c.JSON(http.StatusOK, gin.H{2128 "a": b.NestedStructPointer,2129 "c": b.FieldC,2130 })2131}21322133func GetDataD(c *gin.Context) {2134 var b StructD2135 c.Bind(&b)2136 c.JSON(http.StatusOK, gin.H{2137 "x": b.NestedAnonyStruct,2138 "d": b.FieldD,2139 })2140}21412142func main() {2143 r := gin.Default()2144 r.GET("/getb", GetDataB)2145 r.GET("/getc", GetDataC)2146 r.GET("/getd", GetDataD)21472148 r.Run()2149}2150```21512152Using the command `curl` command result:21532154```sh2155$ curl "http://localhost:8080/getb?field_a=hello&field_b=world"2156{"a":{"FieldA":"hello"},"b":"world"}2157$ curl "http://localhost:8080/getc?field_a=hello&field_c=world"2158{"a":{"FieldA":"hello"},"c":"world"}2159$ curl "http://localhost:8080/getd?field_x=hello&field_d=world"2160{"d":"world","x":{"FieldX":"hello"}}2161```21622163### Try to bind body into different structs21642165The normal methods for binding request body consumes `c.Request.Body` and they2166cannot be called multiple times.21672168```go2169type formA struct {2170 Foo string `json:"foo" xml:"foo" binding:"required"`2171}21722173type formB struct {2174 Bar string `json:"bar" xml:"bar" binding:"required"`2175}21762177func SomeHandler(c *gin.Context) {2178 objA := formA{}2179 objB := formB{}2180 // Calling c.ShouldBind consumes c.Request.Body and it cannot be reused.2181 if errA := c.ShouldBind(&objA); errA == nil {2182 c.String(http.StatusOK, `the body should be formA`)2183 // Always an error is occurred by this because c.Request.Body is EOF now.2184 } else if errB := c.ShouldBind(&objB); errB == nil {2185 c.String(http.StatusOK, `the body should be formB`)2186 } else {2187 ...2188 }2189}2190```21912192For this, you can use `c.ShouldBindBodyWith` or shortcuts.21932194- `c.ShouldBindBodyWithJSON` is a shortcut for c.ShouldBindBodyWith(obj, binding.JSON).2195- `c.ShouldBindBodyWithXML` is a shortcut for c.ShouldBindBodyWith(obj, binding.XML).2196- `c.ShouldBindBodyWithYAML` is a shortcut for c.ShouldBindBodyWith(obj, binding.YAML).2197- `c.ShouldBindBodyWithTOML` is a shortcut for c.ShouldBindBodyWith(obj, binding.TOML).21982199```go2200func SomeHandler(c *gin.Context) {2201 objA := formA{}2202 objB := formB{}2203 // This reads c.Request.Body and stores the result into the context.2204 if errA := c.ShouldBindBodyWith(&objA, binding.Form); errA == nil {2205 c.String(http.StatusOK, `the body should be formA`)2206 // At this time, it reuses body stored in the context.2207 } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {2208 c.String(http.StatusOK, `the body should be formB JSON`)2209 // And it can accepts other formats2210 } else if errB2 := c.ShouldBindBodyWithXML(&objB); errB2 == nil {2211 c.String(http.StatusOK, `the body should be formB XML`)2212 } else {2213 ...2214 }2215}2216```221722181. `c.ShouldBindBodyWith` stores body into the context before binding. This has2219a slight impact to performance, so you should not use this method if you are2220enough to call binding at once.22212. This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`,2222`ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`,2223can be called by `c.ShouldBind()` multiple times without any damage to2224performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)).22252226### Bind form-data request with custom struct and custom tag22272228```go2229const (2230 customerTag = "url"2231 defaultMemory = 32 << 202232)22332234type customerBinding struct {}22352236func (customerBinding) Name() string {2237 return "form"2238}22392240func (customerBinding) Bind(req *http.Request, obj any) error {2241 if err := req.ParseForm(); err != nil {2242 return err2243 }2244 if err := req.ParseMultipartForm(defaultMemory); err != nil {2245 if err != http.ErrNotMultipart {2246 return err2247 }2248 }2249 if err := binding.MapFormWithTag(obj, req.Form, customerTag); err != nil {2250 return err2251 }2252 return validate(obj)2253}22542255func validate(obj any) error {2256 if binding.Validator == nil {2257 return nil2258 }2259 return binding.Validator.ValidateStruct(obj)2260}22612262// Now we can do this!!!2263// FormA is an external type that we can't modify it's tag2264type FormA struct {2265 FieldA string `url:"field_a"`2266}22672268func ListHandler(s *Service) func(ctx *gin.Context) {2269 return func(ctx *gin.Context) {2270 var urlBinding = customerBinding{}2271 var opt FormA2272 err := ctx.MustBindWith(&opt, urlBinding)2273 if err != nil {2274 ...2275 }2276 ...2277 }2278}2279```22802414### http2 server push24152416http.Pusher is supported only **go1.8+**. See the [golang blog](https://go.dev/blog/h2push) for detail information.2417
41 unmodified lines
2459 r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")2460}2461```24622330### Define format for the log of routes23312332The default log of routes is:23332334```sh2335[GIN-debug] POST /foo --> main.main.func1 (3 handlers)2336[GIN-debug] GET /bar --> main.main.func2 (3 handlers)2337[GIN-debug] GET /status --> main.main.func3 (3 handlers)2338```23392340If 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`.2341In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs.23422343```go2344import (2345 "log"2346 "net/http"23472348 "github.com/gin-gonic/gin"2349)23502351func main() {2352 r := gin.Default()2353 gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {2354 log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers)2355 }23562357 r.POST("/foo", func(c *gin.Context) {2358 c.JSON(http.StatusOK, "foo")2359 })23602361 r.GET("/bar", func(c *gin.Context) {2362 c.JSON(http.StatusOK, "bar")2363 })23642365 r.GET("/status", func(c *gin.Context) {2366 c.JSON(http.StatusOK, "ok")2367 })23682369 // Listen and Server in http://0.0.0.0:80802370 r.Run()2371}2372```23732463### Set and get a cookie24642465```go2466import (
72 unmodified lines
2539 router.Run()2540}2541```25422454### Custom json codec at runtime2543### Don't trust all proxies25442456Gin support custom json serialization and deserialization logic without using compile tags.245724581. Define a custom struct implements the `json.Core` interface.245924602. Before your engine starts, assign values to `json.API` using the custom struct.24612462```go2463package main24642465import (2466 "io"24672468 "github.com/gin-gonic/gin"2469 "github.com/gin-gonic/gin/codec/json"2470 jsoniter "github.com/json-iterator/go"2471)24722473var customConfig = jsoniter.Config{2474 EscapeHTML: true,2475 SortMapKeys: true,2476 ValidateJsonRawMessage: true,2477}.Froze()24782479// implement api.JsonApi2480type customJsonApi struct {2481}24822483func (j customJsonApi) Marshal(v any) ([]byte, error) {2484 return customConfig.Marshal(v)2485}24862487func (j customJsonApi) Unmarshal(data []byte, v any) error {2488 return customConfig.Unmarshal(data, v)2489}24902491func (j customJsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {2492 return customConfig.MarshalIndent(v, prefix, indent)2493}24942495func (j customJsonApi) NewEncoder(writer io.Writer) json.Encoder {2496 return customConfig.NewEncoder(writer)2497}24982499func (j customJsonApi) NewDecoder(reader io.Reader) json.Decoder {2500 return customConfig.NewDecoder(reader)2501}25022503func main() {2504 //Replace the default json api2505 json.API = customJsonApi{}25062507 //Start your gin engine2508 router := gin.Default()2509 router.Run(":8080")2510}2511```25122513## Don't trust all proxies25142545Gin lets you specify which headers to hold the real client IP (if any),2546as well as specifying which proxies (or direct clients) you trust to2547specify one of these headers.2548
118 unmodified lines