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
Provenance
- Commit
d467221- Tree
35514d8- Author
Bo-Yi Wu <appleboy.tw@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
3e44fdc
1 file changed+581 added−551 removed
modified:docs/doc.md+581 added-551 removed
2 unmodified lines3 ## Contents4 5 - [Build Tags](#build-tags)6 - [Build with json replacement](#build-with-json-replacement)7- - [Build without `MsgPack` rendering feature](#build-without-msgpack-rendering-feature)8-- [API Examples](#api-examples)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 lines15 - [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 lines59 - [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)76 77+You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples).78+79 ## Build tags80 81 ### Build with json replacement82 13 unmodified lines96 97 [sonic](https://github.com/bytedance/sonic)98 99 ```sh92-$ go build -tags=sonic .100+go build -tags=sonic .101 ```102 103 ### Build without `MsgPack` rendering feature104 4 unmodified lines109 ```110 111 This is useful to reduce the binary size of executable files. See the [detail information](https://github.com/gin-gonic/gin/pull/1852).112 105-## API Examples113+## Routing114 107-You 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.116 117 ### Using GET, POST, PUT, PATCH, DELETE and OPTIONS118 119 ```go248 unmodified lines368 router.Run(":8080")369 }370 ```371 372+### Redirects373+374+Issuing a HTTP redirect is easy. Both internal and external locations are supported.375+376+```go377+r.GET("/test", func(c *gin.Context) {378+ c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")379+})380+```381+382+Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444)383+384+```go385+r.POST("/test", func(c *gin.Context) {386+ c.Redirect(http.StatusFound, "/foo")387+})388+```389+390+Issuing a Router redirect, use `HandleContext` like below.391+392+```go393+r.GET("/test", func(c *gin.Context) {394+ c.Request.URL.Path = "/test2"395+ r.HandleContext(c)396+})397+r.GET("/test2", func(c *gin.Context) {398+ c.JSON(http.StatusOK, gin.H{"hello": "world"})399+})400+```401+402+## Middleware403+404+> Configure middleware for request processing, authentication, and error recovery.405+406 ### Blank Gin without middleware by default407 408 Use409 48 unmodified lines458 r.Run(":8080")459 }460 ```461 462+### Custom Middleware463+464+```go465+func Logger() gin.HandlerFunc {466+ return func(c *gin.Context) {467+ t := time.Now()468+469+ // Set example variable470+ c.Set("example", "12345")471+472+ // before request473+474+ c.Next()475+476+ // after request477+ latency := time.Since(t)478+ log.Print(latency)479+480+ // access the status we are sending481+ status := c.Writer.Status()482+ log.Println(status)483+ }484+}485+486+func main() {487+ r := gin.New()488+ r.Use(Logger())489+490+ r.GET("/test", func(c *gin.Context) {491+ example := c.MustGet("example").(string)492+493+ // it would print: "12345"494+ log.Println(example)495+ })496+497+ // Listen and serve on 0.0.0.0:8080498+ r.Run(":8080")499+}500+```501+502 ### Custom Recovery behavior503 504 ```go505 func main() {26 unmodified lines532 r.Run(":8080")533 }534 ```535 536+### Using BasicAuth() middleware537+538+```go539+// simulate some private data540+var 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+}545+546+func main() {547+ r := gin.Default()548+549+ // 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+ }))557+558+ // /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+ })569+570+ // Listen and serve on 0.0.0.0:8080571+ r.Run(":8080")572+}573+```574+575+### Goroutines inside a middleware576+577+When starting new Goroutines inside a middleware or handler, you **SHOULD NOT** use the original context inside it, you have to use a read-only copy.578+579+```go580+func main() {581+ r := gin.Default()582+583+ 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)589+590+ // note that you are using the copied context "cCp", IMPORTANT591+ log.Println("Done! in path " + cCp.Request.URL.Path)592+ }()593+ })594+595+ r.GET("/long_sync", func(c *gin.Context) {596+ // simulate a long task with time.Sleep(). 5 seconds597+ time.Sleep(5 * time.Second)598+599+ // 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+ })602+603+ // Listen and serve on 0.0.0.0:8080604+ r.Run(":8080")605+}606+```607+608+## Logging609+610+> Control log output, formatting, and filtering.611+612 ### How to write log file613 614 ```go615 func main() {11 unmodified lines627 router.GET("/ping", func(c *gin.Context) {628 c.String(http.StatusOK, "pong")629 })630 473- router.Run(":8080")631+ router.Run(":8080")632 }633 ```634 635 ### Custom Log Format119 unmodified lines755 756 ```go757 func main() {758 router := gin.New()601- 759+760 // 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- 763+764 router.Use(gin.LoggerWithConfig(loggerConfig))765 }766 ```767 768+### Define format for the log of routes769+770+The default log of routes is:771+772+```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+```777+778+If you want to log this information in given format (e.g. JSON, key values or something else), then you can define this format with `gin.DebugPrintRouteFunc`.779+In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs.780+781+```go782+import (783+ "log"784+ "net/http"785+786+ "github.com/gin-gonic/gin"787+)788+789+func 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+ }794+795+ r.POST("/foo", func(c *gin.Context) {796+ c.JSON(http.StatusOK, "foo")797+ })798+799+ r.GET("/bar", func(c *gin.Context) {800+ c.JSON(http.StatusOK, "bar")801+ })802+803+ r.GET("/status", func(c *gin.Context) {804+ c.JSON(http.StatusOK, "ok")805+ })806+807+ // Listen and Server in http://0.0.0.0:8080808+ r.Run()809+}810+```811+812+## Request Binding & Validation813+814+> Bind and validate request data from query strings, forms, JSON, and more.815+816 ### Model binding and validation817 818 To bind a request body into a type, use model binding. We currently support binding of JSON, XML, YAML, TOML and standard form values (foo=bar&boo=baz).819 268 unmodified lines1088 ```sh1089 curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033&unixMilliTime=1562400033001&unixMicroTime=1562400033000012"1090 ```1091 886-1092 ### Bind default value if none provided1093 1094 If 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:1095 1096 ```go1097 package main1098 1099 import (895- "net/http"1100+ "net/http"1101 897- "github.com/gin-gonic/gin"1102+ "github.com/gin-gonic/gin"1103 )1104 1105 type 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 }1112 1113 func 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 ```1126 922-```1127+```sh1128 curl -X POST http://localhost:8080/person1129 {"Name":"William","Age":10,"Friends":["Will","Bill"],"Colors":["red","blue"],"LapTimes":[1,2,3]}1130 ```1131 1132 NOTE: For default [collection values](#collection-format-for-arrays), the following rules apply:1133+1134 - 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"1137 932-1138 #### Collection format for arrays1139 1140 | Format | Description | Example |1141 | --------------- | --------------------------------------------------------- | ----------------------- |6 unmodified lines1148 ```go1149 package main1150 1151 import (947- "log"948- "time"949- "github.com/gin-gonic/gin"1152+ "log"1153+ "time"1154+ "github.com/gin-gonic/gin"1155 )1156 1157 type 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 }1164 1165 func 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 }1170 func 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 ```1185 1186 Test it with:1187+1188 ```sh983-$ curl -X GET "localhost:8085/testing?name=appleboy&addresses=foo,bar&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"1189+curl -X GET "localhost:8085/testing?name=appleboy&addresses=foo,bar&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"1190 ```1191 1192 ### Bind Uri1193 76 unmodified lines1270 1271 ```sh1272 curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02'1273 ```1274+1275 Result1276+1277 ```sh1278 {"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]}1279 ```1280 1281 Note:1282+1283 - 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.1285 1286 ---38 unmodified lines1325 1326 ```sh1327 curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02'1328 ```1329+1330 Result1331+1332 ```sh1333 {"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]}1334 ```1335 1336 Note:1337+1338 - 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.1340 1341 ### Bind Header63 unmodified lines1405 form.html1406 1407 ```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 ```1419 1420 result:1421 1422 ```json1211-{"color":["red","green","blue"]}1423+{ "color": ["red", "green", "blue"] }1424 ```1425 1426 ### Multipart/Urlencoded binding1427 38 unmodified lines1466 ```sh1467 curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile1468 ```1469 1470+### Bind form-data request with custom struct1471+1472+The follow example using custom struct:1473+1474+```go1475+type StructA struct {1476+ FieldA string `form:"field_a"`1477+}1478+1479+type StructB struct {1480+ NestedStruct StructA1481+ FieldB string `form:"field_b"`1482+}1483+1484+type StructC struct {1485+ NestedStructPointer *StructA1486+ FieldC string `form:"field_c"`1487+}1488+1489+type StructD struct {1490+ NestedAnonyStruct struct {1491+ FieldX string `form:"field_x"`1492+ }1493+ FieldD string `form:"field_d"`1494+}1495+1496+func 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+}1504+1505+func 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+}1513+1514+func 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+}1522+1523+func main() {1524+ r := gin.Default()1525+ r.GET("/getb", GetDataB)1526+ r.GET("/getc", GetDataC)1527+ r.GET("/getd", GetDataD)1528+1529+ r.Run()1530+}1531+```1532+1533+Using the command `curl` command result:1534+1535+```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+```1543+1544+### Try to bind body into different structs1545+1546+The normal methods for binding request body consumes `c.Request.Body` and they1547+cannot be called multiple times.1548+1549+```go1550+type formA struct {1551+ Foo string `json:"foo" xml:"foo" binding:"required"`1552+}1553+1554+type formB struct {1555+ Bar string `json:"bar" xml:"bar" binding:"required"`1556+}1557+1558+func 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+```1572+1573+For this, you can use `c.ShouldBindBodyWith` or shortcuts.1574+1575+- `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).1579+1580+```go1581+func 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+```1598+1599+1. `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.1602+2. 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)).1606+1607+### Bind form-data request with custom struct and custom tag1608+1609+```go1610+const (1611+ customerTag = "url"1612+ defaultMemory = 32 << 201613+)1614+1615+type customerBinding struct {}1616+1617+func (customerBinding) Name() string {1618+ return "form"1619+}1620+1621+func (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+}1635+1636+func validate(obj any) error {1637+ if binding.Validator == nil {1638+ return nil1639+ }1640+ return binding.Validator.ValidateStruct(obj)1641+}1642+1643+// Now we can do this!!!1644+// FormA is an external type that we can't modify it's tag1645+type FormA struct {1646+ FieldA string `url:"field_a"`1647+}1648+1649+func 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+```1661+1662+## Response Rendering1663+1664+> Render responses in various formats including JSON, XML, HTML, and more.1665+1666 ### XML, JSON, YAML, TOML and ProtoBuf rendering1667 1668 ```go1669 func main() {236 unmodified lines1906 templates/index.tmpl1907 1908 ```html1909 <html>1502- <h1>1503- {{ .title }}1504- </h1>1910+ <h1>{{ .title }}</h1>1911 </html>1912 ```1913 1914 Using templates with same name in different directories19 unmodified lines1934 templates/posts/index.tmpl1935 1936 ```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 ```1944 1945 templates/users/index.tmpl1946 1947 ```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 lines2033 ### Multitemplate2034 2035 Gin 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`.2036 1633-### Redirects2037+### Build a single binary with templates2038 1635-Issuing a HTTP redirect is easy. Both internal and external locations are supported.2039+You can build a server into a single binary containing templates by using the [embed](https://pkg.go.dev/embed) package.2040 2041 ```go1638-r.GET("/test", func(c *gin.Context) {1639- c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")1640-})1641-```2042+package main2043 1643-Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444)2044+import (2045+ "embed"2046+ "html/template"2047+ "net/http"2048 1645-```go1646-r.POST("/test", func(c *gin.Context) {1647- c.Redirect(http.StatusFound, "/foo")1648-})1649-```2049+ "github.com/gin-gonic/gin"2050+)2051 1651-Issuing a Router redirect, use `HandleContext` like below.2052+//go:embed assets/* templates/*2053+var f embed.FS2054 1653-``` go1654-r.GET("/test", func(c *gin.Context) {1655- c.Request.URL.Path = "/test2"1656- r.HandleContext(c)1657-})1658-r.GET("/test2", func(c *gin.Context) {1659- c.JSON(http.StatusOK, gin.H{"hello": "world"})1660-})1661-```1662-1663-### Custom Middleware1664-1665-```go1666-func Logger() gin.HandlerFunc {1667- return func(c *gin.Context) {1668- t := time.Now()1669-1670- // Set example variable1671- c.Set("example", "12345")1672-1673- // before request1674-1675- c.Next()1676-1677- // after request1678- latency := time.Since(t)1679- log.Print(latency)1680-1681- // access the status we are sending1682- status := c.Writer.Status()1683- log.Println(status)1684- }1685-}1686-2055 func 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)2059 1691- 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))2062 1694- // 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 })2068 1698- // 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+ })2074 1703-### Using BasicAuth() middleware1704-1705-```go1706-// simulate some private data1707-var 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-}1712-1713-func main() {1714- r := gin.Default()1715-1716- // 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- }))1724-1725- // /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 })2083 1737- // Listen and serve on 0.0.0.0:80801738- r.Run(":8080")2084+ router.Run(":8080")2085 }2086 ```2087 1742-### Goroutines inside a middleware2088+See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary/example02` directory.2089 1744-When starting new Goroutines inside a middleware or handler, you **SHOULD NOT** use the original context inside it, you have to use a read-only copy.2090+## Server Configuration2091 1746-```go1747-func main() {1748- r := gin.Default()2092+> Configure HTTP servers, TLS, proxies, and runtime settings.2093 1750- 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)1756-1757- // note that you are using the copied context "cCp", IMPORTANT1758- log.Println("Done! in path " + cCp.Request.URL.Path)1759- }()1760- })1761-1762- r.GET("/long_sync", func(c *gin.Context) {1763- // simulate a long task with time.Sleep(). 5 seconds1764- time.Sleep(5 * time.Second)1765-1766- // 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- })1769-1770- // Listen and serve on 0.0.0.0:80801771- r.Run(":8080")1772-}1773-```1774-2094 ### Custom HTTP configuration2095 2096 Use `http.ListenAndServe()` directly, like this:2097 20 unmodified lines2118 s.ListenAndServe()2119 }2120 ```2121 2122+### Custom json codec at runtime2123+2124+Gin support custom json serialization and deserialization logic without using compile tags.2125+2126+1. Define a custom struct implements the `json.Core` interface.2127+2128+2. Before your engine starts, assign values to `json.API` using the custom struct.2129+2130+```go2131+package main2132+2133+import (2134+ "io"2135+2136+ "github.com/gin-gonic/gin"2137+ "github.com/gin-gonic/gin/codec/json"2138+ jsoniter "github.com/json-iterator/go"2139+)2140+2141+var customConfig = jsoniter.Config{2142+ EscapeHTML: true,2143+ SortMapKeys: true,2144+ ValidateJsonRawMessage: true,2145+}.Froze()2146+2147+// implement api.JsonApi2148+type customJsonApi struct {2149+}2150+2151+func (j customJsonApi) Marshal(v any) ([]byte, error) {2152+ return customConfig.Marshal(v)2153+}2154+2155+func (j customJsonApi) Unmarshal(data []byte, v any) error {2156+ return customConfig.Unmarshal(data, v)2157+}2158+2159+func (j customJsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {2160+ return customConfig.MarshalIndent(v, prefix, indent)2161+}2162+2163+func (j customJsonApi) NewEncoder(writer io.Writer) json.Encoder {2164+ return customConfig.NewEncoder(writer)2165+}2166+2167+func (j customJsonApi) NewDecoder(reader io.Reader) json.Decoder {2168+ return customConfig.NewDecoder(reader)2169+}2170+2171+func main() {2172+ //Replace the default json api2173+ json.API = customJsonApi{}2174+2175+ //Start your gin engine2176+ router := gin.Default()2177+ router.Run(":8080")2178+}2179+```2180+2181 ### Support Let's Encrypt2182 2183 example for 1-line LetsEncrypt HTTPS servers.2184 157 unmodified lines2342 ```2343 2344 Alternatives:2345 1968-* [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.2349 2350 #### Manually2351 2352 In case you are using Go 1.8 or a later version, you may not need to use those libraries. Consider using `http.Server`'s built-in [Shutdown()](https://pkg.go.dev/net/http#Server.Shutdown) method for graceful shutdowns. The example below describes its usage, and we've got more examples using gin [here](https://github.com/gin-gonic/examples/tree/master/graceful-shutdown).57 unmodified lines2410 log.Println("Server exiting")2411 }2412 ```2413 2036-### Build a single binary with templates2037-2038-You can build a server into a single binary containing templates by using the [embed](https://pkg.go.dev/embed) package.2039-2040-```go2041-package main2042-2043-import (2044- "embed"2045- "html/template"2046- "net/http"2047-2048- "github.com/gin-gonic/gin"2049-)2050-2051-//go:embed assets/* templates/*2052-var f embed.FS2053-2054-func main() {2055- router := gin.Default()2056- templ := template.Must(template.New("").ParseFS(f, "templates/*.tmpl", "templates/foo/*.tmpl"))2057- router.SetHTMLTemplate(templ)2058-2059- // example: /public/assets/images/example.png2060- router.StaticFS("/public", http.FS(f))2061-2062- router.GET("/", func(c *gin.Context) {2063- c.HTML(http.StatusOK, "index.tmpl", gin.H{2064- "title": "Main website",2065- })2066- })2067-2068- router.GET("/foo", func(c *gin.Context) {2069- c.HTML(http.StatusOK, "bar.tmpl", gin.H{2070- "title": "Foo website",2071- })2072- })2073-2074- 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- })2082-2083- router.Run(":8080")2084-}2085-```2086-2087-See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary/example02` directory.2088-2089-### Bind form-data request with custom struct2090-2091-The follow example using custom struct:2092-2093-```go2094-type StructA struct {2095- FieldA string `form:"field_a"`2096-}2097-2098-type StructB struct {2099- NestedStruct StructA2100- FieldB string `form:"field_b"`2101-}2102-2103-type StructC struct {2104- NestedStructPointer *StructA2105- FieldC string `form:"field_c"`2106-}2107-2108-type StructD struct {2109- NestedAnonyStruct struct {2110- FieldX string `form:"field_x"`2111- }2112- FieldD string `form:"field_d"`2113-}2114-2115-func 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-}2123-2124-func 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-}2132-2133-func 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-}2141-2142-func main() {2143- r := gin.Default()2144- r.GET("/getb", GetDataB)2145- r.GET("/getc", GetDataC)2146- r.GET("/getd", GetDataD)2147-2148- r.Run()2149-}2150-```2151-2152-Using the command `curl` command result:2153-2154-```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-```2162-2163-### Try to bind body into different structs2164-2165-The normal methods for binding request body consumes `c.Request.Body` and they2166-cannot be called multiple times.2167-2168-```go2169-type formA struct {2170- Foo string `json:"foo" xml:"foo" binding:"required"`2171-}2172-2173-type formB struct {2174- Bar string `json:"bar" xml:"bar" binding:"required"`2175-}2176-2177-func 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-```2191-2192-For this, you can use `c.ShouldBindBodyWith` or shortcuts.2193-2194-- `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).2198-2199-```go2200-func 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-```2217-2218-1. `c.ShouldBindBodyWith` stores body into the context before binding. This has2219-a slight impact to performance, so you should not use this method if you are2220-enough to call binding at once.2221-2. This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`,2222-`ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`,2223-can be called by `c.ShouldBind()` multiple times without any damage to2224-performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)).2225-2226-### Bind form-data request with custom struct and custom tag2227-2228-```go2229-const (2230- customerTag = "url"2231- defaultMemory = 32 << 202232-)2233-2234-type customerBinding struct {}2235-2236-func (customerBinding) Name() string {2237- return "form"2238-}2239-2240-func (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-}2254-2255-func validate(obj any) error {2256- if binding.Validator == nil {2257- return nil2258- }2259- return binding.Validator.ValidateStruct(obj)2260-}2261-2262-// Now we can do this!!!2263-// FormA is an external type that we can't modify it's tag2264-type FormA struct {2265- FieldA string `url:"field_a"`2266-}2267-2268-func 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-```2280-2414 ### http2 server push2415 2416 http.Pusher is supported only **go1.8+**. See the [golang blog](https://go.dev/blog/h2push) for detail information.2417 41 unmodified lines2459 r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")2460 }2461 ```2462 2330-### Define format for the log of routes2331-2332-The default log of routes is:2333-2334-```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-```2339-2340-If you want to log this information in given format (e.g. JSON, key values or something else), then you can define this format with `gin.DebugPrintRouteFunc`.2341-In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs.2342-2343-```go2344-import (2345- "log"2346- "net/http"2347-2348- "github.com/gin-gonic/gin"2349-)2350-2351-func 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- }2356-2357- r.POST("/foo", func(c *gin.Context) {2358- c.JSON(http.StatusOK, "foo")2359- })2360-2361- r.GET("/bar", func(c *gin.Context) {2362- c.JSON(http.StatusOK, "bar")2363- })2364-2365- r.GET("/status", func(c *gin.Context) {2366- c.JSON(http.StatusOK, "ok")2367- })2368-2369- // Listen and Server in http://0.0.0.0:80802370- r.Run()2371-}2372-```2373-2463 ### Set and get a cookie2464 2465 ```go2466 import (72 unmodified lines2539 router.Run()2540 }2541 ```2542 2454-### Custom json codec at runtime2543+### Don't trust all proxies2544 2456-Gin support custom json serialization and deserialization logic without using compile tags.2457-2458-1. Define a custom struct implements the `json.Core` interface.2459-2460-2. Before your engine starts, assign values to `json.API` using the custom struct.2461-2462-```go2463-package main2464-2465-import (2466- "io"2467-2468- "github.com/gin-gonic/gin"2469- "github.com/gin-gonic/gin/codec/json"2470- jsoniter "github.com/json-iterator/go"2471-)2472-2473-var customConfig = jsoniter.Config{2474- EscapeHTML: true,2475- SortMapKeys: true,2476- ValidateJsonRawMessage: true,2477-}.Froze()2478-2479-// implement api.JsonApi2480-type customJsonApi struct {2481-}2482-2483-func (j customJsonApi) Marshal(v any) ([]byte, error) {2484- return customConfig.Marshal(v)2485-}2486-2487-func (j customJsonApi) Unmarshal(data []byte, v any) error {2488- return customConfig.Unmarshal(data, v)2489-}2490-2491-func (j customJsonApi) MarshalIndent(v any, prefix, indent string) ([]byte, error) {2492- return customConfig.MarshalIndent(v, prefix, indent)2493-}2494-2495-func (j customJsonApi) NewEncoder(writer io.Writer) json.Encoder {2496- return customConfig.NewEncoder(writer)2497-}2498-2499-func (j customJsonApi) NewDecoder(reader io.Reader) json.Decoder {2500- return customConfig.NewDecoder(reader)2501-}2502-2503-func main() {2504- //Replace the default json api2505- json.API = customJsonApi{}2506-2507- //Start your gin engine2508- router := gin.Default()2509- router.Run(":8080")2510-}2511-```2512-2513-## Don't trust all proxies2514-2545 Gin lets you specify which headers to hold the real client IP (if any),2546 as well as specifying which proxies (or direct clients) you trust to2547 specify one of these headers.2548 118 unmodified lines