doc.md
This file
Path
docs/doc.md
2,708 lines · 68.8 KiB · Markdown
Last changed by
docs: fix the graceful shutdown example (#4809)Wahid Rizka Fathurrohmanbefore adoption8ad9f9c
History of this fileTake it
The walk stopped after 200 commits: lines older than 255af88 point at it.
chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 1–6why, one step back1# Gin Quick Start23## 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 back7 - [Build without MsgPack rendering feature](#build-without-msgpack-rendering-feature)8- [Routing](#routing)chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 9why, one step back9 - [Using GET, POST, PUT, PATCH, DELETE and OPTIONS](#using-get-post-put-patch-delete-and-options)feat(gin): add support for the HTTP QUERY method (RFC 10008) (#4806)Gaurav Patilbefore adoptionb1f77cf
line 10why, one step back10 - [Using the QUERY method](#using-the-query-method)chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 11–20why, one step back11 - [Parameters in path](#parameters-in-path)12 - [Querystring parameters](#querystring-parameters)13 - [Multipart/Urlencoded Form](#multiparturlencoded-form)14 - [Another example: query + post form](#another-example-query--post-form)15 - [Map as querystring or postform parameters](#map-as-querystring-or-postform-parameters)16 - [Upload files](#upload-files)17 - [Single file](#single-file)18 - [Multiple files](#multiple-files)19 - [Grouping routes](#grouping-routes)20 - [Redirects](#redirects)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 21–23why, one step back21- [Middleware](#middleware)22 - [Blank Gin without middleware by default](#blank-gin-without-middleware-by-default)23 - [Using middleware](#using-middleware)chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 24why, one step back24 - [Custom Middleware](#custom-middleware)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 25why, one step back25 - [Custom Recovery behavior](#custom-recovery-behavior)chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 26–27why, one step back26 - [Using BasicAuth() middleware](#using-basicauth-middleware)27 - [Goroutines inside a middleware](#goroutines-inside-a-middleware)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 28–33why, one step back28- [Logging](#logging)29 - [How to write log file](#how-to-write-log-file)30 - [Custom Log Format](#custom-log-format)31 - [Skip logging](#skip-logging)32 - [Controlling Log output coloring](#controlling-log-output-coloring)33 - [Avoid logging query strings](#avoid-logging-query-strings)chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 34why, one step back34 - [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 35–66why, one step back35- [Request Binding & Validation](#request-binding--validation)36 - [Model binding and validation](#model-binding-and-validation)37 - [Custom Validators](#custom-validators)38 - [Only Bind Query String](#only-bind-query-string)39 - [Bind Query String or Post Data](#bind-query-string-or-post-data)40 - [Bind default value if none provided](#bind-default-value-if-none-provided)41 - [Collection format for arrays](#collection-format-for-arrays)42 - [Bind Uri](#bind-uri)43 - [Bind custom unmarshaler](#bind-custom-unmarshaler)44 - [Bind Header](#bind-header)45 - [Bind HTML checkboxes](#bind-html-checkboxes)46 - [Multipart/Urlencoded binding](#multiparturlencoded-binding)47 - [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct)48 - [Try to bind body into different structs](#try-to-bind-body-into-different-structs)49 - [Bind form-data request with custom struct and custom tag](#bind-form-data-request-with-custom-struct-and-custom-tag)50- [Response Rendering](#response-rendering)51 - [XML, JSON, YAML, TOML and ProtoBuf rendering](#xml-json-yaml-toml-and-protobuf-rendering)52 - [SecureJSON](#securejson)53 - [JSONP](#jsonp)54 - [AsciiJSON](#asciijson)55 - [PureJSON](#purejson)56 - [Serving static files](#serving-static-files)57 - [Serving data from file](#serving-data-from-file)58 - [Serving data from reader](#serving-data-from-reader)59 - [HTML rendering](#html-rendering)60 - [Custom Template renderer](#custom-template-renderer)61 - [Custom Delimiters](#custom-delimiters)62 - [Custom Template Funcs](#custom-template-funcs)63 - [Multitemplate](#multitemplate)64 - [Build a single binary with templates](#build-a-single-binary-with-templates)65- [Server Configuration](#server-configuration)66 - [Custom HTTP configuration](#custom-http-configuration)feat: support custom json codec at runtime (#3391)Timbefore adoption688a429
line 67why, one step back67 - [Custom json codec at runtime](#custom-json-codec-at-runtime)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 68–75why, one step back68 - [Support Let's Encrypt](#support-lets-encrypt)69 - [Run multiple service using Gin](#run-multiple-service-using-gin)70 - [Graceful shutdown or restart](#graceful-shutdown-or-restart)71 - [Third-party packages](#third-party-packages)72 - [Manually](#manually)73 - [http2 server push](#http2-server-push)74 - [Set and get a cookie](#set-and-get-a-cookie)75 - [Don't trust all proxies](#dont-trust-all-proxies)chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 76why, one step back76- [Testing](#testing)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 77why, one step back77chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 78why, one step back78You 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 79–117why, one step back7980## Build tags8182### Build with json replacement8384Gin uses `encoding/json` as the default JSON package but you can change it by building from other tags.8586[jsoniter](https://github.com/json-iterator/go)8788```sh89go build -tags=jsoniter .90```9192[go-json](https://github.com/goccy/go-json)9394```sh95go build -tags=go_json .96```9798[sonic](https://github.com/bytedance/sonic)99100```sh101go build -tags=sonic .102```103104### Build without `MsgPack` rendering feature105106Gin enables `MsgPack` rendering feature by default. But you can disable this feature by specifying `nomsgpack` build tag.107108```sh109go build -tags=nomsgpack .110```111112This is useful to reduce the binary size of executable files. See the [detail information](https://github.com/gin-gonic/gin/pull/1852).113114## Routing115116> Learn how to define routes, handle parameters, and organize endpoints.117chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 118why, one step back118### Using GET, POST, PUT, PATCH, DELETE and OPTIONSdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 119–125why, one step back119120```go121func main() {122 // Creates a gin router with default middleware:123 // logger and recovery (crash-free) middleware124 router := gin.Default()125chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 126–132why, one step back126 router.GET("/someGet", getting)127 router.POST("/somePost", posting)128 router.PUT("/somePut", putting)129 router.DELETE("/someDelete", deleting)130 router.PATCH("/somePatch", patching)131 router.HEAD("/someHead", head)132 router.OPTIONS("/someOptions", options)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 133why, one step back133chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 134–135why, one step back134 // By default, it serves on :8080 unless a135 // PORT environment variable was defined.docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 136why, one step back136 router.Run()chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 137why, one step back137 // router.Run(":3000") for a hard coded portfeat(gin): add support for the HTTP QUERY method (RFC 10008) (#4806)Gaurav Patilbefore adoptionb1f77cf
lines 138–177why, one step back138}139```140141### Using the QUERY method142143`QUERY` is the safe and idempotent method defined by [RFC 10008](https://www.rfc-editor.org/info/rfc10008/). It carries its query in the request body, so you can send a query that is too large or too structured for a URL without turning it into a `POST`.144145```go146func main() {147 router := gin.Default()148149 router.QUERY("/search", func(c *gin.Context) {150 var query struct {151 Term string `json:"term"`152 }153 if err := c.ShouldBindJSON(&query); err != nil {154 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})155 return156 }157 c.JSON(http.StatusOK, gin.H{"term": query.Term})158 })159160 router.Run()161}162```163164Use the `gin.MethodQuery` constant wherever an HTTP method name is expected, for example when building a request in a test:165166```go167req := httptest.NewRequest(gin.MethodQuery, "/search", body)168```169170Two things to keep in mind:171172- `router.Any` does not register `QUERY`, so existing catch-all routes keep matching exactly the methods they matched before. Use `router.QUERY` or `router.Match([]string{gin.MethodQuery, http.MethodPost}, ...)` when you want it.173- `QUERY` is not part of the `gin.IRoutes` interface. `*gin.Engine` and `*gin.RouterGroup` expose it directly; if you only hold an `IRoutes` value, assert to `gin.IQueryRoutes` first.174175```go176if q, ok := routes.(gin.IQueryRoutes); ok {177 q.QUERY("/search", searching)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 178–180why, one step back178}179```180chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 181why, one step back181### Parameters in pathdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 182–186why, one step back182183```go184func main() {185 router := gin.Default()186chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 187–188why, one step back187 // This handler will match /user/john but will not match /user/ or /user188 router.GET("/user/:name", func(c *gin.Context) {docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 189why, one step back189 name := c.Param("name")chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 190why, one step back190 c.String(http.StatusOK, "Hello %s", name)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 191–192why, one step back191 })192chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 193–195why, one step back193 // However, this one will match /user/john/ and also /user/john/send194 // If no other routers match /user/john, it will redirect to /user/john/195 router.GET("/user/:name/*action", func(c *gin.Context) {docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 196why, one step back196 name := c.Param("name")chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 197–199why, one step back197 action := c.Param("action")198 message := name + " is " + action199 c.String(http.StatusOK, message)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 200–201why, one step back200 })201chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 202–205why, one step back202 // For each matched request Context will hold the route definition203 router.POST("/user/:name/*action", func(c *gin.Context) {204 b := c.FullPath() == "/user/:name/*action" // true205 c.String(http.StatusOK, "%t", b)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 206–207why, one step back206 })207chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 208–212why, one step back208 // This handler will add a new router for /user/groups.209 // Exact routes are resolved before param routes, regardless of the order they were defined.210 // Routes starting with /user/groups are never interpreted as /user/:name/... routes211 router.GET("/user/groups", func(c *gin.Context) {212 c.String(http.StatusOK, "The available groups are [...]")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 213–218why, one step back213 })214215 router.Run(":8080")216}217```218chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 219why, one step back219### Querystring parametersdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 220–224why, one step back220221```go222func main() {223 router := gin.Default()224chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 225–229why, one step back225 // Query string parameters are parsed using the existing underlying request object.226 // The request responds to a URL matching: /welcome?firstname=Jane&lastname=Doe227 router.GET("/welcome", func(c *gin.Context) {228 firstname := c.DefaultQuery("firstname", "Guest")229 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 230why, one step back230chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 231why, one step back231 c.String(http.StatusOK, "Hello %s %s", firstname, lastname)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 232–236why, one step back232 })233 router.Run(":8080")234}235```236chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 237why, one step back237### Multipart/Urlencoded Formdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 238–242why, one step back238239```go240func main() {241 router := gin.Default()242chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 243why, one step back243 router.POST("/form_post", func(c *gin.Context) {docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 244why, one step back244 message := c.PostForm("message")chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 245why, one step back245 nick := c.DefaultPostForm("nick", "anonymous")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 246–247why, one step back246247 c.JSON(http.StatusOK, gin.H{chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 248–250why, one step back248 "status": "posted",249 "message": message,250 "nick": nick,docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 251–256why, one step back251 })252 })253 router.Run(":8080")254}255```256chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 257why, one step back257### Another example: query + post formdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 258–259why, one step back258259```shchore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 260why, one step back260POST /post?id=1234&page=1 HTTP/1.1docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 261–262why, one step back261Content-Type: application/x-www-form-urlencoded262chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 263why, one step back263name=manu&message=this_is_greatdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 264–271why, one step back264```265266```go267func main() {268 router := gin.Default()269270 router.POST("/post", func(c *gin.Context) {271chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 272–274why, one step back272 id := c.Query("id")273 page := c.DefaultQuery("page", "0")274 name := c.PostForm("name")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 275–276why, one step back275 message := c.PostForm("message")276chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 277why, one step back277 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 278–283why, one step back278 })279 router.Run(":8080")280}281```282283```shchore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 284why, one step back284id: 1234; page: 1; name: manu; message: this_is_greatdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 285–286why, one step back285```286chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 287why, one step back287### Map as querystring or postform parametersdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 288–289why, one step back288289```shchore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 290why, one step back290POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 291–292why, one step back291Content-Type: application/x-www-form-urlencoded292chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 293why, one step back293names[first]=thinkerou&names[second]=tianoudocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 294–301why, one step back294```295296```go297func main() {298 router := gin.Default()299300 router.POST("/post", func(c *gin.Context) {301chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 302–303why, one step back302 ids := c.QueryMap("ids")303 names := c.PostFormMap("names")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 304why, one step back304chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 305why, one step back305 fmt.Printf("ids: %v; names: %v", ids, names)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 306–311why, one step back306 })307 router.Run(":8080")308}309```310311```shchore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 312why, one step back312ids: 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 313–314why, one step back313```314chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 315why, one step back315### Upload filesdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 316why, one step back316chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 317why, one step back317#### Single filedocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 318why, one step back318chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 319why, one step back319References 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 320why, one step back320chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 321why, one step back321`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 322why, one step back322chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 323why, one step back323> 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 324–330why, one step back324325```go326func main() {327 router := gin.Default()328 // Set a lower memory limit for multipart forms (default is 32 MiB)329 router.MaxMultipartMemory = 8 << 20 // 8 MiB330 router.POST("/upload", func(c *gin.Context) {chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 331–333why, one step back331 // Single file332 file, _ := c.FormFile("file")333 log.Println(file.Filename)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 334why, one step back334chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 335–336why, one step back335 // Upload the file to specific dst.336 c.SaveUploadedFile(file, dst)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 337why, one step back337chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 338why, one step back338 c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 339–347why, one step back339 })340 router.Run(":8080")341}342```343344How to `curl`:345346```bash347curl -X POST http://localhost:8080/upload \chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 348why, one step back348 -F "file=@/Users/appleboy/test.zip" \docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 349–351why, one step back349 -H "Content-Type: multipart/form-data"350```351chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 352why, one step back352#### Multiple filesdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 353why, one step back353chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 354why, one step back354See 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 355–361why, one step back355356```go357func main() {358 router := gin.Default()359 // Set a lower memory limit for multipart forms (default is 32 MiB)360 router.MaxMultipartMemory = 8 << 20 // 8 MiB361 router.POST("/upload", func(c *gin.Context) {chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 362–364why, one step back362 // Multipart form363 form, _ := c.MultipartForm()364 files := form.File["upload[]"]docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 365why, one step back365chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 366–367why, one step back366 for _, file := range files {367 log.Println(file.Filename)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 368why, one step back368chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 369–370why, one step back369 // Upload the file to specific dst.370 c.SaveUploadedFile(file, dst)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 371why, one step back371 }chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 372why, one step back372 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 373–381why, one step back373 })374 router.Run(":8080")375}376```377378How to `curl`:379380```bash381curl -X POST http://localhost:8080/upload \chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 382–383why, one step back382 -F "upload[]=@/Users/appleboy/test1.zip" \383 -F "upload[]=@/Users/appleboy/test2.zip" \docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 384–386why, one step back384 -H "Content-Type: multipart/form-data"385```386chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 387why, one step back387### Grouping routesdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 388–392why, one step back388389```go390func main() {391 router := gin.Default()392chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 393why, one step back393 // Simple group: v1docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 394why, one step back394 {chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 395–398why, one step back395 v1 := router.Group("/v1")396 v1.POST("/login", loginEndpoint)397 v1.POST("/submit", submitEndpoint)398 v1.POST("/read", readEndpoint)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 399–400why, one step back399 }400chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 401why, one step back401 // Simple group: v2docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 402why, one step back402 {chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 403–406why, one step back403 v2 := router.Group("/v2")404 v2.POST("/login", loginEndpoint)405 v2.POST("/submit", submitEndpoint)406 v2.POST("/read", readEndpoint)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 407–412why, one step back407 }408409 router.Run(":8080")410}411```412chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 413why, one step back413### Redirectsdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 414why, one step back414chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 415why, one step back415Issuing 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 416–418why, one step back416417```go418r.GET("/test", func(c *gin.Context) {chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 419why, one step back419 c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 420–422why, one step back420})421```422chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 423why, one step back423Issuing 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 424–425why, one step back424425```gochore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 426–427why, one step back426r.POST("/test", func(c *gin.Context) {427 c.Redirect(http.StatusFound, "/foo")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 428–430why, one step back428})429```430chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 431why, one step back431Issuing a Router redirect, use `HandleContext` like below.docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 432–434why, one step back432433```go434r.GET("/test", func(c *gin.Context) {chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 435–436why, one step back435 c.Request.URL.Path = "/test2"436 r.HandleContext(c)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 437why, one step back437})chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 438–439why, one step back438r.GET("/test2", func(c *gin.Context) {439 c.JSON(http.StatusOK, gin.H{"hello": "world"})docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 440–502why, one step back440})441```442443## Middleware444445> Configure middleware for request processing, authentication, and error recovery.446447### Blank Gin without middleware by default448449Use450451```go452r := gin.New()453```454455instead of456457```go458// Default With the Logger and Recovery middleware already attached459r := gin.Default()460```461462### Using middleware463464```go465func main() {466 // Creates a router without any middleware by default467 r := gin.New()468469 // Global middleware470 // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.471 // By default gin.DefaultWriter = os.Stdout472 r.Use(gin.Logger())473474 // Recovery middleware recovers from any panics and writes a 500 if there was one.475 r.Use(gin.Recovery())476477 // Per route middleware, you can add as many as you desire.478 r.GET("/benchmark", MyBenchLogger(), benchEndpoint)479480 // Authorization group481 // authorized := r.Group("/", AuthRequired())482 // exactly the same as:483 authorized := r.Group("/")484 // per group middleware! in this case we use the custom created485 // AuthRequired() middleware just in the "authorized" group.486 authorized.Use(AuthRequired())487 {488 authorized.POST("/login", loginEndpoint)489 authorized.POST("/submit", submitEndpoint)490 authorized.POST("/read", readEndpoint)491492 // nested group493 testing := authorized.Group("testing")494 // visit 0.0.0.0:8080/testing/analytics495 testing.GET("/analytics", analyticsEndpoint)496 }497498 // Listen and serve on 0.0.0.0:8080499 r.Run(":8080")500}501```502chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 503why, one step back503### Custom Middlewaredocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 504–505why, one step back504505```gochore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 506–508why, one step back506func Logger() gin.HandlerFunc {507 return func(c *gin.Context) {508 t := time.Now()docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 509why, one step back509chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 510–511why, one step back510 // Set example variable511 c.Set("example", "12345")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 512why, one step back512chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 513why, one step back513 // before requestdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 514why, one step back514chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 515why, one step back515 c.Next()docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 516why, one step back516chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 517–519why, one step back517 // after request518 latency := time.Since(t)519 log.Print(latency)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 520why, one step back520chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 521–523why, one step back521 // access the status we are sending522 status := c.Writer.Status()523 log.Println(status)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 524–528why, one step back524 }525}526527func main() {528 r := gin.New()chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 529why, one step back529 r.Use(Logger())docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 530why, one step back530chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 531–532why, one step back531 r.GET("/test", func(c *gin.Context) {532 example := c.MustGet("example").(string)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 533why, one step back533chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 534–535why, one step back534 // it would print: "12345"535 log.Println(example)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 536–576why, one step back536 })537538 // Listen and serve on 0.0.0.0:8080539 r.Run(":8080")540}541```542543### Custom Recovery behavior544545```go546func main() {547 // Creates a router without any middleware by default548 r := gin.New()549550 // Global middleware551 // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.552 // By default gin.DefaultWriter = os.Stdout553 r.Use(gin.Logger())554555 // Recovery middleware recovers from any panics and writes a 500 if there was one.556 r.Use(gin.CustomRecovery(func(c *gin.Context, recovered any) {557 if err, ok := recovered.(string); ok {558 c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))559 }560 c.AbortWithStatus(http.StatusInternalServerError)561 }))562563 r.GET("/panic", func(c *gin.Context) {564 // panic with a string -- the custom middleware could save this to a database or report it to the user565 panic("foo")566 })567568 r.GET("/", func(c *gin.Context) {569 c.String(http.StatusOK, "ohai")570 })571572 // Listen and serve on 0.0.0.0:8080573 r.Run(":8080")574}575```576chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 577why, one step back577### Using BasicAuth() middlewaredocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 578–579why, one step back578579```gochore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 580–584why, one step back580// simulate some private data581var secrets = gin.H{582 "foo": gin.H{"email": "foo@bar.com", "phone": "123433"},583 "austin": gin.H{"email": "austin@example.com", "phone": "666"},584 "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 585–589why, one step back585}586587func main() {588 r := gin.Default()589chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 590–596why, one step back590 // Group using gin.BasicAuth() middleware591 // gin.Accounts is a shortcut for map[string]string592 authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{593 "foo": "bar",594 "austin": "1234",595 "lena": "hello2",596 "manu": "4321",docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 597–598why, one step back597 }))598chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 599–607why, one step back599 // /admin/secrets endpoint600 // hit "localhost:8080/admin/secrets601 authorized.GET("/secrets", func(c *gin.Context) {602 // get user, it was set by the BasicAuth middleware603 user := c.MustGet(gin.AuthUserKey).(string)604 if secret, ok := secrets[user]; ok {605 c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})606 } else {607 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 608–615why, one step back608 }609 })610611 // Listen and serve on 0.0.0.0:8080612 r.Run(":8080")613}614```615chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 616why, one step back616### Goroutines inside a middlewaredocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 617why, one step back617chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 618why, one step back618When 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 619–623why, one step back619620```go621func main() {622 r := gin.Default()623chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 624–629why, one step back624 r.GET("/long_async", func(c *gin.Context) {625 // create copy to be used inside the goroutine626 cCp := c.Copy()627 go func() {628 // simulate a long task with time.Sleep(). 5 seconds629 time.Sleep(5 * time.Second)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 630why, one step back630chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 631–633why, one step back631 // note that you are using the copied context "cCp", IMPORTANT632 log.Println("Done! in path " + cCp.Request.URL.Path)633 }()docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 634–635why, one step back634 })635chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 636–637why, one step back636 r.GET("/long_sync", func(c *gin.Context) {637 // simulate a long task with time.Sleep(). 5 secondsdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 638–639why, one step back638 time.Sleep(5 * time.Second)639chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 640–641why, one step back640 // since we are NOT using a goroutine, we do not have to copy the context641 log.Println("Done! in path " + c.Request.URL.Path)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 642–808why, one step back642 })643644 // Listen and serve on 0.0.0.0:8080645 r.Run(":8080")646}647```648649## Logging650651> Control log output, formatting, and filtering.652653### How to write log file654655```go656func main() {657 // Disable Console Color, you don't need console color when writing the logs to file.658 gin.DisableConsoleColor()659660 // Logging to a file.661 f, _ := os.Create("gin.log")662 gin.DefaultWriter = io.MultiWriter(f)663664 // Use the following code if you need to write the logs to file and console at the same time.665 // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)666667 router := gin.Default()668 router.GET("/ping", func(c *gin.Context) {669 c.String(http.StatusOK, "pong")670 })671672 router.Run(":8080")673}674```675676### Custom Log Format677678```go679func main() {680 router := gin.New()681682 // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter683 // By default gin.DefaultWriter = os.Stdout684 router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {685686 // your custom format687 return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",688 param.ClientIP,689 param.TimeStamp.Format(time.RFC1123),690 param.Method,691 param.Path,692 param.Request.Proto,693 param.StatusCode,694 param.Latency,695 param.Request.UserAgent(),696 param.ErrorMessage,697 )698 }))699 router.Use(gin.Recovery())700701 router.GET("/ping", func(c *gin.Context) {702 c.String(http.StatusOK, "pong")703 })704705 router.Run(":8080")706}707```708709Sample Output710711```sh712::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" "713```714715### Skip logging716717```go718func main() {719 router := gin.New()720721 // skip logging for desired paths by setting SkipPaths in LoggerConfig722 loggerConfig := gin.LoggerConfig{SkipPaths: []string{"/metrics"}}723724 // skip logging based on your logic by setting Skip func in LoggerConfig725 loggerConfig.Skip = func(c *gin.Context) bool {726 // as an example skip non server side errors727 return c.Writer.Status() < http.StatusInternalServerError728 }729730 router.Use(gin.LoggerWithConfig(loggerConfig))731 router.Use(gin.Recovery())732733 // skipped734 router.GET("/metrics", func(c *gin.Context) {735 c.Status(http.StatusNotImplemented)736 })737738 // skipped739 router.GET("/ping", func(c *gin.Context) {740 c.String(http.StatusOK, "pong")741 })742743 // not skipped744 router.GET("/data", func(c *gin.Context) {745 c.Status(http.StatusNotImplemented)746 })747748 router.Run(":8080")749}750751```752753### Controlling Log output coloring754755By default, logs output on console should be colorized depending on the detected TTY.756757Never colorize logs:758759```go760func main() {761 // Disable log's color762 gin.DisableConsoleColor()763764 // Creates a gin router with default middleware:765 // logger and recovery (crash-free) middleware766 router := gin.Default()767768 router.GET("/ping", func(c *gin.Context) {769 c.String(http.StatusOK, "pong")770 })771772 router.Run(":8080")773}774```775776Always colorize logs:777778```go779func main() {780 // Force log's color781 gin.ForceConsoleColor()782783 // Creates a gin router with default middleware:784 // logger and recovery (crash-free) middleware785 router := gin.Default()786787 router.GET("/ping", func(c *gin.Context) {788 c.String(http.StatusOK, "pong")789 })790791 router.Run(":8080")792}793```794795### Avoid logging query strings796797```go798func main() {799 router := gin.New()800801 // SkipQueryString indicates that the logger should not log the query string.802 // For example, /path?q=1 will be logged as /path803 loggerConfig := gin.LoggerConfig{SkipQueryString: true}804805 router.Use(gin.LoggerWithConfig(loggerConfig))806}807```808chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 809why, one step back809### Define format for the log of routesdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 810why, one step back810chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 811why, one step back811The default log of routes is:docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 812–813why, one step back812813```shchore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 814–816why, one step back814[GIN-debug] POST /foo --> main.main.func1 (3 handlers)815[GIN-debug] GET /bar --> main.main.func2 (3 handlers)816[GIN-debug] GET /status --> main.main.func3 (3 handlers)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 817–818why, one step back817```818chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 819–820why, one step back819If 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`.820In 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 821–831why, one step back821822```go823import (824 "log"825 "net/http"826827 "github.com/gin-gonic/gin"828)829830func main() {831 r := gin.Default()chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 832–833why, one step back832 gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {833 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 834–835why, one step back834 }835chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 836–837why, one step back836 r.POST("/foo", func(c *gin.Context) {837 c.JSON(http.StatusOK, "foo")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 838–839why, one step back838 })839chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 840–841why, one step back840 r.GET("/bar", func(c *gin.Context) {841 c.JSON(http.StatusOK, "bar")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 842–843why, one step back842 })843chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
lines 844–845why, one step back844 r.GET("/status", func(c *gin.Context) {845 c.JSON(http.StatusOK, "ok")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 846–847why, one step back846 })847chore(deps): bump github.com/go-playground/validator/v10 (#4208)dependabot[bot]before adoption255af88
line 848why, one step back848 // Listen and Server in http://0.0.0.0:8080docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 849–2162why, one step back849 r.Run()850}851```852853## Request Binding & Validation854855> Bind and validate request data from query strings, forms, JSON, and more.856857### Model binding and validation858859To 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).860861Gin 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).862863Note 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"`.864865Also, Gin provides two sets of methods for binding:866867- **Type** - Must bind868 - **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`, `BindHeader`, `BindTOML`869 - **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.870- **Type** - Should bind871 - **Methods** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindXML`, `ShouldBindQuery`, `ShouldBindYAML`, `ShouldBindHeader`, `ShouldBindTOML`,872 - **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.873874When 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`.875876You 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.877878```go879// Binding from JSON880type Login struct {881 User string `form:"user" json:"user" xml:"user" binding:"required"`882 Password string `form:"password" json:"password" xml:"password" binding:"required"`883}884885func main() {886 router := gin.Default()887888 // Example for binding JSON ({"user": "manu", "password": "123"})889 router.POST("/loginJSON", func(c *gin.Context) {890 var json Login891 if err := c.ShouldBindJSON(&json); err != nil {892 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})893 return894 }895896 if json.User != "manu" || json.Password != "123" {897 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})898 return899 }900901 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})902 })903904 // Example for binding XML (905 // <?xml version="1.0" encoding="UTF-8"?>906 // <root>907 // <user>manu</user>908 // <password>123</password>909 // </root>)910 router.POST("/loginXML", func(c *gin.Context) {911 var xml Login912 if err := c.ShouldBindXML(&xml); err != nil {913 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})914 return915 }916917 if xml.User != "manu" || xml.Password != "123" {918 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})919 return920 }921922 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})923 })924925 // Example for binding a HTML form (user=manu&password=123)926 router.POST("/loginForm", func(c *gin.Context) {927 var form Login928 // This will infer what binder to use depending on the content-type header.929 if err := c.ShouldBind(&form); err != nil {930 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})931 return932 }933934 if form.User != "manu" || form.Password != "123" {935 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})936 return937 }938939 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})940 })941942 // Listen and serve on 0.0.0.0:8080943 router.Run(":8080")944}945```946947Sample request948949```sh950$ curl -v -X POST \951 http://localhost:8080/loginJSON \952 -H 'content-type: application/json' \953 -d '{ "user": "manu" }'954> POST /loginJSON HTTP/1.1955> Host: localhost:8080956> User-Agent: curl/7.51.0957> Accept: */*958> content-type: application/json959> Content-Length: 18960>961* upload completely sent off: 18 out of 18 bytes962< HTTP/1.1 400 Bad Request963< Content-Type: application/json; charset=utf-8964< Date: Fri, 04 Aug 2017 03:51:31 GMT965< Content-Length: 100966<967{"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}968```969970Skip-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.971972### Custom Validators973974It is also possible to register custom validators. See the [example code](https://github.com/gin-gonic/examples/tree/master/custom-validation/server.go).975976```go977package main978979import (980 "net/http"981 "time"982983 "github.com/gin-gonic/gin"984 "github.com/gin-gonic/gin/binding"985 "github.com/go-playground/validator/v10"986)987988// Booking contains binded and validated data.989type Booking struct {990 CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`991 CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`992}993994var bookableDate validator.Func = func(fl validator.FieldLevel) bool {995 date, ok := fl.Field().Interface().(time.Time)996 if ok {997 today := time.Now()998 if today.After(date) {999 return false1000 }1001 }1002 return true1003}10041005func main() {1006 route := gin.Default()10071008 if v, ok := binding.Validator.Engine().(*validator.Validate); ok {1009 v.RegisterValidation("bookabledate", bookableDate)1010 }10111012 route.GET("/bookable", getBookable)1013 route.Run(":8085")1014}10151016func getBookable(c *gin.Context) {1017 var b Booking1018 if err := c.ShouldBindWith(&b, binding.Query); err == nil {1019 c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})1020 } else {1021 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})1022 }1023}1024```10251026```console1027$ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17"1028{"message":"Booking dates are valid!"}10291030$ curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09"1031{"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"}10321033$ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10"1034{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}%1035```10361037[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way.1038See the [struct-lvl-validation example](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) to learn more.10391040### Only Bind Query String10411042`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).10431044```go1045package main10461047import (1048 "log"1049 "net/http"10501051 "github.com/gin-gonic/gin"1052)10531054type Person struct {1055 Name string `form:"name"`1056 Address string `form:"address"`1057}10581059func main() {1060 route := gin.Default()1061 route.Any("/testing", startPage)1062 route.Run(":8085")1063}10641065func startPage(c *gin.Context) {1066 var person Person1067 if c.ShouldBindQuery(&person) == nil {1068 log.Println("====== Only Bind By Query String ======")1069 log.Println(person.Name)1070 log.Println(person.Address)1071 }1072 c.String(http.StatusOK, "Success")1073}10741075```10761077### Bind Query String or Post Data10781079See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292).10801081```go1082package main10831084import (1085 "log"1086 "net/http"1087 "time"10881089 "github.com/gin-gonic/gin"1090)10911092type Person struct {1093 Name string `form:"name"`1094 Address string `form:"address"`1095 Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`1096 CreateTime time.Time `form:"createTime" time_format:"unixNano"`1097 UnixTime time.Time `form:"unixTime" time_format:"unix"`1098 UnixMilliTime time.Time `form:"unixMilliTime" time_format:"unixmilli"`1099 UnixMicroTime time.Time `form:"unixMicroTime" time_format:"uNiXmIcRo"` // case does not matter for "unix*" time formats1100}11011102func main() {1103 route := gin.Default()1104 route.GET("/testing", startPage)1105 route.Run(":8085")1106}11071108func startPage(c *gin.Context) {1109 var person Person1110 // If `GET`, only `Form` binding engine (`query`) used.1111 // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).1112 // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L881113 if c.ShouldBind(&person) == nil {1114 log.Println(person.Name)1115 log.Println(person.Address)1116 log.Println(person.Birthday)1117 log.Println(person.CreateTime)1118 log.Println(person.UnixTime)1119 log.Println(person.UnixMilliTime)1120 log.Println(person.UnixMicroTime)1121 }11221123 c.String(http.StatusOK, "Success")1124}1125```11261127Test it with:11281129```sh1130curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033&unixMilliTime=1562400033001&unixMicroTime=1562400033000012"1131```11321133### Bind default value if none provided11341135If 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:11361137```go1138package main11391140import (1141 "net/http"11421143 "github.com/gin-gonic/gin"1144)11451146type Person struct {1147 Name string `form:"name,default=William"`1148 Age int `form:"age,default=10"`1149 Friends []string `form:"friends,default=Will;Bill"`1150 Addresses [2]string `form:"addresses,default=foo bar" collection_format:"ssv"`1151 LapTimes []int `form:"lap_times,default=1;2;3" collection_format:"csv"`1152}11531154func main() {1155 g := gin.Default()1156 g.POST("/person", func(c *gin.Context) {1157 var req Person1158 if err := c.ShouldBindQuery(&req); err != nil {1159 c.JSON(http.StatusBadRequest, err)1160 return1161 }1162 c.JSON(http.StatusOK, req)1163 })1164 _ = g.Run("localhost:8080")1165}1166```11671168```sh1169curl -X POST http://localhost:8080/person1170{"Name":"William","Age":10,"Friends":["Will","Bill"],"Colors":["red","blue"],"LapTimes":[1,2,3]}1171```11721173NOTE: For default [collection values](#collection-format-for-arrays), the following rules apply:11741175- Since commas are used to delimit tag options, they are not supported within a default value and will result in undefined behavior1176- For the collection formats "multi" and "csv", a semicolon should be used in place of a comma to delimit default values1177- Since semicolons are used to delimit default values for "multi" and "csv", they are not supported within a default value for "multi" and "csv"11781179#### Collection format for arrays11801181| Format | Description | Example |1182| --------------- | --------------------------------------------------------- | ----------------------- |1183| multi (default) | Multiple parameter instances rather than multiple values. | key=foo&key=bar&key=baz |1184| csv | Comma-separated values. | foo,bar,baz |1185| ssv | Space-separated values. | foo bar baz |1186| tsv | Tab-separated values. | "foo\tbar\tbaz" |1187| pipes | Pipe-separated values. | foo\|bar\|baz |11881189```go1190package main11911192import (1193 "log"1194 "time"1195 "github.com/gin-gonic/gin"1196)11971198type Person struct {1199 Name string `form:"name"`1200 Addresses []string `form:"addresses" collection_format:"csv"`1201 Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`1202 CreateTime time.Time `form:"createTime" time_format:"unixNano"`1203 UnixTime time.Time `form:"unixTime" time_format:"unix"`1204}12051206func main() {1207 route := gin.Default()1208 route.GET("/testing", startPage)1209 route.Run(":8085")1210}1211func startPage(c *gin.Context) {1212 var person Person1213 // If `GET`, only `Form` binding engine (`query`) used.1214 // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).1215 // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L481216 if c.ShouldBind(&person) == nil {1217 log.Println(person.Name)1218 log.Println(person.Addresses)1219 log.Println(person.Birthday)1220 log.Println(person.CreateTime)1221 log.Println(person.UnixTime)1222 }1223 c.String(200, "Success")1224}1225```12261227Test it with:12281229```sh1230curl -X GET "localhost:8085/testing?name=appleboy&addresses=foo,bar&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"1231```12321233### Bind Uri12341235See the [detail information](https://github.com/gin-gonic/gin/issues/846).12361237```go1238package main12391240import (1241 "net/http"12421243 "github.com/gin-gonic/gin"1244)12451246type Person struct {1247 ID string `uri:"id" binding:"required,uuid"`1248 Name string `uri:"name" binding:"required"`1249}12501251func main() {1252 route := gin.Default()1253 route.GET("/:name/:id", func(c *gin.Context) {1254 var person Person1255 if err := c.ShouldBindUri(&person); err != nil {1256 c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})1257 return1258 }1259 c.JSON(http.StatusOK, gin.H{"name": person.Name, "uuid": person.ID})1260 })1261 route.Run(":8088")1262}1263```12641265Test it with:12661267```sh1268curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f31269curl -v localhost:8088/thinkerou/not-uuid1270```12711272### Bind custom unmarshaler12731274To 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.12751276```go1277package main12781279import (1280 "encoding"1281 "strings"12821283 "github.com/gin-gonic/gin"1284)12851286type Birthday string12871288func (b *Birthday) UnmarshalText(text []byte) error {1289 *b = Birthday(strings.Replace(string(text), "-", "/", -1))1290 return nil1291}12921293var _ encoding.TextUnmarshaler = (*Birthday)(nil) //assert Birthday implements encoding.TextUnmarshaler12941295func main() {1296 route := gin.Default()1297 var request struct {1298 Birthday Birthday `form:"birthday,parser=encoding.TextUnmarshaler"`1299 Birthdays []Birthday `form:"birthdays,parser=encoding.TextUnmarshaler" collection_format:"csv"`1300 BirthdaysDefault []Birthday `form:"birthdaysDef,default=2020-09-01;2020-09-02,parser=encoding.TextUnmarshaler" collection_format:"csv"`1301 }1302 route.GET("/test", func(ctx *gin.Context) {1303 _ = ctx.BindQuery(&request)1304 ctx.JSON(200, request)1305 })1306 _ = route.Run(":8088")1307}1308```13091310Test it with:13111312```sh1313curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02'1314```13151316Result13171318```sh1319{"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]}1320```13211322Note:13231324- 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.1325- 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.13261327---13281329If 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.13301331```go1332package main13331334import (1335 "strings"13361337 "github.com/gin-gonic/gin"1338 "github.com/gin-gonic/gin/binding"1339)13401341type Birthday string13421343func (b *Birthday) UnmarshalParam(param string) error {1344 *b = Birthday(strings.Replace(param, "-", "/", -1))1345 return nil1346}13471348var _ binding.BindUnmarshaler = (*Birthday)(nil) //assert Birthday implements binding.BindUnmarshaler13491350func main() {1351 route := gin.Default()1352 var request struct {1353 Birthday Birthday `form:"birthday"`1354 Birthdays []Birthday `form:"birthdays" collection_format:"csv"`1355 BirthdaysDefault []Birthday `form:"birthdaysDef,default=2020-09-01;2020-09-02" collection_format:"csv"`1356 }1357 route.GET("/test", func(ctx *gin.Context) {1358 _ = ctx.BindQuery(&request)1359 ctx.JSON(200, request)1360 })1361 _ = route.Run(":8088")1362}1363```13641365Test it with:13661367```sh1368curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02'1369```13701371Result13721373```sh1374{"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]}1375```13761377Note:13781379- 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.1380- If a type returns an error from its implementation of `BindUnmarshaler`, gin will stop binding and return the error to the client.13811382### Bind Header13831384```go1385package main13861387import (1388 "fmt"1389 "net/http"13901391 "github.com/gin-gonic/gin"1392)13931394type testHeader struct {1395 Rate int `header:"Rate"`1396 Domain string `header:"Domain"`1397}13981399func main() {1400 r := gin.Default()1401 r.GET("/", func(c *gin.Context) {1402 h := testHeader{}14031404 if err := c.ShouldBindHeader(&h); err != nil {1405 c.JSON(http.StatusOK, err)1406 }14071408 fmt.Printf("%#v\n", h)1409 c.JSON(http.StatusOK, gin.H{"Rate": h.Rate, "Domain": h.Domain})1410 })14111412 r.Run()14131414// client1415// curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/1416// output1417// {"Domain":"music","Rate":300}1418}1419```14201421### Bind HTML checkboxes14221423See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)14241425main.go14261427```go1428...14291430type myForm struct {1431 Colors []string `form:"colors[]"`1432}14331434...14351436func formHandler(c *gin.Context) {1437 var fakeForm myForm1438 c.ShouldBind(&fakeForm)1439 c.JSON(http.StatusOK, gin.H{"color": fakeForm.Colors})1440}14411442...14431444```14451446form.html14471448```html1449<form action="/" method="POST">1450 <p>Check some colors</p>1451 <label for="red">Red</label>1452 <input type="checkbox" name="colors[]" value="red" id="red" />1453 <label for="green">Green</label>1454 <input type="checkbox" name="colors[]" value="green" id="green" />1455 <label for="blue">Blue</label>1456 <input type="checkbox" name="colors[]" value="blue" id="blue" />1457 <input type="submit" />1458</form>1459```14601461result:14621463```json1464{ "color": ["red", "green", "blue"] }1465```14661467### Multipart/Urlencoded binding14681469```go1470type ProfileForm struct {1471 Name string `form:"name" binding:"required"`1472 Avatar *multipart.FileHeader `form:"avatar" binding:"required"`14731474 // or for multiple files1475 // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"`1476}14771478func main() {1479 router := gin.Default()1480 router.POST("/profile", func(c *gin.Context) {1481 // you can bind multipart form with explicit binding declaration:1482 // c.ShouldBindWith(&form, binding.Form)1483 // or you can simply use autobinding with ShouldBind method:1484 var form ProfileForm1485 // in this case proper binding will be automatically selected1486 if err := c.ShouldBind(&form); err != nil {1487 c.String(http.StatusBadRequest, "bad request")1488 return1489 }14901491 err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename)1492 if err != nil {1493 c.String(http.StatusInternalServerError, "unknown error")1494 return1495 }14961497 // db.Save(&form)14981499 c.String(http.StatusOK, "ok")1500 })1501 router.Run(":8080")1502}1503```15041505Test it with:15061507```sh1508curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile1509```15101511### Bind form-data request with custom struct15121513The follow example using custom struct:15141515```go1516type StructA struct {1517 FieldA string `form:"field_a"`1518}15191520type StructB struct {1521 NestedStruct StructA1522 FieldB string `form:"field_b"`1523}15241525type StructC struct {1526 NestedStructPointer *StructA1527 FieldC string `form:"field_c"`1528}15291530type StructD struct {1531 NestedAnonyStruct struct {1532 FieldX string `form:"field_x"`1533 }1534 FieldD string `form:"field_d"`1535}15361537func GetDataB(c *gin.Context) {1538 var b StructB1539 c.Bind(&b)1540 c.JSON(http.StatusOK, gin.H{1541 "a": b.NestedStruct,1542 "b": b.FieldB,1543 })1544}15451546func GetDataC(c *gin.Context) {1547 var b StructC1548 c.Bind(&b)1549 c.JSON(http.StatusOK, gin.H{1550 "a": b.NestedStructPointer,1551 "c": b.FieldC,1552 })1553}15541555func GetDataD(c *gin.Context) {1556 var b StructD1557 c.Bind(&b)1558 c.JSON(http.StatusOK, gin.H{1559 "x": b.NestedAnonyStruct,1560 "d": b.FieldD,1561 })1562}15631564func main() {1565 r := gin.Default()1566 r.GET("/getb", GetDataB)1567 r.GET("/getc", GetDataC)1568 r.GET("/getd", GetDataD)15691570 r.Run()1571}1572```15731574Using the command `curl` command result:15751576```sh1577$ curl "http://localhost:8080/getb?field_a=hello&field_b=world"1578{"a":{"FieldA":"hello"},"b":"world"}1579$ curl "http://localhost:8080/getc?field_a=hello&field_c=world"1580{"a":{"FieldA":"hello"},"c":"world"}1581$ curl "http://localhost:8080/getd?field_x=hello&field_d=world"1582{"d":"world","x":{"FieldX":"hello"}}1583```15841585### Try to bind body into different structs15861587The normal methods for binding request body consumes `c.Request.Body` and they1588cannot be called multiple times.15891590```go1591type formA struct {1592 Foo string `json:"foo" xml:"foo" binding:"required"`1593}15941595type formB struct {1596 Bar string `json:"bar" xml:"bar" binding:"required"`1597}15981599func SomeHandler(c *gin.Context) {1600 objA := formA{}1601 objB := formB{}1602 // Calling c.ShouldBind consumes c.Request.Body and it cannot be reused.1603 if errA := c.ShouldBind(&objA); errA == nil {1604 c.String(http.StatusOK, `the body should be formA`)1605 // Always an error is occurred by this because c.Request.Body is EOF now.1606 } else if errB := c.ShouldBind(&objB); errB == nil {1607 c.String(http.StatusOK, `the body should be formB`)1608 } else {1609 ...1610 }1611}1612```16131614For this, you can use `c.ShouldBindBodyWith` or shortcuts.16151616- `c.ShouldBindBodyWithJSON` is a shortcut for c.ShouldBindBodyWith(obj, binding.JSON).1617- `c.ShouldBindBodyWithXML` is a shortcut for c.ShouldBindBodyWith(obj, binding.XML).1618- `c.ShouldBindBodyWithYAML` is a shortcut for c.ShouldBindBodyWith(obj, binding.YAML).1619- `c.ShouldBindBodyWithTOML` is a shortcut for c.ShouldBindBodyWith(obj, binding.TOML).16201621```go1622func SomeHandler(c *gin.Context) {1623 objA := formA{}1624 objB := formB{}1625 // This reads c.Request.Body and stores the result into the context.1626 if errA := c.ShouldBindBodyWith(&objA, binding.Form); errA == nil {1627 c.String(http.StatusOK, `the body should be formA`)1628 // At this time, it reuses body stored in the context.1629 } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {1630 c.String(http.StatusOK, `the body should be formB JSON`)1631 // And it can accepts other formats1632 } else if errB2 := c.ShouldBindBodyWithXML(&objB); errB2 == nil {1633 c.String(http.StatusOK, `the body should be formB XML`)1634 } else {1635 ...1636 }1637}1638```163916401. `c.ShouldBindBodyWith` stores body into the context before binding. This has1641 a slight impact to performance, so you should not use this method if you are1642 enough to call binding at once.16432. This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`,1644 `ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`,1645 can be called by `c.ShouldBind()` multiple times without any damage to1646 performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)).16471648### Bind form-data request with custom struct and custom tag16491650```go1651const (1652 customerTag = "url"1653 defaultMemory = 32 << 201654)16551656type customerBinding struct {}16571658func (customerBinding) Name() string {1659 return "form"1660}16611662func (customerBinding) Bind(req *http.Request, obj any) error {1663 if err := req.ParseForm(); err != nil {1664 return err1665 }1666 if err := req.ParseMultipartForm(defaultMemory); err != nil {1667 if err != http.ErrNotMultipart {1668 return err1669 }1670 }1671 if err := binding.MapFormWithTag(obj, req.Form, customerTag); err != nil {1672 return err1673 }1674 return validate(obj)1675}16761677func validate(obj any) error {1678 if binding.Validator == nil {1679 return nil1680 }1681 return binding.Validator.ValidateStruct(obj)1682}16831684// Now we can do this!!!1685// FormA is an external type that we can't modify it's tag1686type FormA struct {1687 FieldA string `url:"field_a"`1688}16891690func ListHandler(s *Service) func(ctx *gin.Context) {1691 return func(ctx *gin.Context) {1692 var urlBinding = customerBinding{}1693 var opt FormA1694 err := ctx.MustBindWith(&opt, urlBinding)1695 if err != nil {1696 ...1697 }1698 ...1699 }1700}1701```17021703## Response Rendering17041705> Render responses in various formats including JSON, XML, HTML, and more.17061707### XML, JSON, YAML, TOML and ProtoBuf rendering17081709```go1710func main() {1711 r := gin.Default()17121713 // gin.H is a shortcut for map[string]any1714 r.GET("/someJSON", func(c *gin.Context) {1715 c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1716 })17171718 r.GET("/moreJSON", func(c *gin.Context) {1719 // You can also use a struct1720 var msg struct {1721 Name string `json:"user"`1722 Message string1723 Number int1724 }1725 msg.Name = "Lena"1726 msg.Message = "hey"1727 msg.Number = 1231728 // Note that msg.Name becomes "user" in the JSON1729 // Will output : {"user": "Lena", "Message": "hey", "Number": 123}1730 c.JSON(http.StatusOK, msg)1731 })17321733 r.GET("/someXML", func(c *gin.Context) {1734 c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1735 })17361737 r.GET("/someYAML", func(c *gin.Context) {1738 c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1739 })17401741 r.GET("/someTOML", func(c *gin.Context) {1742 c.TOML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1743 })17441745 r.GET("/someProtoBuf", func(c *gin.Context) {1746 reps := []int64{int64(1), int64(2)}1747 label := "test"1748 // The specific definition of protobuf is written in the testdata/protoexample file.1749 data := &protoexample.Test{1750 Label: &label,1751 Reps: reps,1752 }1753 // Note that data becomes binary data in the response1754 // Will output protoexample.Test protobuf serialized data1755 c.ProtoBuf(http.StatusOK, data)1756 })17571758 // Listen and serve on 0.0.0.0:80801759 r.Run(":8080")1760}1761```17621763#### SecureJSON17641765Using SecureJSON to prevent json hijacking. Default prepends `"while(1),"` to response body if the given struct is array values.17661767```go1768func main() {1769 r := gin.Default()17701771 // You can also use your own secure json prefix1772 // r.SecureJsonPrefix(")]}',\n")17731774 r.GET("/someJSON", func(c *gin.Context) {1775 names := []string{"lena", "austin", "foo"}17761777 // Will output : while(1);["lena","austin","foo"]1778 c.SecureJSON(http.StatusOK, names)1779 })17801781 // Listen and serve on 0.0.0.0:80801782 r.Run(":8080")1783}1784```17851786#### JSONP17871788Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists.17891790```go1791func main() {1792 r := gin.Default()17931794 r.GET("/JSONP", func(c *gin.Context) {1795 data := gin.H{1796 "foo": "bar",1797 }17981799 //callback is x1800 // Will output : x({\"foo\":\"bar\"})1801 c.JSONP(http.StatusOK, data)1802 })18031804 // Listen and serve on 0.0.0.0:80801805 r.Run(":8080")18061807 // client1808 // curl http://127.0.0.1:8080/JSONP?callback=x1809}1810```18111812#### AsciiJSON18131814Using AsciiJSON to Generates ASCII-only JSON with escaped non-ASCII characters.18151816```go1817func main() {1818 r := gin.Default()18191820 r.GET("/someJSON", func(c *gin.Context) {1821 data := gin.H{1822 "lang": "GO语言",1823 "tag": "<br>",1824 }18251826 // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}1827 c.AsciiJSON(http.StatusOK, data)1828 })18291830 // Listen and serve on 0.0.0.0:80801831 r.Run(":8080")1832}1833```18341835#### PureJSON18361837Normally, 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.1838This feature is unavailable in Go 1.6 and lower.18391840```go1841func main() {1842 r := gin.Default()18431844 // Serves unicode entities1845 r.GET("/json", func(c *gin.Context) {1846 c.JSON(http.StatusOK, gin.H{1847 "html": "<b>Hello, world!</b>",1848 })1849 })18501851 // Serves literal characters1852 r.GET("/purejson", func(c *gin.Context) {1853 c.PureJSON(http.StatusOK, gin.H{1854 "html": "<b>Hello, world!</b>",1855 })1856 })18571858 // listen and serve on 0.0.0.0:80801859 r.Run(":8080")1860}1861```18621863### Serving static files18641865```go1866func main() {1867 router := gin.Default()1868 router.Static("/assets", "./assets")1869 router.StaticFS("/more_static", http.Dir("my_file_system"))1870 router.StaticFile("/favicon.ico", "./resources/favicon.ico")1871 router.StaticFileFS("/more_favicon.ico", "more_favicon.ico", http.Dir("my_file_system"))18721873 // Listen and serve on 0.0.0.0:80801874 router.Run(":8080")1875}1876```18771878### Serving data from file18791880```go1881func main() {1882 router := gin.Default()18831884 router.GET("/local/file", func(c *gin.Context) {1885 c.File("local/file.go")1886 })18871888 var fs http.FileSystem = // ...1889 router.GET("/fs/file", func(c *gin.Context) {1890 c.FileFromFS("fs/file.go", fs)1891 })1892}18931894```18951896### Serving data from reader18971898```go1899func main() {1900 router := gin.Default()1901 router.GET("/someDataFromReader", func(c *gin.Context) {1902 response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")1903 if err != nil || response.StatusCode != http.StatusOK {1904 c.Status(http.StatusServiceUnavailable)1905 return1906 }19071908 reader := response.Body1909 defer reader.Close()1910 contentLength := response.ContentLength1911 contentType := response.Header.Get("Content-Type")19121913 extraHeaders := map[string]string{1914 "Content-Disposition": `attachment; filename="gopher.png"`,1915 }19161917 c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)1918 })1919 router.Run(":8080")1920}1921```19221923### HTML rendering19241925Using LoadHTMLGlob() or LoadHTMLFiles() or LoadHTMLFS()19261927```go1928//go:embed templates/*1929var templates embed.FS19301931func main() {1932 router := gin.Default()1933 router.LoadHTMLGlob("templates/*")1934 //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")1935 //router.LoadHTMLFS(http.Dir("templates"), "template1.html", "template2.html")1936 //or1937 //router.LoadHTMLFS(http.FS(templates), "templates/template1.html", "templates/template2.html")1938 router.GET("/index", func(c *gin.Context) {1939 c.HTML(http.StatusOK, "index.tmpl", gin.H{1940 "title": "Main website",1941 })1942 })1943 router.Run(":8080")1944}1945```19461947templates/index.tmpl19481949```html1950<html>1951 <h1>{{ .title }}</h1>1952</html>1953```19541955Using templates with same name in different directories19561957```go1958func main() {1959 router := gin.Default()1960 router.LoadHTMLGlob("templates/**/*")1961 router.GET("/posts/index", func(c *gin.Context) {1962 c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{1963 "title": "Posts",1964 })1965 })1966 router.GET("/users/index", func(c *gin.Context) {1967 c.HTML(http.StatusOK, "users/index.tmpl", gin.H{1968 "title": "Users",1969 })1970 })1971 router.Run(":8080")1972}1973```19741975templates/posts/index.tmpl19761977```html1978{{ define "posts/index.tmpl" }}1979<html>1980 <h1>{{ .title }}</h1>1981 <p>Using posts/index.tmpl</p>1982</html>1983{{ end }}1984```19851986templates/users/index.tmpl19871988```html1989{{ define "users/index.tmpl" }}1990<html>1991 <h1>{{ .title }}</h1>1992 <p>Using users/index.tmpl</p>1993</html>1994{{ end }}1995```19961997#### Custom Template renderer19981999You can also use your own html template render2000The first 2,000 of 2,708 lines.