doc.md
This file
Path
docs/doc.md
2,707 lines · 68.6 KiB · Markdown
Last changed by
feat(routergroup): include HTTP QUERY method in Any (#4878)adam maguedbefore adoptione8f2496
History of this fileTake it
The walk stopped after 200 commits: lines older than 7a1b655 point at it.
fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
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)fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
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)fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
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)fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
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)fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
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)fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
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)fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 76why, one step back76- [Testing](#testing)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 77why, one step back77fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
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.117fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
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()125fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
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 back133fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
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()fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
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–169why, 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```169feat(routergroup): include HTTP QUERY method in Any (#4878)adam maguedbefore adoptione8f2496
line 170why, one step back170Keep in mind:feat(gin): add support for the HTTP QUERY method (RFC 10008) (#4806)Gaurav Patilbefore adoptionb1f77cf
lines 171–176why, one step back171172- `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.173174```go175if q, ok := routes.(gin.IQueryRoutes); ok {176 q.QUERY("/search", searching)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 177–179why, one step back177}178```179fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 180why, one step back180### Parameters in pathdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 181–185why, one step back181182```go183func main() {184 router := gin.Default()185fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 186–187why, one step back186 // This handler will match /user/john but will not match /user/ or /user187 router.GET("/user/:name", func(c *gin.Context) {docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 188why, one step back188 name := c.Param("name")fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 189why, one step back189 c.String(http.StatusOK, "Hello %s", name)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 190–191why, one step back190 })191fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 192–194why, one step back192 // However, this one will match /user/john/ and also /user/john/send193 // If no other routers match /user/john, it will redirect to /user/john/194 router.GET("/user/:name/*action", func(c *gin.Context) {docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 195why, one step back195 name := c.Param("name")fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 196–198why, one step back196 action := c.Param("action")197 message := name + " is " + action198 c.String(http.StatusOK, message)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 199–200why, one step back199 })200fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 201–204why, one step back201 // For each matched request Context will hold the route definition202 router.POST("/user/:name/*action", func(c *gin.Context) {203 b := c.FullPath() == "/user/:name/*action" // true204 c.String(http.StatusOK, "%t", b)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 205–206why, one step back205 })206fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 207–211why, one step back207 // This handler will add a new router for /user/groups.208 // Exact routes are resolved before param routes, regardless of the order they were defined.209 // Routes starting with /user/groups are never interpreted as /user/:name/... routes210 router.GET("/user/groups", func(c *gin.Context) {211 c.String(http.StatusOK, "The available groups are [...]")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 212–217why, one step back212 })213214 router.Run(":8080")215}216```217fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 218why, one step back218### Querystring parametersdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 219–223why, one step back219220```go221func main() {222 router := gin.Default()223fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 224–228why, one step back224 // Query string parameters are parsed using the existing underlying request object.225 // The request responds to a URL matching: /welcome?firstname=Jane&lastname=Doe226 router.GET("/welcome", func(c *gin.Context) {227 firstname := c.DefaultQuery("firstname", "Guest")228 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 229why, one step back229fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 230why, one step back230 c.String(http.StatusOK, "Hello %s %s", firstname, lastname)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 231–235why, one step back231 })232 router.Run(":8080")233}234```235fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 236why, one step back236### Multipart/Urlencoded Formdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 237–241why, one step back237238```go239func main() {240 router := gin.Default()241fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 242why, one step back242 router.POST("/form_post", func(c *gin.Context) {docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 243why, one step back243 message := c.PostForm("message")fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 244why, one step back244 nick := c.DefaultPostForm("nick", "anonymous")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 245–246why, one step back245246 c.JSON(http.StatusOK, gin.H{fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 247–249why, one step back247 "status": "posted",248 "message": message,249 "nick": nick,docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 250–255why, one step back250 })251 })252 router.Run(":8080")253}254```255fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 256why, one step back256### Another example: query + post formdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 257–258why, one step back257258```shfix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 259why, one step back259POST /post?id=1234&page=1 HTTP/1.1docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 260–261why, one step back260Content-Type: application/x-www-form-urlencoded261fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 262why, one step back262name=manu&message=this_is_greatdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 263–270why, one step back263```264265```go266func main() {267 router := gin.Default()268269 router.POST("/post", func(c *gin.Context) {270fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 271–273why, one step back271 id := c.Query("id")272 page := c.DefaultQuery("page", "0")273 name := c.PostForm("name")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 274–275why, one step back274 message := c.PostForm("message")275fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 276why, one step back276 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 277–282why, one step back277 })278 router.Run(":8080")279}280```281282```shfix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 283why, one step back283id: 1234; page: 1; name: manu; message: this_is_greatdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 284–285why, one step back284```285fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 286why, one step back286### Map as querystring or postform parametersdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 287–288why, one step back287288```shfix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 289why, one step back289POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 290–291why, one step back290Content-Type: application/x-www-form-urlencoded291fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 292why, one step back292names[first]=thinkerou&names[second]=tianoudocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 293–300why, one step back293```294295```go296func main() {297 router := gin.Default()298299 router.POST("/post", func(c *gin.Context) {300fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 301–302why, one step back301 ids := c.QueryMap("ids")302 names := c.PostFormMap("names")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 303why, one step back303fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 304why, one step back304 fmt.Printf("ids: %v; names: %v", ids, names)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 305–310why, one step back305 })306 router.Run(":8080")307}308```309310```shfix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 311why, one step back311ids: 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 312–313why, one step back312```313fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 314why, one step back314### Upload filesdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 315why, one step back315fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 316why, one step back316#### Single filedocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 317why, one step back317fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 318why, one step back318References 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 319why, one step back319fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 320why, one step back320`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 321why, one step back321fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 322why, one step back322> 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 323–329why, one step back323324```go325func main() {326 router := gin.Default()327 // Set a lower memory limit for multipart forms (default is 32 MiB)328 router.MaxMultipartMemory = 8 << 20 // 8 MiB329 router.POST("/upload", func(c *gin.Context) {fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 330–332why, one step back330 // Single file331 file, _ := c.FormFile("file")332 log.Println(file.Filename)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 333why, one step back333fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 334–335why, one step back334 // Upload the file to specific dst.335 c.SaveUploadedFile(file, dst)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 336why, one step back336fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 337why, one step back337 c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 338–346why, one step back338 })339 router.Run(":8080")340}341```342343How to `curl`:344345```bash346curl -X POST http://localhost:8080/upload \fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 347why, one step back347 -F "file=@/Users/appleboy/test.zip" \docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 348–350why, one step back348 -H "Content-Type: multipart/form-data"349```350fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 351why, one step back351#### Multiple filesdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 352why, one step back352fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 353why, one step back353See 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 354–360why, one step back354355```go356func main() {357 router := gin.Default()358 // Set a lower memory limit for multipart forms (default is 32 MiB)359 router.MaxMultipartMemory = 8 << 20 // 8 MiB360 router.POST("/upload", func(c *gin.Context) {fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 361–363why, one step back361 // Multipart form362 form, _ := c.MultipartForm()363 files := form.File["upload[]"]docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 364why, one step back364fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 365–366why, one step back365 for _, file := range files {366 log.Println(file.Filename)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 367why, one step back367fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 368–369why, one step back368 // Upload the file to specific dst.369 c.SaveUploadedFile(file, dst)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 370why, one step back370 }fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 371why, one step back371 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 372–380why, one step back372 })373 router.Run(":8080")374}375```376377How to `curl`:378379```bash380curl -X POST http://localhost:8080/upload \fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 381–382why, one step back381 -F "upload[]=@/Users/appleboy/test1.zip" \382 -F "upload[]=@/Users/appleboy/test2.zip" \docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 383–385why, one step back383 -H "Content-Type: multipart/form-data"384```385fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 386why, one step back386### Grouping routesdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 387–391why, one step back387388```go389func main() {390 router := gin.Default()391fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 392why, one step back392 // Simple group: v1docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 393why, one step back393 {fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 394–397why, one step back394 v1 := router.Group("/v1")395 v1.POST("/login", loginEndpoint)396 v1.POST("/submit", submitEndpoint)397 v1.POST("/read", readEndpoint)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 398–399why, one step back398 }399fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 400why, one step back400 // Simple group: v2docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 401why, one step back401 {fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 402–405why, one step back402 v2 := router.Group("/v2")403 v2.POST("/login", loginEndpoint)404 v2.POST("/submit", submitEndpoint)405 v2.POST("/read", readEndpoint)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 406–411why, one step back406 }407408 router.Run(":8080")409}410```411fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 412why, one step back412### Redirectsdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 413why, one step back413fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 414why, one step back414Issuing 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 415–417why, one step back415416```go417r.GET("/test", func(c *gin.Context) {fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 418why, one step back418 c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 419–421why, one step back419})420```421fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 422why, one step back422Issuing 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 423–424why, one step back423424```gofix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 425–426why, one step back425r.POST("/test", func(c *gin.Context) {426 c.Redirect(http.StatusFound, "/foo")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 427–429why, one step back427})428```429fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 430why, one step back430Issuing a Router redirect, use `HandleContext` like below.docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 431–433why, one step back431432```go433r.GET("/test", func(c *gin.Context) {fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 434–435why, one step back434 c.Request.URL.Path = "/test2"435 r.HandleContext(c)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 436why, one step back436})fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 437–438why, one step back437r.GET("/test2", func(c *gin.Context) {438 c.JSON(http.StatusOK, gin.H{"hello": "world"})docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 439–501why, one step back439})440```441442## Middleware443444> Configure middleware for request processing, authentication, and error recovery.445446### Blank Gin without middleware by default447448Use449450```go451r := gin.New()452```453454instead of455456```go457// Default With the Logger and Recovery middleware already attached458r := gin.Default()459```460461### Using middleware462463```go464func main() {465 // Creates a router without any middleware by default466 r := gin.New()467468 // Global middleware469 // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.470 // By default gin.DefaultWriter = os.Stdout471 r.Use(gin.Logger())472473 // Recovery middleware recovers from any panics and writes a 500 if there was one.474 r.Use(gin.Recovery())475476 // Per route middleware, you can add as many as you desire.477 r.GET("/benchmark", MyBenchLogger(), benchEndpoint)478479 // Authorization group480 // authorized := r.Group("/", AuthRequired())481 // exactly the same as:482 authorized := r.Group("/")483 // per group middleware! in this case we use the custom created484 // AuthRequired() middleware just in the "authorized" group.485 authorized.Use(AuthRequired())486 {487 authorized.POST("/login", loginEndpoint)488 authorized.POST("/submit", submitEndpoint)489 authorized.POST("/read", readEndpoint)490491 // nested group492 testing := authorized.Group("testing")493 // visit 0.0.0.0:8080/testing/analytics494 testing.GET("/analytics", analyticsEndpoint)495 }496497 // Listen and serve on 0.0.0.0:8080498 r.Run(":8080")499}500```501fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 502why, one step back502### Custom Middlewaredocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 503–504why, one step back503504```gofix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 505–507why, one step back505func Logger() gin.HandlerFunc {506 return func(c *gin.Context) {507 t := time.Now()docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 508why, one step back508fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 509–510why, one step back509 // Set example variable510 c.Set("example", "12345")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 511why, one step back511fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 512why, one step back512 // before requestdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 513why, one step back513fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 514why, one step back514 c.Next()docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 515why, one step back515fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 516–518why, one step back516 // after request517 latency := time.Since(t)518 log.Print(latency)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 519why, one step back519fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 520–522why, one step back520 // access the status we are sending521 status := c.Writer.Status()522 log.Println(status)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 523–527why, one step back523 }524}525526func main() {527 r := gin.New()fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 528why, one step back528 r.Use(Logger())docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 529why, one step back529fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 530–531why, one step back530 r.GET("/test", func(c *gin.Context) {531 example := c.MustGet("example").(string)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 532why, one step back532fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 533–534why, one step back533 // it would print: "12345"534 log.Println(example)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 535–575why, one step back535 })536537 // Listen and serve on 0.0.0.0:8080538 r.Run(":8080")539}540```541542### Custom Recovery behavior543544```go545func main() {546 // Creates a router without any middleware by default547 r := gin.New()548549 // Global middleware550 // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.551 // By default gin.DefaultWriter = os.Stdout552 r.Use(gin.Logger())553554 // Recovery middleware recovers from any panics and writes a 500 if there was one.555 r.Use(gin.CustomRecovery(func(c *gin.Context, recovered any) {556 if err, ok := recovered.(string); ok {557 c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))558 }559 c.AbortWithStatus(http.StatusInternalServerError)560 }))561562 r.GET("/panic", func(c *gin.Context) {563 // panic with a string -- the custom middleware could save this to a database or report it to the user564 panic("foo")565 })566567 r.GET("/", func(c *gin.Context) {568 c.String(http.StatusOK, "ohai")569 })570571 // Listen and serve on 0.0.0.0:8080572 r.Run(":8080")573}574```575fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 576why, one step back576### Using BasicAuth() middlewaredocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 577–578why, one step back577578```gofix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 579–583why, one step back579// simulate some private data580var secrets = gin.H{581 "foo": gin.H{"email": "foo@bar.com", "phone": "123433"},582 "austin": gin.H{"email": "austin@example.com", "phone": "666"},583 "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 584–588why, one step back584}585586func main() {587 r := gin.Default()588fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 589–595why, one step back589 // Group using gin.BasicAuth() middleware590 // gin.Accounts is a shortcut for map[string]string591 authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{592 "foo": "bar",593 "austin": "1234",594 "lena": "hello2",595 "manu": "4321",docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 596–597why, one step back596 }))597fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 598–606why, one step back598 // /admin/secrets endpoint599 // hit "localhost:8080/admin/secrets600 authorized.GET("/secrets", func(c *gin.Context) {601 // get user, it was set by the BasicAuth middleware602 user := c.MustGet(gin.AuthUserKey).(string)603 if secret, ok := secrets[user]; ok {604 c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})605 } else {606 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 607–614why, one step back607 }608 })609610 // Listen and serve on 0.0.0.0:8080611 r.Run(":8080")612}613```614fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 615why, one step back615### Goroutines inside a middlewaredocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 616why, one step back616fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 617why, one step back617When 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 618–622why, one step back618619```go620func main() {621 r := gin.Default()622fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 623–628why, one step back623 r.GET("/long_async", func(c *gin.Context) {624 // create copy to be used inside the goroutine625 cCp := c.Copy()626 go func() {627 // simulate a long task with time.Sleep(). 5 seconds628 time.Sleep(5 * time.Second)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 629why, one step back629fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 630–632why, one step back630 // note that you are using the copied context "cCp", IMPORTANT631 log.Println("Done! in path " + cCp.Request.URL.Path)632 }()docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 633–634why, one step back633 })634fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 635–636why, one step back635 r.GET("/long_sync", func(c *gin.Context) {636 // simulate a long task with time.Sleep(). 5 secondsdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 637–638why, one step back637 time.Sleep(5 * time.Second)638fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 639–640why, one step back639 // since we are NOT using a goroutine, we do not have to copy the context640 log.Println("Done! in path " + c.Request.URL.Path)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 641–807why, one step back641 })642643 // Listen and serve on 0.0.0.0:8080644 r.Run(":8080")645}646```647648## Logging649650> Control log output, formatting, and filtering.651652### How to write log file653654```go655func main() {656 // Disable Console Color, you don't need console color when writing the logs to file.657 gin.DisableConsoleColor()658659 // Logging to a file.660 f, _ := os.Create("gin.log")661 gin.DefaultWriter = io.MultiWriter(f)662663 // Use the following code if you need to write the logs to file and console at the same time.664 // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)665666 router := gin.Default()667 router.GET("/ping", func(c *gin.Context) {668 c.String(http.StatusOK, "pong")669 })670671 router.Run(":8080")672}673```674675### Custom Log Format676677```go678func main() {679 router := gin.New()680681 // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter682 // By default gin.DefaultWriter = os.Stdout683 router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {684685 // your custom format686 return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",687 param.ClientIP,688 param.TimeStamp.Format(time.RFC1123),689 param.Method,690 param.Path,691 param.Request.Proto,692 param.StatusCode,693 param.Latency,694 param.Request.UserAgent(),695 param.ErrorMessage,696 )697 }))698 router.Use(gin.Recovery())699700 router.GET("/ping", func(c *gin.Context) {701 c.String(http.StatusOK, "pong")702 })703704 router.Run(":8080")705}706```707708Sample Output709710```sh711::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" "712```713714### Skip logging715716```go717func main() {718 router := gin.New()719720 // skip logging for desired paths by setting SkipPaths in LoggerConfig721 loggerConfig := gin.LoggerConfig{SkipPaths: []string{"/metrics"}}722723 // skip logging based on your logic by setting Skip func in LoggerConfig724 loggerConfig.Skip = func(c *gin.Context) bool {725 // as an example skip non server side errors726 return c.Writer.Status() < http.StatusInternalServerError727 }728729 router.Use(gin.LoggerWithConfig(loggerConfig))730 router.Use(gin.Recovery())731732 // skipped733 router.GET("/metrics", func(c *gin.Context) {734 c.Status(http.StatusNotImplemented)735 })736737 // skipped738 router.GET("/ping", func(c *gin.Context) {739 c.String(http.StatusOK, "pong")740 })741742 // not skipped743 router.GET("/data", func(c *gin.Context) {744 c.Status(http.StatusNotImplemented)745 })746747 router.Run(":8080")748}749750```751752### Controlling Log output coloring753754By default, logs output on console should be colorized depending on the detected TTY.755756Never colorize logs:757758```go759func main() {760 // Disable log's color761 gin.DisableConsoleColor()762763 // Creates a gin router with default middleware:764 // logger and recovery (crash-free) middleware765 router := gin.Default()766767 router.GET("/ping", func(c *gin.Context) {768 c.String(http.StatusOK, "pong")769 })770771 router.Run(":8080")772}773```774775Always colorize logs:776777```go778func main() {779 // Force log's color780 gin.ForceConsoleColor()781782 // Creates a gin router with default middleware:783 // logger and recovery (crash-free) middleware784 router := gin.Default()785786 router.GET("/ping", func(c *gin.Context) {787 c.String(http.StatusOK, "pong")788 })789790 router.Run(":8080")791}792```793794### Avoid logging query strings795796```go797func main() {798 router := gin.New()799800 // SkipQueryString indicates that the logger should not log the query string.801 // For example, /path?q=1 will be logged as /path802 loggerConfig := gin.LoggerConfig{SkipQueryString: true}803804 router.Use(gin.LoggerWithConfig(loggerConfig))805}806```807fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 808why, one step back808### Define format for the log of routesdocs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
line 809why, one step back809fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 810why, one step back810The default log of routes is:docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 811–812why, one step back811812```shfix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 813–815why, one step back813[GIN-debug] POST /foo --> main.main.func1 (3 handlers)814[GIN-debug] GET /bar --> main.main.func2 (3 handlers)815[GIN-debug] GET /status --> main.main.func3 (3 handlers)docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 816–817why, one step back816```817fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 818–819why, one step back818If 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`.819In 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 820–830why, one step back820821```go822import (823 "log"824 "net/http"825826 "github.com/gin-gonic/gin"827)828829func main() {830 r := gin.Default()fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 831–832why, one step back831 gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {832 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 833–834why, one step back833 }834fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 835–836why, one step back835 r.POST("/foo", func(c *gin.Context) {836 c.JSON(http.StatusOK, "foo")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 837–838why, one step back837 })838fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 839–840why, one step back839 r.GET("/bar", func(c *gin.Context) {840 c.JSON(http.StatusOK, "bar")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 841–842why, one step back841 })842fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
lines 843–844why, one step back843 r.GET("/status", func(c *gin.Context) {844 c.JSON(http.StatusOK, "ok")docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 845–846why, one step back845 })846fix: sonic on arm64 (#4234)Yashbefore adoption7a1b655
line 847why, one step back847 // Listen and Server in http://0.0.0.0:8080docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 848–1168why, one step back848 r.Run()849}850```851852## Request Binding & Validation853854> Bind and validate request data from query strings, forms, JSON, and more.855856### Model binding and validation857858To 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).859860Gin 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).861862Note 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"`.863864Also, Gin provides two sets of methods for binding:865866- **Type** - Must bind867 - **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`, `BindHeader`, `BindTOML`868 - **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.869- **Type** - Should bind870 - **Methods** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindXML`, `ShouldBindQuery`, `ShouldBindYAML`, `ShouldBindHeader`, `ShouldBindTOML`,871 - **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.872873When 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`.874875You 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.876877```go878// Binding from JSON879type Login struct {880 User string `form:"user" json:"user" xml:"user" binding:"required"`881 Password string `form:"password" json:"password" xml:"password" binding:"required"`882}883884func main() {885 router := gin.Default()886887 // Example for binding JSON ({"user": "manu", "password": "123"})888 router.POST("/loginJSON", func(c *gin.Context) {889 var json Login890 if err := c.ShouldBindJSON(&json); err != nil {891 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})892 return893 }894895 if json.User != "manu" || json.Password != "123" {896 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})897 return898 }899900 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})901 })902903 // Example for binding XML (904 // <?xml version="1.0" encoding="UTF-8"?>905 // <root>906 // <user>manu</user>907 // <password>123</password>908 // </root>)909 router.POST("/loginXML", func(c *gin.Context) {910 var xml Login911 if err := c.ShouldBindXML(&xml); err != nil {912 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})913 return914 }915916 if xml.User != "manu" || xml.Password != "123" {917 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})918 return919 }920921 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})922 })923924 // Example for binding a HTML form (user=manu&password=123)925 router.POST("/loginForm", func(c *gin.Context) {926 var form Login927 // This will infer what binder to use depending on the content-type header.928 if err := c.ShouldBind(&form); err != nil {929 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})930 return931 }932933 if form.User != "manu" || form.Password != "123" {934 c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})935 return936 }937938 c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})939 })940941 // Listen and serve on 0.0.0.0:8080942 router.Run(":8080")943}944```945946Sample request947948```sh949$ curl -v -X POST \950 http://localhost:8080/loginJSON \951 -H 'content-type: application/json' \952 -d '{ "user": "manu" }'953> POST /loginJSON HTTP/1.1954> Host: localhost:8080955> User-Agent: curl/7.51.0956> Accept: */*957> content-type: application/json958> Content-Length: 18959>960* upload completely sent off: 18 out of 18 bytes961< HTTP/1.1 400 Bad Request962< Content-Type: application/json; charset=utf-8963< Date: Fri, 04 Aug 2017 03:51:31 GMT964< Content-Length: 100965<966{"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}967```968969Skip-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.970971### Custom Validators972973It is also possible to register custom validators. See the [example code](https://github.com/gin-gonic/examples/tree/master/custom-validation/server.go).974975```go976package main977978import (979 "net/http"980 "time"981982 "github.com/gin-gonic/gin"983 "github.com/gin-gonic/gin/binding"984 "github.com/go-playground/validator/v10"985)986987// Booking contains binded and validated data.988type Booking struct {989 CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`990 CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`991}992993var bookableDate validator.Func = func(fl validator.FieldLevel) bool {994 date, ok := fl.Field().Interface().(time.Time)995 if ok {996 today := time.Now()997 if today.After(date) {998 return false999 }1000 }1001 return true1002}10031004func main() {1005 route := gin.Default()10061007 if v, ok := binding.Validator.Engine().(*validator.Validate); ok {1008 v.RegisterValidation("bookabledate", bookableDate)1009 }10101011 route.GET("/bookable", getBookable)1012 route.Run(":8085")1013}10141015func getBookable(c *gin.Context) {1016 var b Booking1017 if err := c.ShouldBindWith(&b, binding.Query); err == nil {1018 c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})1019 } else {1020 c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})1021 }1022}1023```10241025```console1026$ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17"1027{"message":"Booking dates are valid!"}10281029$ curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09"1030{"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"}10311032$ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10"1033{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}%1034```10351036[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way.1037See the [struct-lvl-validation example](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) to learn more.10381039### Only Bind Query String10401041`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).10421043```go1044package main10451046import (1047 "log"1048 "net/http"10491050 "github.com/gin-gonic/gin"1051)10521053type Person struct {1054 Name string `form:"name"`1055 Address string `form:"address"`1056}10571058func main() {1059 route := gin.Default()1060 route.Any("/testing", startPage)1061 route.Run(":8085")1062}10631064func startPage(c *gin.Context) {1065 var person Person1066 if c.ShouldBindQuery(&person) == nil {1067 log.Println("====== Only Bind By Query String ======")1068 log.Println(person.Name)1069 log.Println(person.Address)1070 }1071 c.String(http.StatusOK, "Success")1072}10731074```10751076### Bind Query String or Post Data10771078See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292).10791080```go1081package main10821083import (1084 "log"1085 "net/http"1086 "time"10871088 "github.com/gin-gonic/gin"1089)10901091type Person struct {1092 Name string `form:"name"`1093 Address string `form:"address"`1094 Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`1095 CreateTime time.Time `form:"createTime" time_format:"unixNano"`1096 UnixTime time.Time `form:"unixTime" time_format:"unix"`1097 UnixMilliTime time.Time `form:"unixMilliTime" time_format:"unixmilli"`1098 UnixMicroTime time.Time `form:"unixMicroTime" time_format:"uNiXmIcRo"` // case does not matter for "unix*" time formats1099}11001101func main() {1102 route := gin.Default()1103 route.GET("/testing", startPage)1104 route.Run(":8085")1105}11061107func startPage(c *gin.Context) {1108 var person Person1109 // If `GET`, only `Form` binding engine (`query`) used.1110 // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).1111 // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L881112 if c.ShouldBind(&person) == nil {1113 log.Println(person.Name)1114 log.Println(person.Address)1115 log.Println(person.Birthday)1116 log.Println(person.CreateTime)1117 log.Println(person.UnixTime)1118 log.Println(person.UnixMilliTime)1119 log.Println(person.UnixMicroTime)1120 }11211122 c.String(http.StatusOK, "Success")1123}1124```11251126Test it with:11271128```sh1129curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033&unixMilliTime=1562400033001&unixMicroTime=1562400033000012"1130```11311132### Bind default value if none provided11331134If 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:11351136```go1137package main11381139import (1140 "net/http"11411142 "github.com/gin-gonic/gin"1143)11441145type Person struct {1146 Name string `form:"name,default=William"`1147 Age int `form:"age,default=10"`1148 Friends []string `form:"friends,default=Will;Bill"`1149 Addresses [2]string `form:"addresses,default=foo bar" collection_format:"ssv"`1150 LapTimes []int `form:"lap_times,default=1;2;3" collection_format:"csv"`1151}11521153func main() {1154 g := gin.Default()1155 g.POST("/person", func(c *gin.Context) {1156 var req Person1157 if err := c.ShouldBindQuery(&req); err != nil {1158 c.JSON(http.StatusBadRequest, err)1159 return1160 }1161 c.JSON(http.StatusOK, req)1162 })1163 _ = g.Run("localhost:8080")1164}1165```11661167```sh1168curl -X POST http://localhost:8080/persondocs: fix SecureJSON default prefix and default-binding example output (#4861)Zain Qureshibefore adoption43fe48e
line 1169why, one step back1169{"Name":"William","Age":10,"Friends":["Will","Bill"],"Addresses":["foo","bar"],"LapTimes":[1,2,3]}docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 1170–1763why, one step back1170```11711172NOTE: For default [collection values](#collection-format-for-arrays), the following rules apply:11731174- Since commas are used to delimit tag options, they are not supported within a default value and will result in undefined behavior1175- For the collection formats "multi" and "csv", a semicolon should be used in place of a comma to delimit default values1176- Since semicolons are used to delimit default values for "multi" and "csv", they are not supported within a default value for "multi" and "csv"11771178#### Collection format for arrays11791180| Format | Description | Example |1181| --------------- | --------------------------------------------------------- | ----------------------- |1182| multi (default) | Multiple parameter instances rather than multiple values. | key=foo&key=bar&key=baz |1183| csv | Comma-separated values. | foo,bar,baz |1184| ssv | Space-separated values. | foo bar baz |1185| tsv | Tab-separated values. | "foo\tbar\tbaz" |1186| pipes | Pipe-separated values. | foo\|bar\|baz |11871188```go1189package main11901191import (1192 "log"1193 "time"1194 "github.com/gin-gonic/gin"1195)11961197type Person struct {1198 Name string `form:"name"`1199 Addresses []string `form:"addresses" collection_format:"csv"`1200 Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`1201 CreateTime time.Time `form:"createTime" time_format:"unixNano"`1202 UnixTime time.Time `form:"unixTime" time_format:"unix"`1203}12041205func main() {1206 route := gin.Default()1207 route.GET("/testing", startPage)1208 route.Run(":8085")1209}1210func startPage(c *gin.Context) {1211 var person Person1212 // If `GET`, only `Form` binding engine (`query`) used.1213 // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).1214 // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L481215 if c.ShouldBind(&person) == nil {1216 log.Println(person.Name)1217 log.Println(person.Addresses)1218 log.Println(person.Birthday)1219 log.Println(person.CreateTime)1220 log.Println(person.UnixTime)1221 }1222 c.String(200, "Success")1223}1224```12251226Test it with:12271228```sh1229curl -X GET "localhost:8085/testing?name=appleboy&addresses=foo,bar&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"1230```12311232### Bind Uri12331234See the [detail information](https://github.com/gin-gonic/gin/issues/846).12351236```go1237package main12381239import (1240 "net/http"12411242 "github.com/gin-gonic/gin"1243)12441245type Person struct {1246 ID string `uri:"id" binding:"required,uuid"`1247 Name string `uri:"name" binding:"required"`1248}12491250func main() {1251 route := gin.Default()1252 route.GET("/:name/:id", func(c *gin.Context) {1253 var person Person1254 if err := c.ShouldBindUri(&person); err != nil {1255 c.JSON(http.StatusBadRequest, gin.H{"msg": err.Error()})1256 return1257 }1258 c.JSON(http.StatusOK, gin.H{"name": person.Name, "uuid": person.ID})1259 })1260 route.Run(":8088")1261}1262```12631264Test it with:12651266```sh1267curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f31268curl -v localhost:8088/thinkerou/not-uuid1269```12701271### Bind custom unmarshaler12721273To 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.12741275```go1276package main12771278import (1279 "encoding"1280 "strings"12811282 "github.com/gin-gonic/gin"1283)12841285type Birthday string12861287func (b *Birthday) UnmarshalText(text []byte) error {1288 *b = Birthday(strings.Replace(string(text), "-", "/", -1))1289 return nil1290}12911292var _ encoding.TextUnmarshaler = (*Birthday)(nil) //assert Birthday implements encoding.TextUnmarshaler12931294func main() {1295 route := gin.Default()1296 var request struct {1297 Birthday Birthday `form:"birthday,parser=encoding.TextUnmarshaler"`1298 Birthdays []Birthday `form:"birthdays,parser=encoding.TextUnmarshaler" collection_format:"csv"`1299 BirthdaysDefault []Birthday `form:"birthdaysDef,default=2020-09-01;2020-09-02,parser=encoding.TextUnmarshaler" collection_format:"csv"`1300 }1301 route.GET("/test", func(ctx *gin.Context) {1302 _ = ctx.BindQuery(&request)1303 ctx.JSON(200, request)1304 })1305 _ = route.Run(":8088")1306}1307```13081309Test it with:13101311```sh1312curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02'1313```13141315Result13161317```sh1318{"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]}1319```13201321Note:13221323- 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.1324- 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.13251326---13271328If 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.13291330```go1331package main13321333import (1334 "strings"13351336 "github.com/gin-gonic/gin"1337 "github.com/gin-gonic/gin/binding"1338)13391340type Birthday string13411342func (b *Birthday) UnmarshalParam(param string) error {1343 *b = Birthday(strings.Replace(param, "-", "/", -1))1344 return nil1345}13461347var _ binding.BindUnmarshaler = (*Birthday)(nil) //assert Birthday implements binding.BindUnmarshaler13481349func main() {1350 route := gin.Default()1351 var request struct {1352 Birthday Birthday `form:"birthday"`1353 Birthdays []Birthday `form:"birthdays" collection_format:"csv"`1354 BirthdaysDefault []Birthday `form:"birthdaysDef,default=2020-09-01;2020-09-02" collection_format:"csv"`1355 }1356 route.GET("/test", func(ctx *gin.Context) {1357 _ = ctx.BindQuery(&request)1358 ctx.JSON(200, request)1359 })1360 _ = route.Run(":8088")1361}1362```13631364Test it with:13651366```sh1367curl 'localhost:8088/test?birthday=2000-01-01&birthdays=2000-01-01,2000-01-02'1368```13691370Result13711372```sh1373{"Birthday":"2000/01/01","Birthdays":["2000/01/01","2000/01/02"],"BirthdaysDefault":["2020/09/01","2020/09/02"]}1374```13751376Note:13771378- 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.1379- If a type returns an error from its implementation of `BindUnmarshaler`, gin will stop binding and return the error to the client.13801381### Bind Header13821383```go1384package main13851386import (1387 "fmt"1388 "net/http"13891390 "github.com/gin-gonic/gin"1391)13921393type testHeader struct {1394 Rate int `header:"Rate"`1395 Domain string `header:"Domain"`1396}13971398func main() {1399 r := gin.Default()1400 r.GET("/", func(c *gin.Context) {1401 h := testHeader{}14021403 if err := c.ShouldBindHeader(&h); err != nil {1404 c.JSON(http.StatusOK, err)1405 }14061407 fmt.Printf("%#v\n", h)1408 c.JSON(http.StatusOK, gin.H{"Rate": h.Rate, "Domain": h.Domain})1409 })14101411 r.Run()14121413// client1414// curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/1415// output1416// {"Domain":"music","Rate":300}1417}1418```14191420### Bind HTML checkboxes14211422See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)14231424main.go14251426```go1427...14281429type myForm struct {1430 Colors []string `form:"colors[]"`1431}14321433...14341435func formHandler(c *gin.Context) {1436 var fakeForm myForm1437 c.ShouldBind(&fakeForm)1438 c.JSON(http.StatusOK, gin.H{"color": fakeForm.Colors})1439}14401441...14421443```14441445form.html14461447```html1448<form action="/" method="POST">1449 <p>Check some colors</p>1450 <label for="red">Red</label>1451 <input type="checkbox" name="colors[]" value="red" id="red" />1452 <label for="green">Green</label>1453 <input type="checkbox" name="colors[]" value="green" id="green" />1454 <label for="blue">Blue</label>1455 <input type="checkbox" name="colors[]" value="blue" id="blue" />1456 <input type="submit" />1457</form>1458```14591460result:14611462```json1463{ "color": ["red", "green", "blue"] }1464```14651466### Multipart/Urlencoded binding14671468```go1469type ProfileForm struct {1470 Name string `form:"name" binding:"required"`1471 Avatar *multipart.FileHeader `form:"avatar" binding:"required"`14721473 // or for multiple files1474 // Avatars []*multipart.FileHeader `form:"avatar" binding:"required"`1475}14761477func main() {1478 router := gin.Default()1479 router.POST("/profile", func(c *gin.Context) {1480 // you can bind multipart form with explicit binding declaration:1481 // c.ShouldBindWith(&form, binding.Form)1482 // or you can simply use autobinding with ShouldBind method:1483 var form ProfileForm1484 // in this case proper binding will be automatically selected1485 if err := c.ShouldBind(&form); err != nil {1486 c.String(http.StatusBadRequest, "bad request")1487 return1488 }14891490 err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename)1491 if err != nil {1492 c.String(http.StatusInternalServerError, "unknown error")1493 return1494 }14951496 // db.Save(&form)14971498 c.String(http.StatusOK, "ok")1499 })1500 router.Run(":8080")1501}1502```15031504Test it with:15051506```sh1507curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile1508```15091510### Bind form-data request with custom struct15111512The follow example using custom struct:15131514```go1515type StructA struct {1516 FieldA string `form:"field_a"`1517}15181519type StructB struct {1520 NestedStruct StructA1521 FieldB string `form:"field_b"`1522}15231524type StructC struct {1525 NestedStructPointer *StructA1526 FieldC string `form:"field_c"`1527}15281529type StructD struct {1530 NestedAnonyStruct struct {1531 FieldX string `form:"field_x"`1532 }1533 FieldD string `form:"field_d"`1534}15351536func GetDataB(c *gin.Context) {1537 var b StructB1538 c.Bind(&b)1539 c.JSON(http.StatusOK, gin.H{1540 "a": b.NestedStruct,1541 "b": b.FieldB,1542 })1543}15441545func GetDataC(c *gin.Context) {1546 var b StructC1547 c.Bind(&b)1548 c.JSON(http.StatusOK, gin.H{1549 "a": b.NestedStructPointer,1550 "c": b.FieldC,1551 })1552}15531554func GetDataD(c *gin.Context) {1555 var b StructD1556 c.Bind(&b)1557 c.JSON(http.StatusOK, gin.H{1558 "x": b.NestedAnonyStruct,1559 "d": b.FieldD,1560 })1561}15621563func main() {1564 r := gin.Default()1565 r.GET("/getb", GetDataB)1566 r.GET("/getc", GetDataC)1567 r.GET("/getd", GetDataD)15681569 r.Run()1570}1571```15721573Using the command `curl` command result:15741575```sh1576$ curl "http://localhost:8080/getb?field_a=hello&field_b=world"1577{"a":{"FieldA":"hello"},"b":"world"}1578$ curl "http://localhost:8080/getc?field_a=hello&field_c=world"1579{"a":{"FieldA":"hello"},"c":"world"}1580$ curl "http://localhost:8080/getd?field_x=hello&field_d=world"1581{"d":"world","x":{"FieldX":"hello"}}1582```15831584### Try to bind body into different structs15851586The normal methods for binding request body consumes `c.Request.Body` and they1587cannot be called multiple times.15881589```go1590type formA struct {1591 Foo string `json:"foo" xml:"foo" binding:"required"`1592}15931594type formB struct {1595 Bar string `json:"bar" xml:"bar" binding:"required"`1596}15971598func SomeHandler(c *gin.Context) {1599 objA := formA{}1600 objB := formB{}1601 // Calling c.ShouldBind consumes c.Request.Body and it cannot be reused.1602 if errA := c.ShouldBind(&objA); errA == nil {1603 c.String(http.StatusOK, `the body should be formA`)1604 // Always an error is occurred by this because c.Request.Body is EOF now.1605 } else if errB := c.ShouldBind(&objB); errB == nil {1606 c.String(http.StatusOK, `the body should be formB`)1607 } else {1608 ...1609 }1610}1611```16121613For this, you can use `c.ShouldBindBodyWith` or shortcuts.16141615- `c.ShouldBindBodyWithJSON` is a shortcut for c.ShouldBindBodyWith(obj, binding.JSON).1616- `c.ShouldBindBodyWithXML` is a shortcut for c.ShouldBindBodyWith(obj, binding.XML).1617- `c.ShouldBindBodyWithYAML` is a shortcut for c.ShouldBindBodyWith(obj, binding.YAML).1618- `c.ShouldBindBodyWithTOML` is a shortcut for c.ShouldBindBodyWith(obj, binding.TOML).16191620```go1621func SomeHandler(c *gin.Context) {1622 objA := formA{}1623 objB := formB{}1624 // This reads c.Request.Body and stores the result into the context.1625 if errA := c.ShouldBindBodyWith(&objA, binding.Form); errA == nil {1626 c.String(http.StatusOK, `the body should be formA`)1627 // At this time, it reuses body stored in the context.1628 } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {1629 c.String(http.StatusOK, `the body should be formB JSON`)1630 // And it can accepts other formats1631 } else if errB2 := c.ShouldBindBodyWithXML(&objB); errB2 == nil {1632 c.String(http.StatusOK, `the body should be formB XML`)1633 } else {1634 ...1635 }1636}1637```163816391. `c.ShouldBindBodyWith` stores body into the context before binding. This has1640 a slight impact to performance, so you should not use this method if you are1641 enough to call binding at once.16422. This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`,1643 `ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`,1644 can be called by `c.ShouldBind()` multiple times without any damage to1645 performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)).16461647### Bind form-data request with custom struct and custom tag16481649```go1650const (1651 customerTag = "url"1652 defaultMemory = 32 << 201653)16541655type customerBinding struct {}16561657func (customerBinding) Name() string {1658 return "form"1659}16601661func (customerBinding) Bind(req *http.Request, obj any) error {1662 if err := req.ParseForm(); err != nil {1663 return err1664 }1665 if err := req.ParseMultipartForm(defaultMemory); err != nil {1666 if err != http.ErrNotMultipart {1667 return err1668 }1669 }1670 if err := binding.MapFormWithTag(obj, req.Form, customerTag); err != nil {1671 return err1672 }1673 return validate(obj)1674}16751676func validate(obj any) error {1677 if binding.Validator == nil {1678 return nil1679 }1680 return binding.Validator.ValidateStruct(obj)1681}16821683// Now we can do this!!!1684// FormA is an external type that we can't modify it's tag1685type FormA struct {1686 FieldA string `url:"field_a"`1687}16881689func ListHandler(s *Service) func(ctx *gin.Context) {1690 return func(ctx *gin.Context) {1691 var urlBinding = customerBinding{}1692 var opt FormA1693 err := ctx.MustBindWith(&opt, urlBinding)1694 if err != nil {1695 ...1696 }1697 ...1698 }1699}1700```17011702## Response Rendering17031704> Render responses in various formats including JSON, XML, HTML, and more.17051706### XML, JSON, YAML, TOML and ProtoBuf rendering17071708```go1709func main() {1710 r := gin.Default()17111712 // gin.H is a shortcut for map[string]any1713 r.GET("/someJSON", func(c *gin.Context) {1714 c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1715 })17161717 r.GET("/moreJSON", func(c *gin.Context) {1718 // You can also use a struct1719 var msg struct {1720 Name string `json:"user"`1721 Message string1722 Number int1723 }1724 msg.Name = "Lena"1725 msg.Message = "hey"1726 msg.Number = 1231727 // Note that msg.Name becomes "user" in the JSON1728 // Will output : {"user": "Lena", "Message": "hey", "Number": 123}1729 c.JSON(http.StatusOK, msg)1730 })17311732 r.GET("/someXML", func(c *gin.Context) {1733 c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1734 })17351736 r.GET("/someYAML", func(c *gin.Context) {1737 c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1738 })17391740 r.GET("/someTOML", func(c *gin.Context) {1741 c.TOML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1742 })17431744 r.GET("/someProtoBuf", func(c *gin.Context) {1745 reps := []int64{int64(1), int64(2)}1746 label := "test"1747 // The specific definition of protobuf is written in the testdata/protoexample file.1748 data := &protoexample.Test{1749 Label: &label,1750 Reps: reps,1751 }1752 // Note that data becomes binary data in the response1753 // Will output protoexample.Test protobuf serialized data1754 c.ProtoBuf(http.StatusOK, data)1755 })17561757 // Listen and serve on 0.0.0.0:80801758 r.Run(":8080")1759}1760```17611762#### SecureJSON1763docs: fix SecureJSON default prefix and default-binding example output (#4861)Zain Qureshibefore adoption43fe48e
line 1764why, one step back1764Using SecureJSON to prevent json hijacking. Default prepends `"while(1);"` to response body if the given struct is array values.docs: reorganize doc.md TOC into thematic groups (#4579)Bo-Yi Wubefore adoptiond467221
lines 1765–2161why, one step back17651766```go1767func main() {1768 r := gin.Default()17691770 // You can also use your own secure json prefix1771 // r.SecureJsonPrefix(")]}',\n")17721773 r.GET("/someJSON", func(c *gin.Context) {1774 names := []string{"lena", "austin", "foo"}17751776 // Will output : while(1);["lena","austin","foo"]1777 c.SecureJSON(http.StatusOK, names)1778 })17791780 // Listen and serve on 0.0.0.0:80801781 r.Run(":8080")1782}1783```17841785#### JSONP17861787Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists.17881789```go1790func main() {1791 r := gin.Default()17921793 r.GET("/JSONP", func(c *gin.Context) {1794 data := gin.H{1795 "foo": "bar",1796 }17971798 //callback is x1799 // Will output : x({\"foo\":\"bar\"})1800 c.JSONP(http.StatusOK, data)1801 })18021803 // Listen and serve on 0.0.0.0:80801804 r.Run(":8080")18051806 // client1807 // curl http://127.0.0.1:8080/JSONP?callback=x1808}1809```18101811#### AsciiJSON18121813Using AsciiJSON to Generates ASCII-only JSON with escaped non-ASCII characters.18141815```go1816func main() {1817 r := gin.Default()18181819 r.GET("/someJSON", func(c *gin.Context) {1820 data := gin.H{1821 "lang": "GO语言",1822 "tag": "<br>",1823 }18241825 // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}1826 c.AsciiJSON(http.StatusOK, data)1827 })18281829 // Listen and serve on 0.0.0.0:80801830 r.Run(":8080")1831}1832```18331834#### PureJSON18351836Normally, 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.1837This feature is unavailable in Go 1.6 and lower.18381839```go1840func main() {1841 r := gin.Default()18421843 // Serves unicode entities1844 r.GET("/json", func(c *gin.Context) {1845 c.JSON(http.StatusOK, gin.H{1846 "html": "<b>Hello, world!</b>",1847 })1848 })18491850 // Serves literal characters1851 r.GET("/purejson", func(c *gin.Context) {1852 c.PureJSON(http.StatusOK, gin.H{1853 "html": "<b>Hello, world!</b>",1854 })1855 })18561857 // listen and serve on 0.0.0.0:80801858 r.Run(":8080")1859}1860```18611862### Serving static files18631864```go1865func main() {1866 router := gin.Default()1867 router.Static("/assets", "./assets")1868 router.StaticFS("/more_static", http.Dir("my_file_system"))1869 router.StaticFile("/favicon.ico", "./resources/favicon.ico")1870 router.StaticFileFS("/more_favicon.ico", "more_favicon.ico", http.Dir("my_file_system"))18711872 // Listen and serve on 0.0.0.0:80801873 router.Run(":8080")1874}1875```18761877### Serving data from file18781879```go1880func main() {1881 router := gin.Default()18821883 router.GET("/local/file", func(c *gin.Context) {1884 c.File("local/file.go")1885 })18861887 var fs http.FileSystem = // ...1888 router.GET("/fs/file", func(c *gin.Context) {1889 c.FileFromFS("fs/file.go", fs)1890 })1891}18921893```18941895### Serving data from reader18961897```go1898func main() {1899 router := gin.Default()1900 router.GET("/someDataFromReader", func(c *gin.Context) {1901 response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")1902 if err != nil || response.StatusCode != http.StatusOK {1903 c.Status(http.StatusServiceUnavailable)1904 return1905 }19061907 reader := response.Body1908 defer reader.Close()1909 contentLength := response.ContentLength1910 contentType := response.Header.Get("Content-Type")19111912 extraHeaders := map[string]string{1913 "Content-Disposition": `attachment; filename="gopher.png"`,1914 }19151916 c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)1917 })1918 router.Run(":8080")1919}1920```19211922### HTML rendering19231924Using LoadHTMLGlob() or LoadHTMLFiles() or LoadHTMLFS()19251926```go1927//go:embed templates/*1928var templates embed.FS19291930func main() {1931 router := gin.Default()1932 router.LoadHTMLGlob("templates/*")1933 //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")1934 //router.LoadHTMLFS(http.Dir("templates"), "template1.html", "template2.html")1935 //or1936 //router.LoadHTMLFS(http.FS(templates), "templates/template1.html", "templates/template2.html")1937 router.GET("/index", func(c *gin.Context) {1938 c.HTML(http.StatusOK, "index.tmpl", gin.H{1939 "title": "Main website",1940 })1941 })1942 router.Run(":8080")1943}1944```19451946templates/index.tmpl19471948```html1949<html>1950 <h1>{{ .title }}</h1>1951</html>1952```19531954Using templates with same name in different directories19551956```go1957func main() {1958 router := gin.Default()1959 router.LoadHTMLGlob("templates/**/*")1960 router.GET("/posts/index", func(c *gin.Context) {1961 c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{1962 "title": "Posts",1963 })1964 })1965 router.GET("/users/index", func(c *gin.Context) {1966 c.HTML(http.StatusOK, "users/index.tmpl", gin.H{1967 "title": "Users",1968 })1969 })1970 router.Run(":8080")1971}1972```19731974templates/posts/index.tmpl19751976```html1977{{ define "posts/index.tmpl" }}1978<html>1979 <h1>{{ .title }}</h1>1980 <p>Using posts/index.tmpl</p>1981</html>1982{{ end }}1983```19841985templates/users/index.tmpl19861987```html1988{{ define "users/index.tmpl" }}1989<html>1990 <h1>{{ .title }}</h1>1991 <p>Using users/index.tmpl</p>1992</html>1993{{ end }}1994```19951996#### Custom Template renderer19971998You can also use your own html template render19992000```goThe first 2,000 of 2,707 lines.