Skip to content
Myr

doc.md

This file

Path

docs/doc.md

2,666 lines · 67.4 KiB · Markdown

Last changed by

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

History of this file

Take it

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

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 1–6why, one step back
1# Gin Quick Start
23## Contents45- [Build Tags](#build-tags)6 - [Build with json replacement](#build-with-json-replacement)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 7–8why, one step back
7 - [Build without MsgPack rendering feature](#build-without-msgpack-rendering-feature)
8- [Routing](#routing)

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 9–19why, one step back
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 - [Redirects](#redirects)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 20–22why, one step back
20- [Middleware](#middleware)
21 - [Blank Gin without middleware by default](#blank-gin-without-middleware-by-default)22 - [Using middleware](#using-middleware)

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 23why, one step back
23 - [Custom Middleware](#custom-middleware)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 24why, one step back
24 - [Custom Recovery behavior](#custom-recovery-behavior)

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 25–26why, one step back
25 - [Using BasicAuth() middleware](#using-basicauth-middleware)
26 - [Goroutines inside a middleware](#goroutines-inside-a-middleware)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 27–32why, one step back
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)32 - [Avoid logging query strings](#avoid-logging-query-strings)

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 33why, one step back
33 - [Define format for the log of routes](#define-format-for-the-log-of-routes)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 34–65why, one step back
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)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)54 - [PureJSON](#purejson)55 - [Serving static files](#serving-static-files)56 - [Serving data from file](#serving-data-from-file)57 - [Serving data from reader](#serving-data-from-reader)58 - [HTML rendering](#html-rendering)59 - [Custom Template renderer](#custom-template-renderer)60 - [Custom Delimiters](#custom-delimiters)61 - [Custom Template Funcs](#custom-template-funcs)62 - [Multitemplate](#multitemplate)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)

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

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

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 67–74why, one step back
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)72 - [http2 server push](#http2-server-push)73 - [Set and get a cookie](#set-and-get-a-cookie)74 - [Don't trust all proxies](#dont-trust-all-proxies)

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 75why, one step back
75- [Testing](#testing)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 76why, one step back
76

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 77why, one step back
77You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples).

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 78–116why, one step back
78
79## Build tags8081### Build with json replacement8283Gin uses `encoding/json` as the default JSON package but you can change it by building from other tags.8485[jsoniter](https://github.com/json-iterator/go)8687```sh88go build -tags=jsoniter .89```9091[go-json](https://github.com/goccy/go-json)9293```sh94go build -tags=go_json .95```9697[sonic](https://github.com/bytedance/sonic)9899```sh100go build -tags=sonic .101```102103### Build without `MsgPack` rendering feature104105Gin enables `MsgPack` rendering feature by default. But you can disable this feature by specifying `nomsgpack` build tag.106107```sh108go build -tags=nomsgpack .109```110111This is useful to reduce the binary size of executable files. See the [detail information](https://github.com/gin-gonic/gin/pull/1852).112113## Routing114115> Learn how to define routes, handle parameters, and organize endpoints.116

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 117why, one step back
117### Using GET, POST, PUT, PATCH, DELETE and OPTIONS

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 118–124why, one step back
118
119```go120func main() {121 // Creates a gin router with default middleware:122 // logger and recovery (crash-free) middleware123 router := gin.Default()124

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 125–131why, one step back
125 router.GET("/someGet", getting)
126 router.POST("/somePost", posting)127 router.PUT("/somePut", putting)128 router.DELETE("/someDelete", deleting)129 router.PATCH("/somePatch", patching)130 router.HEAD("/someHead", head)131 router.OPTIONS("/someOptions", options)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 132why, one step back
132

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 133–134why, one step back
133 // By default, it serves on :8080 unless a
134 // PORT environment variable was defined.

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 135why, one step back
135 router.Run()

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 136why, one step back
136 // router.Run(":3000") for a hard coded port

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 137–139why, one step back
137}
138```139

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 140why, one step back
140### Parameters in path

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 141–145why, one step back
141
142```go143func main() {144 router := gin.Default()145

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 146–147why, one step back
146 // This handler will match /user/john but will not match /user/ or /user
147 router.GET("/user/:name", func(c *gin.Context) {

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 148why, one step back
148 name := c.Param("name")

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 149why, one step back
149 c.String(http.StatusOK, "Hello %s", name)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 150–151why, one step back
150 })
151

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 152–154why, one step back
152 // However, this one will match /user/john/ and also /user/john/send
153 // If no other routers match /user/john, it will redirect to /user/john/154 router.GET("/user/:name/*action", func(c *gin.Context) {

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 155why, one step back
155 name := c.Param("name")

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 156–158why, one step back
156 action := c.Param("action")
157 message := name + " is " + action158 c.String(http.StatusOK, message)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 159–160why, one step back
159 })
160

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 161–164why, one step back
161 // For each matched request Context will hold the route definition
162 router.POST("/user/:name/*action", func(c *gin.Context) {163 b := c.FullPath() == "/user/:name/*action" // true164 c.String(http.StatusOK, "%t", b)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 165–166why, one step back
165 })
166

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 167–171why, one step back
167 // This handler will add a new router for /user/groups.
168 // Exact routes are resolved before param routes, regardless of the order they were defined.169 // Routes starting with /user/groups are never interpreted as /user/:name/... routes170 router.GET("/user/groups", func(c *gin.Context) {171 c.String(http.StatusOK, "The available groups are [...]")

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 172–177why, one step back
172 })
173174 router.Run(":8080")175}176```177

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 178why, one step back
178### Querystring parameters

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 179–183why, one step back
179
180```go181func main() {182 router := gin.Default()183

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 184–188why, one step back
184 // Query string parameters are parsed using the existing underlying request object.
185 // The request responds to a URL matching: /welcome?firstname=Jane&lastname=Doe186 router.GET("/welcome", func(c *gin.Context) {187 firstname := c.DefaultQuery("firstname", "Guest")188 lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 189why, one step back
189

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 190why, one step back
190 c.String(http.StatusOK, "Hello %s %s", firstname, lastname)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 191–195why, one step back
191 })
192 router.Run(":8080")193}194```195

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 196why, one step back
196### Multipart/Urlencoded Form

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 197–201why, one step back
197
198```go199func main() {200 router := gin.Default()201

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 202why, one step back
202 router.POST("/form_post", func(c *gin.Context) {

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 203why, one step back
203 message := c.PostForm("message")

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 204why, one step back
204 nick := c.DefaultPostForm("nick", "anonymous")

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 205–206why, one step back
205
206 c.JSON(http.StatusOK, gin.H{

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 207–209why, one step back
207 "status": "posted",
208 "message": message,209 "nick": nick,

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 210–215why, one step back
210 })
211 })212 router.Run(":8080")213}214```215

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 216why, one step back
216### Another example: query + post form

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 217–218why, one step back
217
218```sh

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 219why, one step back
219POST /post?id=1234&page=1 HTTP/1.1

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 220–221why, one step back
220Content-Type: application/x-www-form-urlencoded
221

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 222why, one step back
222name=manu&message=this_is_great

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 223–230why, one step back
223```
224225```go226func main() {227 router := gin.Default()228229 router.POST("/post", func(c *gin.Context) {230

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 231–233why, one step back
231 id := c.Query("id")
232 page := c.DefaultQuery("page", "0")233 name := c.PostForm("name")

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 234–235why, one step back
234 message := c.PostForm("message")
235

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 236why, one step back
236 fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 237–242why, one step back
237 })
238 router.Run(":8080")239}240```241242```sh

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 243why, one step back
243id: 1234; page: 1; name: manu; message: this_is_great

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 244–245why, one step back
244```
245

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 246why, one step back
246### Map as querystring or postform parameters

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 247–248why, one step back
247
248```sh

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 249why, one step back
249POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 250–251why, one step back
250Content-Type: application/x-www-form-urlencoded
251

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 252why, one step back
252names[first]=thinkerou&names[second]=tianou

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 253–260why, one step back
253```
254255```go256func main() {257 router := gin.Default()258259 router.POST("/post", func(c *gin.Context) {260

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 261–262why, one step back
261 ids := c.QueryMap("ids")
262 names := c.PostFormMap("names")

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 263why, one step back
263

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 264why, one step back
264 fmt.Printf("ids: %v; names: %v", ids, names)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 265–270why, one step back
265 })
266 router.Run(":8080")267}268```269270```sh

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 271why, one step back
271ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou]

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 272–273why, one step back
272```
273

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 274why, one step back
274### Upload files

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 275why, one step back
275

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 276why, one step back
276#### Single file

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 277why, one step back
277

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 278why, one step back
278References 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).

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 279why, one step back
279

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 280why, one step back
280`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)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 281why, one step back
281

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

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

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 283–289why, one step back
283
284```go285func main() {286 router := gin.Default()287 // Set a lower memory limit for multipart forms (default is 32 MiB)288 router.MaxMultipartMemory = 8 << 20 // 8 MiB289 router.POST("/upload", func(c *gin.Context) {

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 290–292why, one step back
290 // Single file
291 file, _ := c.FormFile("file")292 log.Println(file.Filename)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 293why, one step back
293

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 294–295why, one step back
294 // Upload the file to specific dst.
295 c.SaveUploadedFile(file, dst)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 296why, one step back
296

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 297why, one step back
297 c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 298–306why, one step back
298 })
299 router.Run(":8080")300}301```302303How to `curl`:304305```bash306curl -X POST http://localhost:8080/upload \

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 307why, one step back
307 -F "file=@/Users/appleboy/test.zip" \

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 308–310why, one step back
308 -H "Content-Type: multipart/form-data"
309```310

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 311why, one step back
311#### Multiple files

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 312why, one step back
312

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

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

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 314–320why, one step back
314
315```go316func main() {317 router := gin.Default()318 // Set a lower memory limit for multipart forms (default is 32 MiB)319 router.MaxMultipartMemory = 8 << 20 // 8 MiB320 router.POST("/upload", func(c *gin.Context) {

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 321–323why, one step back
321 // Multipart form
322 form, _ := c.MultipartForm()323 files := form.File["upload[]"]

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 324why, one step back
324

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 325–326why, one step back
325 for _, file := range files {
326 log.Println(file.Filename)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 327why, one step back
327

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 328–329why, one step back
328 // Upload the file to specific dst.
329 c.SaveUploadedFile(file, dst)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 330why, one step back
330 }

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 331why, one step back
331 c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 332–340why, one step back
332 })
333 router.Run(":8080")334}335```336337How to `curl`:338339```bash340curl -X POST http://localhost:8080/upload \

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 341–342why, one step back
341 -F "upload[]=@/Users/appleboy/test1.zip" \
342 -F "upload[]=@/Users/appleboy/test2.zip" \

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 343–345why, one step back
343 -H "Content-Type: multipart/form-data"
344```345

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 346why, one step back
346### Grouping routes

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 347–351why, one step back
347
348```go349func main() {350 router := gin.Default()351

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 352why, one step back
352 // Simple group: v1

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 353why, one step back
353 {

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 354–357why, one step back
354 v1 := router.Group("/v1")
355 v1.POST("/login", loginEndpoint)356 v1.POST("/submit", submitEndpoint)357 v1.POST("/read", readEndpoint)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 358–359why, one step back
358 }
359

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 360why, one step back
360 // Simple group: v2

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 361why, one step back
361 {

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 362–365why, one step back
362 v2 := router.Group("/v2")
363 v2.POST("/login", loginEndpoint)364 v2.POST("/submit", submitEndpoint)365 v2.POST("/read", readEndpoint)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 366–371why, one step back
366 }
367368 router.Run(":8080")369}370```371

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 372why, one step back
372### Redirects

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 373why, one step back
373

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 374why, one step back
374Issuing a HTTP redirect is easy. Both internal and external locations are supported.

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 375–377why, one step back
375
376```go377r.GET("/test", func(c *gin.Context) {

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 378why, one step back
378 c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 379–381why, one step back
379})
380```381

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 382why, one step back
382Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 383–384why, one step back
383
384```go

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 385–386why, one step back
385r.POST("/test", func(c *gin.Context) {
386 c.Redirect(http.StatusFound, "/foo")

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 387–389why, one step back
387})
388```389

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 390why, one step back
390Issuing a Router redirect, use `HandleContext` like below.

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 391–393why, one step back
391
392```go393r.GET("/test", func(c *gin.Context) {

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 394–395why, one step back
394 c.Request.URL.Path = "/test2"
395 r.HandleContext(c)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 396why, one step back
396})

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 397–398why, one step back
397r.GET("/test2", func(c *gin.Context) {
398 c.JSON(http.StatusOK, gin.H{"hello": "world"})

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 399–461why, one step back
399})
400```401402## Middleware403404> Configure middleware for request processing, authentication, and error recovery.405406### Blank Gin without middleware by default407408Use409410```go411r := gin.New()412```413414instead of415416```go417// Default With the Logger and Recovery middleware already attached418r := gin.Default()419```420421### Using middleware422423```go424func main() {425 // Creates a router without any middleware by default426 r := gin.New()427428 // Global middleware429 // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.430 // By default gin.DefaultWriter = os.Stdout431 r.Use(gin.Logger())432433 // Recovery middleware recovers from any panics and writes a 500 if there was one.434 r.Use(gin.Recovery())435436 // Per route middleware, you can add as many as you desire.437 r.GET("/benchmark", MyBenchLogger(), benchEndpoint)438439 // Authorization group440 // authorized := r.Group("/", AuthRequired())441 // exactly the same as:442 authorized := r.Group("/")443 // per group middleware! in this case we use the custom created444 // AuthRequired() middleware just in the "authorized" group.445 authorized.Use(AuthRequired())446 {447 authorized.POST("/login", loginEndpoint)448 authorized.POST("/submit", submitEndpoint)449 authorized.POST("/read", readEndpoint)450451 // nested group452 testing := authorized.Group("testing")453 // visit 0.0.0.0:8080/testing/analytics454 testing.GET("/analytics", analyticsEndpoint)455 }456457 // Listen and serve on 0.0.0.0:8080458 r.Run(":8080")459}460```461

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 462why, one step back
462### Custom Middleware

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 463–464why, one step back
463
464```go

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 465–467why, one step back
465func Logger() gin.HandlerFunc {
466 return func(c *gin.Context) {467 t := time.Now()

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 468why, one step back
468

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 469–470why, one step back
469 // Set example variable
470 c.Set("example", "12345")

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 471why, one step back
471

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 472why, one step back
472 // before request

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 473why, one step back
473

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 474why, one step back
474 c.Next()

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 475why, one step back
475

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 476–478why, one step back
476 // after request
477 latency := time.Since(t)478 log.Print(latency)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 479why, one step back
479

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 480–482why, one step back
480 // access the status we are sending
481 status := c.Writer.Status()482 log.Println(status)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 483–487why, one step back
483 }
484}485486func main() {487 r := gin.New()

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 488why, one step back
488 r.Use(Logger())

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 489why, one step back
489

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 490–491why, one step back
490 r.GET("/test", func(c *gin.Context) {
491 example := c.MustGet("example").(string)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 492why, one step back
492

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 493–494why, one step back
493 // it would print: "12345"
494 log.Println(example)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 495–535why, one step back
495 })
496497 // Listen and serve on 0.0.0.0:8080498 r.Run(":8080")499}500```501502### Custom Recovery behavior503504```go505func main() {506 // Creates a router without any middleware by default507 r := gin.New()508509 // Global middleware510 // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.511 // By default gin.DefaultWriter = os.Stdout512 r.Use(gin.Logger())513514 // Recovery middleware recovers from any panics and writes a 500 if there was one.515 r.Use(gin.CustomRecovery(func(c *gin.Context, recovered any) {516 if err, ok := recovered.(string); ok {517 c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))518 }519 c.AbortWithStatus(http.StatusInternalServerError)520 }))521522 r.GET("/panic", func(c *gin.Context) {523 // panic with a string -- the custom middleware could save this to a database or report it to the user524 panic("foo")525 })526527 r.GET("/", func(c *gin.Context) {528 c.String(http.StatusOK, "ohai")529 })530531 // Listen and serve on 0.0.0.0:8080532 r.Run(":8080")533}534```535

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 536why, one step back
536### Using BasicAuth() middleware

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 537–538why, one step back
537
538```go

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 539–543why, one step back
539// simulate some private data
540var 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"},

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 544–548why, one step back
544}
545546func main() {547 r := gin.Default()548

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 549–555why, one step back
549 // Group using gin.BasicAuth() middleware
550 // 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",

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 556–557why, one step back
556 }))
557

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 558–566why, one step back
558 // /admin/secrets endpoint
559 // 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 :("})

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 567–574why, one step back
567 }
568 })569570 // Listen and serve on 0.0.0.0:8080571 r.Run(":8080")572}573```574

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 575why, one step back
575### Goroutines inside a middleware

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 576why, one step back
576

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 577why, one step back
577When 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.

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 578–582why, one step back
578
579```go580func main() {581 r := gin.Default()582

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 583–588why, one step back
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)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 589why, one step back
589

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 590–592why, one step back
590 // note that you are using the copied context "cCp", IMPORTANT
591 log.Println("Done! in path " + cCp.Request.URL.Path)592 }()

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 593–594why, one step back
593 })
594

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 595–596why, one step back
595 r.GET("/long_sync", func(c *gin.Context) {
596 // simulate a long task with time.Sleep(). 5 seconds

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 597–598why, one step back
597 time.Sleep(5 * time.Second)
598

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 599–600why, one step back
599 // since we are NOT using a goroutine, we do not have to copy the context
600 log.Println("Done! in path " + c.Request.URL.Path)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 601–767why, one step back
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() {616 // Disable Console Color, you don't need console color when writing the logs to file.617 gin.DisableConsoleColor()618619 // Logging to a file.620 f, _ := os.Create("gin.log")621 gin.DefaultWriter = io.MultiWriter(f)622623 // Use the following code if you need to write the logs to file and console at the same time.624 // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)625626 router := gin.Default()627 router.GET("/ping", func(c *gin.Context) {628 c.String(http.StatusOK, "pong")629 })630631 router.Run(":8080")632}633```634635### Custom Log Format636637```go638func main() {639 router := gin.New()640641 // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter642 // By default gin.DefaultWriter = os.Stdout643 router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {644645 // your custom format646 return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",647 param.ClientIP,648 param.TimeStamp.Format(time.RFC1123),649 param.Method,650 param.Path,651 param.Request.Proto,652 param.StatusCode,653 param.Latency,654 param.Request.UserAgent(),655 param.ErrorMessage,656 )657 }))658 router.Use(gin.Recovery())659660 router.GET("/ping", func(c *gin.Context) {661 c.String(http.StatusOK, "pong")662 })663664 router.Run(":8080")665}666```667668Sample Output669670```sh671::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" "672```673674### Skip logging675676```go677func main() {678 router := gin.New()679680 // skip logging for desired paths by setting SkipPaths in LoggerConfig681 loggerConfig := gin.LoggerConfig{SkipPaths: []string{"/metrics"}}682683 // skip logging based on your logic by setting Skip func in LoggerConfig684 loggerConfig.Skip = func(c *gin.Context) bool {685 // as an example skip non server side errors686 return c.Writer.Status() < http.StatusInternalServerError687 }688689 router.Use(gin.LoggerWithConfig(loggerConfig))690 router.Use(gin.Recovery())691692 // skipped693 router.GET("/metrics", func(c *gin.Context) {694 c.Status(http.StatusNotImplemented)695 })696697 // skipped698 router.GET("/ping", func(c *gin.Context) {699 c.String(http.StatusOK, "pong")700 })701702 // not skipped703 router.GET("/data", func(c *gin.Context) {704 c.Status(http.StatusNotImplemented)705 })706707 router.Run(":8080")708}709710```711712### Controlling Log output coloring713714By default, logs output on console should be colorized depending on the detected TTY.715716Never colorize logs:717718```go719func main() {720 // Disable log's color721 gin.DisableConsoleColor()722723 // Creates a gin router with default middleware:724 // logger and recovery (crash-free) middleware725 router := gin.Default()726727 router.GET("/ping", func(c *gin.Context) {728 c.String(http.StatusOK, "pong")729 })730731 router.Run(":8080")732}733```734735Always colorize logs:736737```go738func main() {739 // Force log's color740 gin.ForceConsoleColor()741742 // Creates a gin router with default middleware:743 // logger and recovery (crash-free) middleware744 router := gin.Default()745746 router.GET("/ping", func(c *gin.Context) {747 c.String(http.StatusOK, "pong")748 })749750 router.Run(":8080")751}752```753754### Avoid logging query strings755756```go757func main() {758 router := gin.New()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}763764 router.Use(gin.LoggerWithConfig(loggerConfig))765}766```767

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 768why, one step back
768### Define format for the log of routes

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

line 769why, one step back
769

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 770why, one step back
770The default log of routes is:

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 771–772why, one step back
771
772```sh

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 773–775why, one step back
773[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)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 776–777why, one step back
776```
777

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 778–779why, one step back
778If 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.

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 780–790why, one step back
780
781```go782import (783 "log"784 "net/http"785786 "github.com/gin-gonic/gin"787)788789func main() {790 r := gin.Default()

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 791–792why, one step back
791 gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {
792 log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers)

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 793–794why, one step back
793 }
794

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 795–796why, one step back
795 r.POST("/foo", func(c *gin.Context) {
796 c.JSON(http.StatusOK, "foo")

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 797–798why, one step back
797 })
798

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 799–800why, one step back
799 r.GET("/bar", func(c *gin.Context) {
800 c.JSON(http.StatusOK, "bar")

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 801–802why, one step back
801 })
802

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

lines 803–804why, one step back
803 r.GET("/status", func(c *gin.Context) {
804 c.JSON(http.StatusOK, "ok")

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 805–806why, one step back
805 })
806

fix(readme): fix broken link to English documentation (#4222)eduardo-axbefore adoption3319038

line 807why, one step back
807 // Listen and Server in http://0.0.0.0:8080

docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221

lines 808–2121why, one step back
808 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).819820Gin 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).821822Note 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"`.823824Also, Gin provides two sets of methods for binding:825826- **Type** - Must bind827 - **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`, `BindHeader`, `BindTOML`828 - **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.829- **Type** - Should bind830 - **Methods** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindXML`, `ShouldBindQuery`, `ShouldBindYAML`, `ShouldBindHeader`, `ShouldBindTOML`,831 - **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.832833When 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`.834835You 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.836837```go838// Binding from JSON839type Login struct {840 User string `form:"user" json:"user" xml:"user" binding:"required"`841 Password string `form:"password" json:"password" xml:"password" binding:"required"`842}843844func main() {845 router := gin.Default()846847 // Example for binding JSON ({"user": "manu", "password": "123"})848 router.POST("/loginJSON", func(c *gin.Context) {849 var json Login850 if err := c.ShouldBindJSON(&json); err != nil {851 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})852 return853 }854855 if json.User != "manu" || json.Password != "123" {856 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})857 return858 }859860 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})861 })862863 // Example for binding XML (864 // <?xml version="1.0" encoding="UTF-8"?>865 // <root>866 // <user>manu</user>867 // <password>123</password>868 // </root>)869 router.POST("/loginXML", func(c *gin.Context) {870 var xml Login871 if err := c.ShouldBindXML(&xml); err != nil {872 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})873 return874 }875876 if xml.User != "manu" || xml.Password != "123" {877 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})878 return879 }880881 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})882 })883884 // Example for binding a HTML form (user=manu&password=123)885 router.POST("/loginForm", func(c *gin.Context) {886 var form Login887 // This will infer what binder to use depending on the content-type header.888 if err := c.ShouldBind(&form); err != nil {889 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})890 return891 }892893 if form.User != "manu" || form.Password != "123" {894 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})895 return896 }897898 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})899 })900901 // Listen and serve on 0.0.0.0:8080902 router.Run(":8080")903}904```905906Sample request907908```sh909$ curl -v -X POST \910 http://localhost:8080/loginJSON \911 -H 'content-type: application/json' \912 -d '{ "user": "manu" }'913> POST /loginJSON HTTP/1.1914> Host: localhost:8080915> User-Agent: curl/7.51.0916> Accept: */*917> content-type: application/json918> Content-Length: 18919>920* upload completely sent off: 18 out of 18 bytes921< HTTP/1.1 400 Bad Request922< Content-Type: application/json; charset=utf-8923< Date: Fri, 04 Aug 2017 03:51:31 GMT924< Content-Length: 100925<926{"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}927```928929Skip-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.930931### Custom Validators932933It is also possible to register custom validators. See the [example code](https://github.com/gin-gonic/examples/tree/master/custom-validation/server.go).934935```go936package main937938import (939 "net/http"940 "time"941942 "github.com/gin-gonic/gin"943 "github.com/gin-gonic/gin/binding"944 "github.com/go-playground/validator/v10"945)946947// Booking contains binded and validated data.948type Booking struct {949 CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`950 CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`951}952953var bookableDate validator.Func = func(fl validator.FieldLevel) bool {954 date, ok := fl.Field().Interface().(time.Time)955 if ok {956 today := time.Now()957 if today.After(date) {958 return false959 }960 }961 return true962}963964func main() {965 route := gin.Default()966967 if v, ok := binding.Validator.Engine().(*validator.Validate); ok {968 v.RegisterValidation("bookabledate", bookableDate)969 }970971 route.GET("/bookable", getBookable)972 route.Run(":8085")973}974975func getBookable(c *gin.Context) {976 var b Booking977 if err := c.ShouldBindWith(&b, binding.Query); err == nil {978 c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})979 } else {980 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})981 }982}983```984985```console986$ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17"987{"message":"Booking dates are valid!"}988989$ curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09"990{"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"}991992$ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10"993{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}%994```995996[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way.997See the [struct-lvl-validation example](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) to learn more.998999### Only Bind Query String10001001`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).10021003```go1004package main10051006import (1007 "log"1008 "net/http"10091010 "github.com/gin-gonic/gin"1011)10121013type Person struct {1014 Name string `form:"name"`1015 Address string `form:"address"`1016}10171018func main() {1019 route := gin.Default()1020 route.Any("/testing", startPage)1021 route.Run(":8085")1022}10231024func startPage(c *gin.Context) {1025 var person Person1026 if c.ShouldBindQuery(&person) == nil {1027 log.Println("====== Only Bind By Query String ======")1028 log.Println(person.Name)1029 log.Println(person.Address)1030 }1031 c.String(http.StatusOK, "Success")1032}10331034```10351036### Bind Query String or Post Data10371038See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292).10391040```go1041package main10421043import (1044 "log"1045 "net/http"1046 "time"10471048 "github.com/gin-gonic/gin"1049)10501051type Person struct {1052 Name string `form:"name"`1053 Address string `form:"address"`1054 Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`1055 CreateTime time.Time `form:"createTime" time_format:"unixNano"`1056 UnixTime time.Time `form:"unixTime" time_format:"unix"`1057 UnixMilliTime time.Time `form:"unixMilliTime" time_format:"unixmilli"`1058 UnixMicroTime time.Time `form:"unixMicroTime" time_format:"uNiXmIcRo"` // case does not matter for "unix*" time formats1059}10601061func main() {1062 route := gin.Default()1063 route.GET("/testing", startPage)1064 route.Run(":8085")1065}10661067func startPage(c *gin.Context) {1068 var person Person1069 // If `GET`, only `Form` binding engine (`query`) used.1070 // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).1071 // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L881072 if c.ShouldBind(&person) == nil {1073 log.Println(person.Name)1074 log.Println(person.Address)1075 log.Println(person.Birthday)1076 log.Println(person.CreateTime)1077 log.Println(person.UnixTime)1078 log.Println(person.UnixMilliTime)1079 log.Println(person.UnixMicroTime)1080 }10811082 c.String(http.StatusOK, "Success")1083}1084```10851086Test it with:10871088```sh1089curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033&unixMilliTime=1562400033001&unixMicroTime=1562400033000012"1090```10911092### 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 (1100 "net/http"11011102 "github.com/gin-gonic/gin"1103)11041105type Person struct {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() {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```11261127```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"11371138#### Collection format for arrays11391140| Format | Description | Example |1141| --------------- | --------------------------------------------------------- | ----------------------- |1142| multi (default) | Multiple parameter instances rather than multiple values. | key=foo&key=bar&key=baz |1143| csv | Comma-separated values. | foo,bar,baz |1144| ssv | Space-separated values. | foo bar baz |1145| tsv | Tab-separated values. | "foo\tbar\tbaz" |1146| pipes | Pipe-separated values. | foo\|bar\|baz |11471148```go1149package main11501151import (1152 "log"1153 "time"1154 "github.com/gin-gonic/gin"1155)11561157type Person struct {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() {1166 route := gin.Default()1167 route.GET("/testing", startPage)1168 route.Run(":8085")1169}1170func startPage(c *gin.Context) {1171 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 }1182 c.String(200, "Success")1183}1184```11851186Test it with:11871188```sh1189curl -X GET "localhost:8085/testing?name=appleboy&addresses=foo,bar&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"1190```11911192### Bind Uri11931194See the [detail information](https://github.com/gin-gonic/gin/issues/846).11951196```go1197package main11981199import (1200 "net/http"12011202 "github.com/gin-gonic/gin"1203)12041205type Person struct {1206 ID string `uri:"id" binding:"required,uuid"`1207 Name string `uri:"name" binding:"required"`1208}12091210func main() {1211 route := gin.Default()1212 route.GET("/:name/:id", func(c *gin.Context) {1213 var person Person1214 if err := c.ShouldBindUri(&person); err != nil {1215 c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})1216 return1217 }1218 c.JSON(http.StatusOK, gin.H{"name": person.Name, "uuid": person.ID})1219 })1220 route.Run(":8088")1221}1222```12231224Test it with:12251226```sh1227curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f31228curl -v localhost:8088/thinkerou/not-uuid1229```12301231### Bind custom unmarshaler12321233To 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.12341235```go1236package main12371238import (1239 "encoding"1240 "strings"12411242 "github.com/gin-gonic/gin"1243)12441245type Birthday string12461247func (b *Birthday) UnmarshalText(text []byte) error {1248 *b = Birthday(strings.Replace(string(text), "-", "/", -1))1249 return nil1250}12511252var _ encoding.TextUnmarshaler = (*Birthday)(nil) //assert Birthday implements encoding.TextUnmarshaler12531254func main() {1255 route := gin.Default()1256 var request struct {1257 Birthday Birthday `form:"birthday,parser=encoding.TextUnmarshaler"`1258 Birthdays []Birthday `form:"birthdays,parser=encoding.TextUnmarshaler" collection_format:"csv"`1259 BirthdaysDefault []Birthday `form:"birthdaysDef,default=2020-09-01;2020-09-02,parser=encoding.TextUnmarshaler" collection_format:"csv"`1260 }1261 route.GET("/test", func(ctx *gin.Context) {1262 _ = ctx.BindQuery(&request)1263 ctx.JSON(200, request)1264 })1265 _ = route.Run(":8088")1266}1267```12681269Test it with: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---12871288If 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.12891290```go1291package main12921293import (1294 "strings"12951296 "github.com/gin-gonic/gin"1297 "github.com/gin-gonic/gin/binding"1298)12991300type Birthday string13011302func (b *Birthday) UnmarshalParam(param string) error {1303 *b = Birthday(strings.Replace(param, "-", "/", -1))1304 return nil1305}13061307var _ binding.BindUnmarshaler = (*Birthday)(nil) //assert Birthday implements binding.BindUnmarshaler13081309func main() {1310 route := gin.Default()1311 var request struct {1312 Birthday Birthday `form:"birthday"`1313 Birthdays []Birthday `form:"birthdays" collection_format:"csv"`1314 BirthdaysDefault []Birthday `form:"birthdaysDef,default=2020-09-01;2020-09-02" collection_format:"csv"`1315 }1316 route.GET("/test", func(ctx *gin.Context) {1317 _ = ctx.BindQuery(&request)1318 ctx.JSON(200, request)1319 })1320 _ = route.Run(":8088")1321}1322```13231324Test it with: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 Header13421343```go1344package main13451346import (1347 "fmt"1348 "net/http"13491350 "github.com/gin-gonic/gin"1351)13521353type testHeader struct {1354 Rate int `header:"Rate"`1355 Domain string `header:"Domain"`1356}13571358func main() {1359 r := gin.Default()1360 r.GET("/", func(c *gin.Context) {1361 h := testHeader{}13621363 if err := c.ShouldBindHeader(&h); err != nil {1364 c.JSON(http.StatusOK, err)1365 }13661367 fmt.Printf("%#v\n", h)1368 c.JSON(http.StatusOK, gin.H{"Rate": h.Rate, "Domain": h.Domain})1369 })13701371 r.Run()13721373// client1374// curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/1375// output1376// {"Domain":"music","Rate":300}1377}1378```13791380### Bind HTML checkboxes13811382See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)13831384main.go13851386```go1387...13881389type myForm struct {1390 Colors []string `form:"colors[]"`1391}13921393...13941395func formHandler(c *gin.Context) {1396 var fakeForm myForm1397 c.ShouldBind(&fakeForm)1398 c.JSON(http.StatusOK, gin.H{"color": fakeForm.Colors})1399}14001401...14021403```14041405form.html14061407```html1408<form action="/" method="POST">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```json1423{ "color": ["red", "green", "blue"] }1424```14251426### Multipart/Urlencoded binding14271428```go1429type ProfileForm struct {1430 Name string `form:"name" binding:"required"`1431 Avatar *multipart.FileHeader `form:"avatar" binding:"required"`14321433 // or for multiple files1434 // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"`1435}14361437func main() {1438 router := gin.Default()1439 router.POST("/profile", func(c *gin.Context) {1440 // you can bind multipart form with explicit binding declaration:1441 // c.ShouldBindWith(&form, binding.Form)1442 // or you can simply use autobinding with ShouldBind method:1443 var form ProfileForm1444 // in this case proper binding will be automatically selected1445 if err := c.ShouldBind(&form); err != nil {1446 c.String(http.StatusBadRequest, "bad request")1447 return1448 }14491450 err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename)1451 if err != nil {1452 c.String(http.StatusInternalServerError, "unknown error")1453 return1454 }14551456 // db.Save(&form)14571458 c.String(http.StatusOK, "ok")1459 })1460 router.Run(":8080")1461}1462```14631464Test it with:14651466```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() {1670 r := gin.Default()16711672 // gin.H is a shortcut for map[string]any1673 r.GET("/someJSON", func(c *gin.Context) {1674 c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1675 })16761677 r.GET("/moreJSON", func(c *gin.Context) {1678 // You can also use a struct1679 var msg struct {1680 Name string `json:"user"`1681 Message string1682 Number int1683 }1684 msg.Name = "Lena"1685 msg.Message = "hey"1686 msg.Number = 1231687 // Note that msg.Name becomes "user" in the JSON1688 // Will output : {"user": "Lena", "Message": "hey", "Number": 123}1689 c.JSON(http.StatusOK, msg)1690 })16911692 r.GET("/someXML", func(c *gin.Context) {1693 c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1694 })16951696 r.GET("/someYAML", func(c *gin.Context) {1697 c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1698 })16991700 r.GET("/someTOML", func(c *gin.Context) {1701 c.TOML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1702 })17031704 r.GET("/someProtoBuf", func(c *gin.Context) {1705 reps := []int64{int64(1), int64(2)}1706 label := "test"1707 // The specific definition of protobuf is written in the testdata/protoexample file.1708 data := &protoexample.Test{1709 Label: &label,1710 Reps: reps,1711 }1712 // Note that data becomes binary data in the response1713 // Will output protoexample.Test protobuf serialized data1714 c.ProtoBuf(http.StatusOK, data)1715 })17161717 // Listen and serve on 0.0.0.0:80801718 r.Run(":8080")1719}1720```17211722#### SecureJSON17231724Using SecureJSON to prevent json hijacking. Default prepends `"while(1),"` to response body if the given struct is array values.17251726```go1727func main() {1728 r := gin.Default()17291730 // You can also use your own secure json prefix1731 // r.SecureJsonPrefix(")]}',\n")17321733 r.GET("/someJSON", func(c *gin.Context) {1734 names := []string{"lena", "austin", "foo"}17351736 // Will output : while(1);["lena","austin","foo"]1737 c.SecureJSON(http.StatusOK, names)1738 })17391740 // Listen and serve on 0.0.0.0:80801741 r.Run(":8080")1742}1743```17441745#### JSONP17461747Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists.17481749```go1750func main() {1751 r := gin.Default()17521753 r.GET("/JSONP", func(c *gin.Context) {1754 data := gin.H{1755 "foo": "bar",1756 }17571758 //callback is x1759 // Will output : x({\"foo\":\"bar\"})1760 c.JSONP(http.StatusOK, data)1761 })17621763 // Listen and serve on 0.0.0.0:80801764 r.Run(":8080")17651766 // client1767 // curl http://127.0.0.1:8080/JSONP?callback=x1768}1769```17701771#### AsciiJSON17721773Using AsciiJSON to Generates ASCII-only JSON with escaped non-ASCII characters.17741775```go1776func main() {1777 r := gin.Default()17781779 r.GET("/someJSON", func(c *gin.Context) {1780 data := gin.H{1781 "lang": "GO语言",1782 "tag": "<br>",1783 }17841785 // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}1786 c.AsciiJSON(http.StatusOK, data)1787 })17881789 // Listen and serve on 0.0.0.0:80801790 r.Run(":8080")1791}1792```17931794#### PureJSON17951796Normally, 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.1797This feature is unavailable in Go 1.6 and lower.17981799```go1800func main() {1801 r := gin.Default()18021803 // Serves unicode entities1804 r.GET("/json", func(c *gin.Context) {1805 c.JSON(http.StatusOK, gin.H{1806 "html": "<b>Hello, world!</b>",1807 })1808 })18091810 // Serves literal characters1811 r.GET("/purejson", func(c *gin.Context) {1812 c.PureJSON(http.StatusOK, gin.H{1813 "html": "<b>Hello, world!</b>",1814 })1815 })18161817 // listen and serve on 0.0.0.0:80801818 r.Run(":8080")1819}1820```18211822### Serving static files18231824```go1825func main() {1826 router := gin.Default()1827 router.Static("/assets", "./assets")1828 router.StaticFS("/more_static", http.Dir("my_file_system"))1829 router.StaticFile("/favicon.ico", "./resources/favicon.ico")1830 router.StaticFileFS("/more_favicon.ico", "more_favicon.ico", http.Dir("my_file_system"))18311832 // Listen and serve on 0.0.0.0:80801833 router.Run(":8080")1834}1835```18361837### Serving data from file18381839```go1840func main() {1841 router := gin.Default()18421843 router.GET("/local/file", func(c *gin.Context) {1844 c.File("local/file.go")1845 })18461847 var fs http.FileSystem = // ...1848 router.GET("/fs/file", func(c *gin.Context) {1849 c.FileFromFS("fs/file.go", fs)1850 })1851}18521853```18541855### Serving data from reader18561857```go1858func main() {1859 router := gin.Default()1860 router.GET("/someDataFromReader", func(c *gin.Context) {1861 response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")1862 if err != nil || response.StatusCode != http.StatusOK {1863 c.Status(http.StatusServiceUnavailable)1864 return1865 }18661867 reader := response.Body1868 defer reader.Close()1869 contentLength := response.ContentLength1870 contentType := response.Header.Get("Content-Type")18711872 extraHeaders := map[string]string{1873 "Content-Disposition": `attachment; filename="gopher.png"`,1874 }18751876 c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)1877 })1878 router.Run(":8080")1879}1880```18811882### HTML rendering18831884Using LoadHTMLGlob() or LoadHTMLFiles() or LoadHTMLFS()18851886```go1887//go:embed templates/*1888var templates embed.FS18891890func main() {1891 router := gin.Default()1892 router.LoadHTMLGlob("templates/*")1893 //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")1894 //router.LoadHTMLFS(http.Dir("templates"), "template1.html", "template2.html")1895 //or1896 //router.LoadHTMLFS(http.FS(templates), "templates/template1.html", "templates/template2.html")1897 router.GET("/index", func(c *gin.Context) {1898 c.HTML(http.StatusOK, "index.tmpl", gin.H{1899 "title": "Main website",1900 })1901 })1902 router.Run(":8080")1903}1904```19051906templates/index.tmpl19071908```html1909<html>1910 <h1>{{ .title }}</h1>1911</html>1912```19131914Using templates with same name in different directories19151916```go1917func main() {1918 router := gin.Default()1919 router.LoadHTMLGlob("templates/**/*")1920 router.GET("/posts/index", func(c *gin.Context) {1921 c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{1922 "title": "Posts",1923 })1924 })1925 router.GET("/users/index", func(c *gin.Context) {1926 c.HTML(http.StatusOK, "users/index.tmpl", gin.H{1927 "title": "Users",1928 })1929 })1930 router.Run(":8080")1931}1932```19331934templates/posts/index.tmpl19351936```html1937{{ define "posts/index.tmpl" }}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" }}1949<html>1950 <h1>{{ .title }}</h1>1951 <p>Using users/index.tmpl</p>1952</html>1953{{ end }}1954```19551956#### Custom Template renderer19571958You can also use your own html template render19591960```go1961import "html/template"19621963func main() {1964 router := gin.Default()1965 html := template.Must(template.ParseFiles("file1", "file2"))1966 router.SetHTMLTemplate(html)1967 router.Run(":8080")1968}1969```19701971#### Custom Delimiters19721973You may use custom delims19741975```go1976 r := gin.Default()1977 r.Delims("{[{", "}]}")1978 r.LoadHTMLGlob("/path/to/templates")1979```19801981#### Custom Template Funcs19821983See the detailed [example code](https://github.com/gin-gonic/examples/tree/master/template).19841985main.go19861987```go1988import (1989 "fmt"1990 "html/template"1991 "net/http"1992 "time"19931994 "github.com/gin-gonic/gin"1995)19961997func formatAsDate(t time.Time) string {1998 year, month, day := t.Date()1999 return fmt.Sprintf("%d/%02d/%02d", year, month, day)2000}

The first 2,000 of 2,666 lines.