chore: update readme (#1793)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* update readme * add multi-language version doc link * add multi-language version doc link * update readme * update * update readme * update readme * update readme
authored by 田欧 · committed by GitHub · parent e526148 · Browse files · 1 file·+35 added−1972 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+35 added−1972 removed
- other:+35 added−1972 removed
Provenance
- Commit
cab0749- Tree
3301912- Author
田欧 <thinkerou@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
e526148
1 file changed+35 added−1972 removed
modified:README.md+35 added-1972 removed
11 unmodified lines12 [](https://github.com/gin-gonic/gin/releases)13 14 Gin is a web framework written in Go (Golang). It features a martini-like API with much better performance, up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin.15 16-16+**The key features of Gin are:**17 18-## Contents18+- Zero allocation router19+- Fast20+- Middleware support21+- Crash-free22+- JSON validation23+- Routes grouping24+- Error management25+- Rendering built-in26+- Extendable27 20-- [Installation](#installation)21-- [Prerequisite](#prerequisite)22-- [Quick start](#quick-start)23-- [Benchmarks](#benchmarks)24-- [Gin v1.stable](#gin-v1-stable)25-- [Build with jsoniter](#build-with-jsoniter)26-- [API Examples](#api-examples)27- - [Using GET,POST,PUT,PATCH,DELETE and OPTIONS](#using-get-post-put-patch-delete-and-options)28- - [Parameters in path](#parameters-in-path)29- - [Querystring parameters](#querystring-parameters)30- - [Multipart/Urlencoded Form](#multiparturlencoded-form)31- - [Another example: query + post form](#another-example-query--post-form)32- - [Map as querystring or postform parameters](#map-as-querystring-or-postform-parameters)33- - [Upload files](#upload-files)34- - [Grouping routes](#grouping-routes)35- - [Blank Gin without middleware by default](#blank-gin-without-middleware-by-default)36- - [Using middleware](#using-middleware)37- - [How to write log file](#how-to-write-log-file)38- - [Custom Log Format](#custom-log-format)39- - [Model binding and validation](#model-binding-and-validation)40- - [Custom Validators](#custom-validators)41- - [Only Bind Query String](#only-bind-query-string)42- - [Bind Query String or Post Data](#bind-query-string-or-post-data)43- - [Bind Uri](#bind-uri)44- - [Bind HTML checkboxes](#bind-html-checkboxes)45- - [Multipart/Urlencoded binding](#multiparturlencoded-binding)46- - [XML, JSON, YAML and ProtoBuf rendering](#xml-json-yaml-and-protobuf-rendering)47- - [JSONP rendering](#jsonp)48- - [Serving static files](#serving-static-files)49- - [Serving data from reader](#serving-data-from-reader)50- - [HTML rendering](#html-rendering)51- - [Multitemplate](#multitemplate)52- - [Redirects](#redirects)53- - [Custom Middleware](#custom-middleware)54- - [Using BasicAuth() middleware](#using-basicauth-middleware)55- - [Goroutines inside a middleware](#goroutines-inside-a-middleware)56- - [Custom HTTP configuration](#custom-http-configuration)57- - [Support Let's Encrypt](#support-lets-encrypt)58- - [Run multiple service using Gin](#run-multiple-service-using-gin)59- - [Graceful restart or stop](#graceful-restart-or-stop)60- - [Build a single binary with templates](#build-a-single-binary-with-templates)61- - [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct)62- - [Try to bind body into different structs](#try-to-bind-body-into-different-structs)63- - [http2 server push](#http2-server-push)64- - [Define format for the log of routes](#define-format-for-the-log-of-routes)65- - [Set and get a cookie](#set-and-get-a-cookie)66-- [Testing](#testing)67-- [Users](#users)28+For more feature details, please see the [Gin website introduction](https://gin-gonic.com/docs/introduction/).29 69-## Installation30+## Getting started31 71-To install Gin package, you need to install Go and set your Go workspace first.32+### Getting Gin33 73-1. Download and install it:34+The first need [Go](https://golang.org/) installed (version 1.6+ is required), then you can use the below Go command to install Gin.35 36 ```sh37 $ go get -u github.com/gin-gonic/gin38 ```39 79-2. Import it in your code:40+For more installation guides such as vendor tool, please check out [Gin quickstart](https://gin-gonic.com/docs/quickstart/).41 81-```go82-import "github.com/gin-gonic/gin"83-```42+### Running Gin43 85-3. (Optional) Import `net/http`. This is required for example if using constants such as `http.StatusOK`.44+First you need to import Gin package for using Gin, one simplest example likes the follow `example.go`:45 46 ```go88-import "net/http"89-```90-91-### Use a vendor tool like [Govendor](https://github.com/kardianos/govendor)92-93-1. `go get` govendor94-95-```sh96-$ go get github.com/kardianos/govendor97-```98-2. Create your project folder and `cd` inside99-100-```sh101-$ mkdir -p $GOPATH/src/github.com/myusername/project && cd "$_"102-```103-104-3. Vendor init your project and add gin105-106-```sh107-$ govendor init108-$ govendor fetch github.com/gin-gonic/gin@v1.3109-```110-111-4. Copy a starting template inside your project112-113-```sh114-$ curl https://raw.githubusercontent.com/gin-gonic/examples/master/basic/main.go > main.go115-```116-117-5. Run your project118-119-```sh120-$ go run main.go121-```122-123-## Prerequisite124-125-Now Gin requires Go 1.6 or later and Go 1.7 will be required soon.126-127-## Quick start128- 129-```sh130-# assume the following codes in example.go file131-$ cat example.go132-```133-134-```go47 package main48 49 import "github.com/gin-gonic/gin"50 7 unmodified lines58 r.Run() // listen and serve on 0.0.0.0:808059 }60 ```61 62+And use the Go command to run the demo:63+64 ```65 # run example.go and visit 0.0.0.0:8080/ping on browser66 $ go run example.go67 ```68 69 ## Benchmarks70 157-Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httprouter)71+Please see all benchmarks details from [Gin website](https://gin-gonic.com/docs/benchmarks/).72 159-[See all benchmarks](/BENCHMARKS.md)160-73 Benchmark name | (1) | (2) | (3) | (4)74 --------------------------------------------|-----------:|------------:|-----------:|---------:75 **BenchmarkGin_GithubAll** | **30000** | **48375** | **0** | **0**76 BenchmarkAce_GithubAll | 10000 | 134059 | 13792 | 16727 unmodified lines104 - (2): Single Repetition Duration (ns/op), lower is better105 - (3): Heap Memory (B/op), lower is better106 - (4): Average Allocations per Repetition (allocs/op), lower is better107 196-## Gin v1. stable108+## Middlewares109 198-- [x] Zero allocation router.199-- [x] Still the fastest http router and framework. From routing to writing.200-- [x] Complete suite of unit tests201-- [x] Battle tested202-- [x] API frozen, new releases will not break your code.110+You can find many useful Gin middlewares at [gin-contrib](https://github.com/gin-contrib).111 204-## Build with [jsoniter](https://github.com/json-iterator/go)112+## Documentation113 206-Gin uses `encoding/json` as default json package but you can change to [jsoniter](https://github.com/json-iterator/go) by build from other tags.114+All documentation is available on the Gin website.115 208-```sh209-$ go build -tags=jsoniter .210-```116+- [English](https://gin-gonic.com/docs/)117+- [简体中文](https://gin-gonic.com/zh-cn/docs/)118+- [繁體中文](https://gin-gonic.com/zh-tw/docs/)119+- [にほんご](https://gin-gonic.com/ja/docs/)120 212-## API Examples121+## Examples122 214-You can find a number of ready-to-run examples at [Gin examples repository](https://github.com/gin-gonic/examples).123+A number of ready-to-run examples demonstrating various use cases of Gin on the [Gin examples](https://github.com/gin-gonic/examples) repository.124 216-### Using GET, POST, PUT, PATCH, DELETE and OPTIONS125+## Users126 218-```go219-func main() {220- // Creates a gin router with default middleware:221- // logger and recovery (crash-free) middleware222- router := gin.Default()127+[Gin website](https://gin-gonic.com/docs/users/) lists some awesome projects made with Gin web framework.128 224- router.GET("/someGet", getting)225- router.POST("/somePost", posting)226- router.PUT("/somePut", putting)227- router.DELETE("/someDelete", deleting)228- router.PATCH("/somePatch", patching)229- router.HEAD("/someHead", head)230- router.OPTIONS("/someOptions", options)129+## Contributing130 232- // By default it serves on :8080 unless a233- // PORT environment variable was defined.234- router.Run()235- // router.Run(":3000") for a hard coded port236-}237-```131+Gin is the work of hundreds of contributors. We appreciate your help!132 239-### Parameters in path133+Please see [CONTRIBUTING](CONTRIBUTING.md) for details on submitting patches and the contribution workflow.134 241-```go242-func main() {243- router := gin.Default()244-245- // This handler will match /user/john but will not match /user/ or /user246- router.GET("/user/:name", func(c *gin.Context) {247- name := c.Param("name")248- c.String(http.StatusOK, "Hello %s", name)249- })250-251- // However, this one will match /user/john/ and also /user/john/send252- // If no other routers match /user/john, it will redirect to /user/john/253- router.GET("/user/:name/*action", func(c *gin.Context) {254- name := c.Param("name")255- action := c.Param("action")256- message := name + " is " + action257- c.String(http.StatusOK, message)258- })259-260- router.Run(":8080")261-}262-```263-264-### Querystring parameters265-266-```go267-func main() {268- router := gin.Default()269-270- // Query string parameters are parsed using the existing underlying request object.271- // The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe272- router.GET("/welcome", func(c *gin.Context) {273- firstname := c.DefaultQuery("firstname", "Guest")274- lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")275-276- c.String(http.StatusOK, "Hello %s %s", firstname, lastname)277- })278- router.Run(":8080")279-}280-```281-282-### Multipart/Urlencoded Form283-284-```go285-func main() {286- router := gin.Default()287-288- router.POST("/form_post", func(c *gin.Context) {289- message := c.PostForm("message")290- nick := c.DefaultPostForm("nick", "anonymous")291-292- c.JSON(200, gin.H{293- "status": "posted",294- "message": message,295- "nick": nick,296- })297- })298- router.Run(":8080")299-}300-```301-302-### Another example: query + post form303-304-```305-POST /post?id=1234&page=1 HTTP/1.1306-Content-Type: application/x-www-form-urlencoded307-308-name=manu&message=this_is_great309-```310-311-```go312-func main() {313- router := gin.Default()314-315- router.POST("/post", func(c *gin.Context) {316-317- id := c.Query("id")318- page := c.DefaultQuery("page", "0")319- name := c.PostForm("name")320- message := c.PostForm("message")321-322- fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)323- })324- router.Run(":8080")325-}326-```327-328-```329-id: 1234; page: 1; name: manu; message: this_is_great330-```331-332-### Map as querystring or postform parameters333-334-```335-POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1336-Content-Type: application/x-www-form-urlencoded337-338-names[first]=thinkerou&names[second]=tianou339-```340-341-```go342-func main() {343- router := gin.Default()344-345- router.POST("/post", func(c *gin.Context) {346-347- ids := c.QueryMap("ids")348- names := c.PostFormMap("names")349-350- fmt.Printf("ids: %v; names: %v", ids, names)351- })352- router.Run(":8080")353-}354-```355-356-```357-ids: map[b:hello a:1234], names: map[second:tianou first:thinkerou]358-```359-360-### Upload files361-362-#### Single file363-364-References 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).365-366-`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)367-368-> 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.369-370-```go371-func main() {372- router := gin.Default()373- // Set a lower memory limit for multipart forms (default is 32 MiB)374- // router.MaxMultipartMemory = 8 << 20 // 8 MiB375- router.POST("/upload", func(c *gin.Context) {376- // single file377- file, _ := c.FormFile("file")378- log.Println(file.Filename)379-380- // Upload the file to specific dst.381- // c.SaveUploadedFile(file, dst)382-383- c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))384- })385- router.Run(":8080")386-}387-```388-389-How to `curl`:390-391-```bash392-curl -X POST http://localhost:8080/upload \393- -F "file=@/Users/appleboy/test.zip" \394- -H "Content-Type: multipart/form-data"395-```396-397-#### Multiple files398-399-See the detail [example code](https://github.com/gin-gonic/examples/tree/master/upload-file/multiple).400-401-```go402-func main() {403- router := gin.Default()404- // Set a lower memory limit for multipart forms (default is 32 MiB)405- // router.MaxMultipartMemory = 8 << 20 // 8 MiB406- router.POST("/upload", func(c *gin.Context) {407- // Multipart form408- form, _ := c.MultipartForm()409- files := form.File["upload[]"]410-411- for _, file := range files {412- log.Println(file.Filename)413-414- // Upload the file to specific dst.415- // c.SaveUploadedFile(file, dst)416- }417- c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))418- })419- router.Run(":8080")420-}421-```422-423-How to `curl`:424-425-```bash426-curl -X POST http://localhost:8080/upload \427- -F "upload[]=@/Users/appleboy/test1.zip" \428- -F "upload[]=@/Users/appleboy/test2.zip" \429- -H "Content-Type: multipart/form-data"430-```431-432-### Grouping routes433-434-```go435-func main() {436- router := gin.Default()437-438- // Simple group: v1439- v1 := router.Group("/v1")440- {441- v1.POST("/login", loginEndpoint)442- v1.POST("/submit", submitEndpoint)443- v1.POST("/read", readEndpoint)444- }445-446- // Simple group: v2447- v2 := router.Group("/v2")448- {449- v2.POST("/login", loginEndpoint)450- v2.POST("/submit", submitEndpoint)451- v2.POST("/read", readEndpoint)452- }453-454- router.Run(":8080")455-}456-```457-458-### Blank Gin without middleware by default459-460-Use461-462-```go463-r := gin.New()464-```465-466-instead of467-468-```go469-// Default With the Logger and Recovery middleware already attached470-r := gin.Default()471-```472-473-474-### Using middleware475-```go476-func main() {477- // Creates a router without any middleware by default478- r := gin.New()479-480- // Global middleware481- // Logger middleware will write the logs to gin.DefaultWriter even if you set with GIN_MODE=release.482- // By default gin.DefaultWriter = os.Stdout483- r.Use(gin.Logger())484-485- // Recovery middleware recovers from any panics and writes a 500 if there was one.486- r.Use(gin.Recovery())487-488- // Per route middleware, you can add as many as you desire.489- r.GET("/benchmark", MyBenchLogger(), benchEndpoint)490-491- // Authorization group492- // authorized := r.Group("/", AuthRequired())493- // exactly the same as:494- authorized := r.Group("/")495- // per group middleware! in this case we use the custom created496- // AuthRequired() middleware just in the "authorized" group.497- authorized.Use(AuthRequired())498- {499- authorized.POST("/login", loginEndpoint)500- authorized.POST("/submit", submitEndpoint)501- authorized.POST("/read", readEndpoint)502-503- // nested group504- testing := authorized.Group("testing")505- testing.GET("/analytics", analyticsEndpoint)506- }507-508- // Listen and serve on 0.0.0.0:8080509- r.Run(":8080")510-}511-```512-513-### How to write log file514-```go515-func main() {516- // Disable Console Color, you don't need console color when writing the logs to file.517- gin.DisableConsoleColor()518-519- // Logging to a file.520- f, _ := os.Create("gin.log")521- gin.DefaultWriter = io.MultiWriter(f)522-523- // Use the following code if you need to write the logs to file and console at the same time.524- // gin.DefaultWriter = io.MultiWriter(f, os.Stdout)525-526- router := gin.Default()527- router.GET("/ping", func(c *gin.Context) {528- c.String(200, "pong")529- })530-531- router.Run(":8080")532-}533-```534-535-### Custom Log Format536-```go537-func main() {538- router := gin.New()539-540- // LoggerWithFormatter middleware will write the logs to gin.DefaultWriter541- // By default gin.DefaultWriter = os.Stdout542- router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {543-544- // your custom format545- return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",546- param.ClientIP,547- param.TimeStamp.Format(time.RFC1123),548- param.Method,549- param.Path,550- param.Request.Proto,551- param.StatusCode,552- param.Latency,553- param.Request.UserAgent(),554- param.ErrorMessage,555- )556- }))557- router.Use(gin.Recovery())558-559- router.GET("/ping", func(c *gin.Context) {560- c.String(200, "pong")561- })562-563- router.Run(":8080")564-}565-```566-567-**Sample Output**568-```569-::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" "570-```571-572-### Controlling Log output coloring 573-574-By default, logs output on console should be colorized depending on the detected TTY.575-576-Never colorize logs: 577-578-```go579-func main() {580- // Disable log's color581- gin.DisableConsoleColor()582- 583- // Creates a gin router with default middleware:584- // logger and recovery (crash-free) middleware585- router := gin.Default()586- 587- router.GET("/ping", func(c *gin.Context) {588- c.String(200, "pong")589- })590- 591- router.Run(":8080")592-}593-```594-595-Always colorize logs: 596-597-```go598-func main() {599- // Force log's color600- gin.ForceConsoleColor()601- 602- // Creates a gin router with default middleware:603- // logger and recovery (crash-free) middleware604- router := gin.Default()605- 606- router.GET("/ping", func(c *gin.Context) {607- c.String(200, "pong")608- })609- 610- router.Run(":8080")611-}612-```613-614-### Model binding and validation615-616-To bind a request body into a type, use model binding. We currently support binding of JSON, XML, YAML and standard form values (foo=bar&boo=baz).617-618-Gin uses [**go-playground/validator.v8**](https://github.com/go-playground/validator) for validation. Check the full docs on tags usage [here](http://godoc.org/gopkg.in/go-playground/validator.v8#hdr-Baked_In_Validators_and_Tags).619-620-Note 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"`.621-622-Also, Gin provides two sets of methods for binding:623-- **Type** - Must bind624- - **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`625- - **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.626-- **Type** - Should bind627- - **Methods** - `ShouldBind`, `ShouldBindJSON`, `ShouldBindXML`, `ShouldBindQuery`, `ShouldBindYAML`628- - **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.629-630-When 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`.631-632-You can also specify that specific fields are required. If a field is decorated with `binding:"required"` and has a empty value when binding, an error will be returned.633-634-```go635-// Binding from JSON636-type Login struct {637- User string `form:"user" json:"user" xml:"user" binding:"required"`638- Password string `form:"password" json:"password" xml:"password" binding:"required"`639-}640-641-func main() {642- router := gin.Default()643-644- // Example for binding JSON ({"user": "manu", "password": "123"})645- router.POST("/loginJSON", func(c *gin.Context) {646- var json Login647- if err := c.ShouldBindJSON(&json); err != nil {648- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})649- return650- }651- 652- if json.User != "manu" || json.Password != "123" {653- c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})654- return655- } 656- 657- c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})658- })659-660- // Example for binding XML (661- // <?xml version="1.0" encoding="UTF-8"?>662- // <root>663- // <user>user</user>664- // <password>123</password>665- // </root>)666- router.POST("/loginXML", func(c *gin.Context) {667- var xml Login668- if err := c.ShouldBindXML(&xml); err != nil {669- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})670- return671- }672- 673- if xml.User != "manu" || xml.Password != "123" {674- c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})675- return676- } 677- 678- c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})679- })680-681- // Example for binding a HTML form (user=manu&password=123)682- router.POST("/loginForm", func(c *gin.Context) {683- var form Login684- // This will infer what binder to use depending on the content-type header.685- if err := c.ShouldBind(&form); err != nil {686- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})687- return688- }689- 690- if form.User != "manu" || form.Password != "123" {691- c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})692- return693- } 694- 695- c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})696- })697-698- // Listen and serve on 0.0.0.0:8080699- router.Run(":8080")700-}701-```702-703-**Sample request**704-```shell705-$ curl -v -X POST \706- http://localhost:8080/loginJSON \707- -H 'content-type: application/json' \708- -d '{ "user": "manu" }'709-> POST /loginJSON HTTP/1.1710-> Host: localhost:8080711-> User-Agent: curl/7.51.0712-> Accept: */*713-> content-type: application/json714-> Content-Length: 18715->716-* upload completely sent off: 18 out of 18 bytes717-< HTTP/1.1 400 Bad Request718-< Content-Type: application/json; charset=utf-8719-< Date: Fri, 04 Aug 2017 03:51:31 GMT720-< Content-Length: 100721-<722-{"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}723-```724-725-**Skip validate**726-727-When running the above example using the above the `curl` command, it returns error. Because the example use `binding:"required"` for `Password`. If use `binding:"-"` for `Password`, then it will not return error when running the above example again.728-729-### Custom Validators730-731-It is also possible to register custom validators. See the [example code](https://github.com/gin-gonic/examples/tree/master/custom-validation/server.go).732-733-```go734-package main735-736-import (737- "net/http"738- "reflect"739- "time"740-741- "github.com/gin-gonic/gin"742- "github.com/gin-gonic/gin/binding"743- "gopkg.in/go-playground/validator.v8"744-)745-746-// Booking contains binded and validated data.747-type Booking struct {748- CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`749- CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`750-}751-752-func bookableDate(753- v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,754- field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,755-) bool {756- if date, ok := field.Interface().(time.Time); ok {757- today := time.Now()758- if today.Year() > date.Year() || today.YearDay() > date.YearDay() {759- return false760- }761- }762- return true763-}764-765-func main() {766- route := gin.Default()767-768- if v, ok := binding.Validator.Engine().(*validator.Validate); ok {769- v.RegisterValidation("bookabledate", bookableDate)770- }771-772- route.GET("/bookable", getBookable)773- route.Run(":8085")774-}775-776-func getBookable(c *gin.Context) {777- var b Booking778- if err := c.ShouldBindWith(&b, binding.Query); err == nil {779- c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})780- } else {781- c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})782- }783-}784-```785-786-```console787-$ curl "localhost:8085/bookable?check_in=2018-04-16&check_out=2018-04-17"788-{"message":"Booking dates are valid!"}789-790-$ curl "localhost:8085/bookable?check_in=2018-03-08&check_out=2018-03-09"791-{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}792-```793-794-[Struct level validations](https://github.com/go-playground/validator/releases/tag/v8.7) can also be registered this way.795-See the [struct-lvl-validation example](https://github.com/gin-gonic/examples/tree/master/struct-lvl-validations) to learn more.796-797-### Only Bind Query String798-799-`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).800-801-```go802-package main803-804-import (805- "log"806-807- "github.com/gin-gonic/gin"808-)809-810-type Person struct {811- Name string `form:"name"`812- Address string `form:"address"`813-}814-815-func main() {816- route := gin.Default()817- route.Any("/testing", startPage)818- route.Run(":8085")819-}820-821-func startPage(c *gin.Context) {822- var person Person823- if c.ShouldBindQuery(&person) == nil {824- log.Println("====== Only Bind By Query String ======")825- log.Println(person.Name)826- log.Println(person.Address)827- }828- c.String(200, "Success")829-}830-831-```832-833-### Bind Query String or Post Data834-835-See the [detail information](https://github.com/gin-gonic/gin/issues/742#issuecomment-264681292).836-837-```go838-package main839-840-import (841- "log"842- "time"843-844- "github.com/gin-gonic/gin"845-)846-847-type Person struct {848- Name string `form:"name"`849- Address string `form:"address"`850- Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`851-}852-853-func main() {854- route := gin.Default()855- route.GET("/testing", startPage)856- route.Run(":8085")857-}858-859-func startPage(c *gin.Context) {860- var person Person861- // If `GET`, only `Form` binding engine (`query`) used.862- // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`).863- // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48864- if c.ShouldBind(&person) == nil {865- log.Println(person.Name)866- log.Println(person.Address)867- log.Println(person.Birthday)868- }869-870- c.String(200, "Success")871-}872-```873-874-Test it with:875-```sh876-$ curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15"877-```878-879-### Bind Uri880-881-See the [detail information](https://github.com/gin-gonic/gin/issues/846).882-883-```go884-package main885-886-import "github.com/gin-gonic/gin"887-888-type Person struct {889- ID string `uri:"id" binding:"required,uuid"`890- Name string `uri:"name" binding:"required"`891-}892-893-func main() {894- route := gin.Default()895- route.GET("/:name/:id", func(c *gin.Context) {896- var person Person897- if err := c.ShouldBindUri(&person); err != nil {898- c.JSON(400, gin.H{"msg": err})899- return900- }901- c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID})902- })903- route.Run(":8088")904-}905-```906-907-Test it with:908-```sh909-$ curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3910-$ curl -v localhost:8088/thinkerou/not-uuid911-```912-913-### Bind HTML checkboxes914-915-See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)916-917-main.go918-919-```go920-...921-922-type myForm struct {923- Colors []string `form:"colors[]"`924-}925-926-...927-928-func formHandler(c *gin.Context) {929- var fakeForm myForm930- c.ShouldBind(&fakeForm)931- c.JSON(200, gin.H{"color": fakeForm.Colors})932-}933-934-...935-936-```937-938-form.html939-940-```html941-<form action="/" method="POST">942- <p>Check some colors</p>943- <label for="red">Red</label>944- <input type="checkbox" name="colors[]" value="red" id="red">945- <label for="green">Green</label>946- <input type="checkbox" name="colors[]" value="green" id="green">947- <label for="blue">Blue</label>948- <input type="checkbox" name="colors[]" value="blue" id="blue">949- <input type="submit">950-</form>951-```952-953-result:954-955-```956-{"color":["red","green","blue"]}957-```958-959-### Multipart/Urlencoded binding960-961-```go962-package main963-964-import (965- "github.com/gin-gonic/gin"966-)967-968-type LoginForm struct {969- User string `form:"user" binding:"required"`970- Password string `form:"password" binding:"required"`971-}972-973-func main() {974- router := gin.Default()975- router.POST("/login", func(c *gin.Context) {976- // you can bind multipart form with explicit binding declaration:977- // c.ShouldBindWith(&form, binding.Form)978- // or you can simply use autobinding with ShouldBind method:979- var form LoginForm980- // in this case proper binding will be automatically selected981- if c.ShouldBind(&form) == nil {982- if form.User == "user" && form.Password == "password" {983- c.JSON(200, gin.H{"status": "you are logged in"})984- } else {985- c.JSON(401, gin.H{"status": "unauthorized"})986- }987- }988- })989- router.Run(":8080")990-}991-```992-993-Test it with:994-```sh995-$ curl -v --form user=user --form password=password http://localhost:8080/login996-```997-998-### XML, JSON, YAML and ProtoBuf rendering999-1000-```go1001-func main() {1002- r := gin.Default()1003-1004- // gin.H is a shortcut for map[string]interface{}1005- r.GET("/someJSON", func(c *gin.Context) {1006- c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1007- })1008-1009- r.GET("/moreJSON", func(c *gin.Context) {1010- // You also can use a struct1011- var msg struct {1012- Name string `json:"user"`1013- Message string1014- Number int1015- }1016- msg.Name = "Lena"1017- msg.Message = "hey"1018- msg.Number = 1231019- // Note that msg.Name becomes "user" in the JSON1020- // Will output : {"user": "Lena", "Message": "hey", "Number": 123}1021- c.JSON(http.StatusOK, msg)1022- })1023-1024- r.GET("/someXML", func(c *gin.Context) {1025- c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1026- })1027-1028- r.GET("/someYAML", func(c *gin.Context) {1029- c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})1030- })1031-1032- r.GET("/someProtoBuf", func(c *gin.Context) {1033- reps := []int64{int64(1), int64(2)}1034- label := "test"1035- // The specific definition of protobuf is written in the testdata/protoexample file.1036- data := &protoexample.Test{1037- Label: &label,1038- Reps: reps,1039- }1040- // Note that data becomes binary data in the response1041- // Will output protoexample.Test protobuf serialized data1042- c.ProtoBuf(http.StatusOK, data)1043- })1044-1045- // Listen and serve on 0.0.0.0:80801046- r.Run(":8080")1047-}1048-```1049-1050-#### SecureJSON1051-1052-Using SecureJSON to prevent json hijacking. Default prepends `"while(1),"` to response body if the given struct is array values.1053-1054-```go1055-func main() {1056- r := gin.Default()1057-1058- // You can also use your own secure json prefix1059- // r.SecureJsonPrefix(")]}',\n")1060-1061- r.GET("/someJSON", func(c *gin.Context) {1062- names := []string{"lena", "austin", "foo"}1063-1064- // Will output : while(1);["lena","austin","foo"]1065- c.SecureJSON(http.StatusOK, names)1066- })1067-1068- // Listen and serve on 0.0.0.0:80801069- r.Run(":8080")1070-}1071-```1072-#### JSONP1073-1074-Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists.1075-1076-```go1077-func main() {1078- r := gin.Default()1079-1080- r.GET("/JSONP?callback=x", func(c *gin.Context) {1081- data := map[string]interface{}{1082- "foo": "bar",1083- }1084- 1085- //callback is x1086- // Will output : x({\"foo\":\"bar\"})1087- c.JSONP(http.StatusOK, data)1088- })1089-1090- // Listen and serve on 0.0.0.0:80801091- r.Run(":8080")1092-}1093-```1094-1095-#### AsciiJSON1096-1097-Using AsciiJSON to Generates ASCII-only JSON with escaped non-ASCII chracters.1098-1099-```go1100-func main() {1101- r := gin.Default()1102-1103- r.GET("/someJSON", func(c *gin.Context) {1104- data := map[string]interface{}{1105- "lang": "GO语言",1106- "tag": "<br>",1107- }1108-1109- // will output : {"lang":"GO\u8bed\u8a00","tag":"\u003cbr\u003e"}1110- c.AsciiJSON(http.StatusOK, data)1111- })1112-1113- // Listen and serve on 0.0.0.0:80801114- r.Run(":8080")1115-}1116-```1117-1118-#### PureJSON1119-1120-Normally, 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.1121-This feature is unavailable in Go 1.6 and lower.1122-1123-```go1124-func main() {1125- r := gin.Default()1126- 1127- // Serves unicode entities1128- r.GET("/json", func(c *gin.Context) {1129- c.JSON(200, gin.H{1130- "html": "<b>Hello, world!</b>",1131- })1132- })1133- 1134- // Serves literal characters1135- r.GET("/purejson", func(c *gin.Context) {1136- c.PureJSON(200, gin.H{1137- "html": "<b>Hello, world!</b>",1138- })1139- })1140- 1141- // listen and serve on 0.0.0.0:80801142- r.Run(":8080")1143-}1144-```1145-1146-### Serving static files1147-1148-```go1149-func main() {1150- router := gin.Default()1151- router.Static("/assets", "./assets")1152- router.StaticFS("/more_static", http.Dir("my_file_system"))1153- router.StaticFile("/favicon.ico", "./resources/favicon.ico")1154-1155- // Listen and serve on 0.0.0.0:80801156- router.Run(":8080")1157-}1158-```1159-1160-### Serving data from reader1161-1162-```go1163-func main() {1164- router := gin.Default()1165- router.GET("/someDataFromReader", func(c *gin.Context) {1166- response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")1167- if err != nil || response.StatusCode != http.StatusOK {1168- c.Status(http.StatusServiceUnavailable)1169- return1170- }1171-1172- reader := response.Body1173- contentLength := response.ContentLength1174- contentType := response.Header.Get("Content-Type")1175-1176- extraHeaders := map[string]string{1177- "Content-Disposition": `attachment; filename="gopher.png"`,1178- }1179-1180- c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)1181- })1182- router.Run(":8080")1183-}1184-```1185-1186-### HTML rendering1187-1188-Using LoadHTMLGlob() or LoadHTMLFiles()1189-1190-```go1191-func main() {1192- router := gin.Default()1193- router.LoadHTMLGlob("templates/*")1194- //router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")1195- router.GET("/index", func(c *gin.Context) {1196- c.HTML(http.StatusOK, "index.tmpl", gin.H{1197- "title": "Main website",1198- })1199- })1200- router.Run(":8080")1201-}1202-```1203-1204-templates/index.tmpl1205-1206-```html1207-<html>1208- <h1>1209- {{ .title }}1210- </h1>1211-</html>1212-```1213-1214-Using templates with same name in different directories1215-1216-```go1217-func main() {1218- router := gin.Default()1219- router.LoadHTMLGlob("templates/**/*")1220- router.GET("/posts/index", func(c *gin.Context) {1221- c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{1222- "title": "Posts",1223- })1224- })1225- router.GET("/users/index", func(c *gin.Context) {1226- c.HTML(http.StatusOK, "users/index.tmpl", gin.H{1227- "title": "Users",1228- })1229- })1230- router.Run(":8080")1231-}1232-```1233-1234-templates/posts/index.tmpl1235-1236-```html1237-{{ define "posts/index.tmpl" }}1238-<html><h1>1239- {{ .title }}1240-</h1>1241-<p>Using posts/index.tmpl</p>1242-</html>1243-{{ end }}1244-```1245-1246-templates/users/index.tmpl1247-1248-```html1249-{{ define "users/index.tmpl" }}1250-<html><h1>1251- {{ .title }}1252-</h1>1253-<p>Using users/index.tmpl</p>1254-</html>1255-{{ end }}1256-```1257-1258-#### Custom Template renderer1259-1260-You can also use your own html template render1261-1262-```go1263-import "html/template"1264-1265-func main() {1266- router := gin.Default()1267- html := template.Must(template.ParseFiles("file1", "file2"))1268- router.SetHTMLTemplate(html)1269- router.Run(":8080")1270-}1271-```1272-1273-#### Custom Delimiters1274-1275-You may use custom delims1276-1277-```go1278- r := gin.Default()1279- r.Delims("{[{", "}]}")1280- r.LoadHTMLGlob("/path/to/templates")1281-```1282-1283-#### Custom Template Funcs1284-1285-See the detail [example code](https://github.com/gin-gonic/examples/tree/master/template).1286-1287-main.go1288-1289-```go1290-import (1291- "fmt"1292- "html/template"1293- "net/http"1294- "time"1295-1296- "github.com/gin-gonic/gin"1297-)1298-1299-func formatAsDate(t time.Time) string {1300- year, month, day := t.Date()1301- return fmt.Sprintf("%d%02d/%02d", year, month, day)1302-}1303-1304-func main() {1305- router := gin.Default()1306- router.Delims("{[{", "}]}")1307- router.SetFuncMap(template.FuncMap{1308- "formatAsDate": formatAsDate,1309- })1310- router.LoadHTMLFiles("./testdata/template/raw.tmpl")1311-1312- router.GET("/raw", func(c *gin.Context) {1313- c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{1314- "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),1315- })1316- })1317-1318- router.Run(":8080")1319-}1320-1321-```1322-1323-raw.tmpl1324-1325-```html1326-Date: {[{.now | formatAsDate}]}1327-```1328-1329-Result:1330-```1331-Date: 2017/07/011332-```1333-1334-### Multitemplate1335-1336-Gin allow by default use only one html.Template. Check [a multitemplate render](https://github.com/gin-contrib/multitemplate) for using features like go 1.6 `block template`.1337-1338-### Redirects1339-1340-Issuing a HTTP redirect is easy. Both internal and external locations are supported.1341-1342-```go1343-r.GET("/test", func(c *gin.Context) {1344- c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")1345-})1346-```1347-1348-1349-Issuing a Router redirect, use `HandleContext` like below.1350-1351-``` go1352-r.GET("/test", func(c *gin.Context) {1353- c.Request.URL.Path = "/test2"1354- r.HandleContext(c)1355-})1356-r.GET("/test2", func(c *gin.Context) {1357- c.JSON(200, gin.H{"hello": "world"})1358-})1359-```1360-1361-1362-### Custom Middleware1363-1364-```go1365-func Logger() gin.HandlerFunc {1366- return func(c *gin.Context) {1367- t := time.Now()1368-1369- // Set example variable1370- c.Set("example", "12345")1371-1372- // before request1373-1374- c.Next()1375-1376- // after request1377- latency := time.Since(t)1378- log.Print(latency)1379-1380- // access the status we are sending1381- status := c.Writer.Status()1382- log.Println(status)1383- }1384-}1385-1386-func main() {1387- r := gin.New()1388- r.Use(Logger())1389-1390- r.GET("/test", func(c *gin.Context) {1391- example := c.MustGet("example").(string)1392-1393- // it would print: "12345"1394- log.Println(example)1395- })1396-1397- // Listen and serve on 0.0.0.0:80801398- r.Run(":8080")1399-}1400-```1401-1402-### Using BasicAuth() middleware1403-1404-```go1405-// simulate some private data1406-var secrets = gin.H{1407- "foo": gin.H{"email": "foo@bar.com", "phone": "123433"},1408- "austin": gin.H{"email": "austin@example.com", "phone": "666"},1409- "lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},1410-}1411-1412-func main() {1413- r := gin.Default()1414-1415- // Group using gin.BasicAuth() middleware1416- // gin.Accounts is a shortcut for map[string]string1417- authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{1418- "foo": "bar",1419- "austin": "1234",1420- "lena": "hello2",1421- "manu": "4321",1422- }))1423-1424- // /admin/secrets endpoint1425- // hit "localhost:8080/admin/secrets1426- authorized.GET("/secrets", func(c *gin.Context) {1427- // get user, it was set by the BasicAuth middleware1428- user := c.MustGet(gin.AuthUserKey).(string)1429- if secret, ok := secrets[user]; ok {1430- c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})1431- } else {1432- c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})1433- }1434- })1435-1436- // Listen and serve on 0.0.0.0:80801437- r.Run(":8080")1438-}1439-```1440-1441-### Goroutines inside a middleware1442-1443-When starting new Goroutines inside a middleware or handler, you **SHOULD NOT** use the original context inside it, you have to use a read-only copy.1444-1445-```go1446-func main() {1447- r := gin.Default()1448-1449- r.GET("/long_async", func(c *gin.Context) {1450- // create copy to be used inside the goroutine1451- cCp := c.Copy()1452- go func() {1453- // simulate a long task with time.Sleep(). 5 seconds1454- time.Sleep(5 * time.Second)1455-1456- // note that you are using the copied context "cCp", IMPORTANT1457- log.Println("Done! in path " + cCp.Request.URL.Path)1458- }()1459- })1460-1461- r.GET("/long_sync", func(c *gin.Context) {1462- // simulate a long task with time.Sleep(). 5 seconds1463- time.Sleep(5 * time.Second)1464-1465- // since we are NOT using a goroutine, we do not have to copy the context1466- log.Println("Done! in path " + c.Request.URL.Path)1467- })1468-1469- // Listen and serve on 0.0.0.0:80801470- r.Run(":8080")1471-}1472-```1473-1474-### Custom HTTP configuration1475-1476-Use `http.ListenAndServe()` directly, like this:1477-1478-```go1479-func main() {1480- router := gin.Default()1481- http.ListenAndServe(":8080", router)1482-}1483-```1484-or1485-1486-```go1487-func main() {1488- router := gin.Default()1489-1490- s := &http.Server{1491- Addr: ":8080",1492- Handler: router,1493- ReadTimeout: 10 * time.Second,1494- WriteTimeout: 10 * time.Second,1495- MaxHeaderBytes: 1 << 20,1496- }1497- s.ListenAndServe()1498-}1499-```1500-1501-### Support Let's Encrypt1502-1503-example for 1-line LetsEncrypt HTTPS servers.1504-1505-```go1506-package main1507-1508-import (1509- "log"1510-1511- "github.com/gin-gonic/autotls"1512- "github.com/gin-gonic/gin"1513-)1514-1515-func main() {1516- r := gin.Default()1517-1518- // Ping handler1519- r.GET("/ping", func(c *gin.Context) {1520- c.String(200, "pong")1521- })1522-1523- log.Fatal(autotls.Run(r, "example1.com", "example2.com"))1524-}1525-```1526-1527-example for custom autocert manager.1528-1529-```go1530-package main1531-1532-import (1533- "log"1534-1535- "github.com/gin-gonic/autotls"1536- "github.com/gin-gonic/gin"1537- "golang.org/x/crypto/acme/autocert"1538-)1539-1540-func main() {1541- r := gin.Default()1542-1543- // Ping handler1544- r.GET("/ping", func(c *gin.Context) {1545- c.String(200, "pong")1546- })1547-1548- m := autocert.Manager{1549- Prompt: autocert.AcceptTOS,1550- HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),1551- Cache: autocert.DirCache("/var/www/.cache"),1552- }1553-1554- log.Fatal(autotls.RunWithManager(r, &m))1555-}1556-```1557-1558-### Run multiple service using Gin1559-1560-See the [question](https://github.com/gin-gonic/gin/issues/346) and try the following example:1561-1562-```go1563-package main1564-1565-import (1566- "log"1567- "net/http"1568- "time"1569-1570- "github.com/gin-gonic/gin"1571- "golang.org/x/sync/errgroup"1572-)1573-1574-var (1575- g errgroup.Group1576-)1577-1578-func router01() http.Handler {1579- e := gin.New()1580- e.Use(gin.Recovery())1581- e.GET("/", func(c *gin.Context) {1582- c.JSON(1583- http.StatusOK,1584- gin.H{1585- "code": http.StatusOK,1586- "error": "Welcome server 01",1587- },1588- )1589- })1590-1591- return e1592-}1593-1594-func router02() http.Handler {1595- e := gin.New()1596- e.Use(gin.Recovery())1597- e.GET("/", func(c *gin.Context) {1598- c.JSON(1599- http.StatusOK,1600- gin.H{1601- "code": http.StatusOK,1602- "error": "Welcome server 02",1603- },1604- )1605- })1606-1607- return e1608-}1609-1610-func main() {1611- server01 := &http.Server{1612- Addr: ":8080",1613- Handler: router01(),1614- ReadTimeout: 5 * time.Second,1615- WriteTimeout: 10 * time.Second,1616- }1617-1618- server02 := &http.Server{1619- Addr: ":8081",1620- Handler: router02(),1621- ReadTimeout: 5 * time.Second,1622- WriteTimeout: 10 * time.Second,1623- }1624-1625- g.Go(func() error {1626- return server01.ListenAndServe()1627- })1628-1629- g.Go(func() error {1630- return server02.ListenAndServe()1631- })1632-1633- if err := g.Wait(); err != nil {1634- log.Fatal(err)1635- }1636-}1637-```1638-1639-### Graceful restart or stop1640-1641-Do you want to graceful restart or stop your web server?1642-There are some ways this can be done.1643-1644-We can use [fvbock/endless](https://github.com/fvbock/endless) to replace the default `ListenAndServe`. Refer issue [#296](https://github.com/gin-gonic/gin/issues/296) for more details.1645-1646-```go1647-router := gin.Default()1648-router.GET("/", handler)1649-// [...]1650-endless.ListenAndServe(":4242", router)1651-```1652-1653-An alternative to endless:1654-1655-* [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully.1656-* [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server.1657-* [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers.1658-1659-If you are using Go 1.8, you may not need to use this library! Consider using http.Server's built-in [Shutdown()](https://golang.org/pkg/net/http/#Server.Shutdown) method for graceful shutdowns. See the full [graceful-shutdown](https://github.com/gin-gonic/examples/tree/master/graceful-shutdown) example with gin.1660-1661-```go1662-// +build go1.81663-1664-package main1665-1666-import (1667- "context"1668- "log"1669- "net/http"1670- "os"1671- "os/signal"1672- "syscall"1673- "time"1674-1675- "github.com/gin-gonic/gin"1676-)1677-1678-func main() {1679- router := gin.Default()1680- router.GET("/", func(c *gin.Context) {1681- time.Sleep(5 * time.Second)1682- c.String(http.StatusOK, "Welcome Gin Server")1683- })1684-1685- srv := &http.Server{1686- Addr: ":8080",1687- Handler: router,1688- }1689-1690- go func() {1691- // service connections1692- if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {1693- log.Fatalf("listen: %s\n", err)1694- }1695- }()1696-1697- // Wait for interrupt signal to gracefully shutdown the server with1698- // a timeout of 5 seconds.1699- quit := make(chan os.Signal)1700- // kill (no param) default send syscanll.SIGTERM1701- // kill -2 is syscall.SIGINT1702- // kill -9 is syscall. SIGKILL but can"t be catch, so don't need add it1703- signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)1704- <-quit1705- log.Println("Shutdown Server ...")1706-1707- ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)1708- defer cancel()1709- if err := srv.Shutdown(ctx); err != nil {1710- log.Fatal("Server Shutdown:", err)1711- }1712- // catching ctx.Done(). timeout of 5 seconds.1713- select {1714- case <-ctx.Done():1715- log.Println("timeout of 5 seconds.")1716- }1717- log.Println("Server exiting")1718-}1719-```1720-1721-### Build a single binary with templates1722-1723-You can build a server into a single binary containing templates by using [go-assets][].1724-1725-[go-assets]: https://github.com/jessevdk/go-assets1726-1727-```go1728-func main() {1729- r := gin.New()1730-1731- t, err := loadTemplate()1732- if err != nil {1733- panic(err)1734- }1735- r.SetHTMLTemplate(t)1736-1737- r.GET("/", func(c *gin.Context) {1738- c.HTML(http.StatusOK, "/html/index.tmpl",nil)1739- })1740- r.Run(":8080")1741-}1742-1743-// loadTemplate loads templates embedded by go-assets-builder1744-func loadTemplate() (*template.Template, error) {1745- t := template.New("")1746- for name, file := range Assets.Files {1747- if file.IsDir() || !strings.HasSuffix(name, ".tmpl") {1748- continue1749- }1750- h, err := ioutil.ReadAll(file)1751- if err != nil {1752- return nil, err1753- }1754- t, err = t.New(name).Parse(string(h))1755- if err != nil {1756- return nil, err1757- }1758- }1759- return t, nil1760-}1761-```1762-1763-See a complete example in the `https://github.com/gin-gonic/examples/tree/master/assets-in-binary` directory.1764-1765-### Bind form-data request with custom struct1766-1767-The follow example using custom struct:1768-1769-```go1770-type StructA struct {1771- FieldA string `form:"field_a"`1772-}1773-1774-type StructB struct {1775- NestedStruct StructA1776- FieldB string `form:"field_b"`1777-}1778-1779-type StructC struct {1780- NestedStructPointer *StructA1781- FieldC string `form:"field_c"`1782-}1783-1784-type StructD struct {1785- NestedAnonyStruct struct {1786- FieldX string `form:"field_x"`1787- }1788- FieldD string `form:"field_d"`1789-}1790-1791-func GetDataB(c *gin.Context) {1792- var b StructB1793- c.Bind(&b)1794- c.JSON(200, gin.H{1795- "a": b.NestedStruct,1796- "b": b.FieldB,1797- })1798-}1799-1800-func GetDataC(c *gin.Context) {1801- var b StructC1802- c.Bind(&b)1803- c.JSON(200, gin.H{1804- "a": b.NestedStructPointer,1805- "c": b.FieldC,1806- })1807-}1808-1809-func GetDataD(c *gin.Context) {1810- var b StructD1811- c.Bind(&b)1812- c.JSON(200, gin.H{1813- "x": b.NestedAnonyStruct,1814- "d": b.FieldD,1815- })1816-}1817-1818-func main() {1819- r := gin.Default()1820- r.GET("/getb", GetDataB)1821- r.GET("/getc", GetDataC)1822- r.GET("/getd", GetDataD)1823-1824- r.Run()1825-}1826-```1827-1828-Using the command `curl` command result:1829-1830-```1831-$ curl "http://localhost:8080/getb?field_a=hello&field_b=world"1832-{"a":{"FieldA":"hello"},"b":"world"}1833-$ curl "http://localhost:8080/getc?field_a=hello&field_c=world"1834-{"a":{"FieldA":"hello"},"c":"world"}1835-$ curl "http://localhost:8080/getd?field_x=hello&field_d=world"1836-{"d":"world","x":{"FieldX":"hello"}}1837-```1838-1839-### Try to bind body into different structs1840-1841-The normal methods for binding request body consumes `c.Request.Body` and they1842-cannot be called multiple times.1843-1844-```go1845-type formA struct {1846- Foo string `json:"foo" xml:"foo" binding:"required"`1847-}1848-1849-type formB struct {1850- Bar string `json:"bar" xml:"bar" binding:"required"`1851-}1852-1853-func SomeHandler(c *gin.Context) {1854- objA := formA{}1855- objB := formB{}1856- // This c.ShouldBind consumes c.Request.Body and it cannot be reused.1857- if errA := c.ShouldBind(&objA); errA == nil {1858- c.String(http.StatusOK, `the body should be formA`)1859- // Always an error is occurred by this because c.Request.Body is EOF now.1860- } else if errB := c.ShouldBind(&objB); errB == nil {1861- c.String(http.StatusOK, `the body should be formB`)1862- } else {1863- ...1864- }1865-}1866-```1867-1868-For this, you can use `c.ShouldBindBodyWith`.1869-1870-```go1871-func SomeHandler(c *gin.Context) {1872- objA := formA{}1873- objB := formB{}1874- // This reads c.Request.Body and stores the result into the context.1875- if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil {1876- c.String(http.StatusOK, `the body should be formA`)1877- // At this time, it reuses body stored in the context.1878- } else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {1879- c.String(http.StatusOK, `the body should be formB JSON`)1880- // And it can accepts other formats1881- } else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {1882- c.String(http.StatusOK, `the body should be formB XML`)1883- } else {1884- ...1885- }1886-}1887-```1888-1889-* `c.ShouldBindBodyWith` stores body into the context before binding. This has1890-a slight impact to performance, so you should not use this method if you are1891-enough to call binding at once.1892-* This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`,1893-`ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`,1894-can be called by `c.ShouldBind()` multiple times without any damage to1895-performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)).1896-1897-### http2 server push1898-1899-http.Pusher is supported only **go1.8+**. See the [golang blog](https://blog.golang.org/h2push) for detail information.1900-1901-```go1902-package main1903-1904-import (1905- "html/template"1906- "log"1907-1908- "github.com/gin-gonic/gin"1909-)1910-1911-var html = template.Must(template.New("https").Parse(`1912-<html>1913-<head>1914- <title>Https Test</title>1915- <script src="/assets/app.js"></script>1916-</head>1917-<body>1918- <h1 style="color:red;">Welcome, Ginner!</h1>1919-</body>1920-</html>1921-`))1922-1923-func main() {1924- r := gin.Default()1925- r.Static("/assets", "./assets")1926- r.SetHTMLTemplate(html)1927-1928- r.GET("/", func(c *gin.Context) {1929- if pusher := c.Writer.Pusher(); pusher != nil {1930- // use pusher.Push() to do server push1931- if err := pusher.Push("/assets/app.js", nil); err != nil {1932- log.Printf("Failed to push: %v", err)1933- }1934- }1935- c.HTML(200, "https", gin.H{1936- "status": "success",1937- })1938- })1939-1940- // Listen and Server in https://127.0.0.1:80801941- r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")1942-}1943-```1944-1945-### Define format for the log of routes1946-1947-The default log of routes is:1948-```1949-[GIN-debug] POST /foo --> main.main.func1 (3 handlers)1950-[GIN-debug] GET /bar --> main.main.func2 (3 handlers)1951-[GIN-debug] GET /status --> main.main.func3 (3 handlers)1952-```1953-1954-If you want to log this information in given format (e.g. JSON, key values or something else), then you can define this format with `gin.DebugPrintRouteFunc`.1955-In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs.1956-```go1957-import (1958- "log"1959- "net/http"1960-1961- "github.com/gin-gonic/gin"1962-)1963-1964-func main() {1965- r := gin.Default()1966- gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {1967- log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers)1968- }1969-1970- r.POST("/foo", func(c *gin.Context) {1971- c.JSON(http.StatusOK, "foo")1972- })1973-1974- r.GET("/bar", func(c *gin.Context) {1975- c.JSON(http.StatusOK, "bar")1976- })1977-1978- r.GET("/status", func(c *gin.Context) {1979- c.JSON(http.StatusOK, "ok")1980- })1981-1982- // Listen and Server in http://0.0.0.0:80801983- r.Run()1984-}1985-```1986-1987-### Set and get a cookie1988-1989-```go1990-import (1991- "fmt"1992-1993- "github.com/gin-gonic/gin"1994-)1995-1996-func main() {1997-1998- router := gin.Default()1999-2000- router.GET("/cookie", func(c *gin.Context) {2001-2002- cookie, err := c.Cookie("gin_cookie")2003-2004- if err != nil {2005- cookie = "NotSet"2006- c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)2007- }2008-2009- fmt.Printf("Cookie value: %s \n", cookie)2010- })2011-2012- router.Run()2013-}2014-```2015-2016-2017-## Testing2018-2019-The `net/http/httptest` package is preferable way for HTTP testing.2020-2021-```go2022-package main2023-2024-func setupRouter() *gin.Engine {2025- r := gin.Default()2026- r.GET("/ping", func(c *gin.Context) {2027- c.String(200, "pong")2028- })2029- return r2030-}2031-2032-func main() {2033- r := setupRouter()2034- r.Run(":8080")2035-}2036-```2037-2038-Test for code example above:2039-2040-```go2041-package main2042-2043-import (2044- "net/http"2045- "net/http/httptest"2046- "testing"2047-2048- "github.com/stretchr/testify/assert"2049-)2050-2051-func TestPingRoute(t *testing.T) {2052- router := setupRouter()2053-2054- w := httptest.NewRecorder()2055- req, _ := http.NewRequest("GET", "/ping", nil)2056- router.ServeHTTP(w, req)2057-2058- assert.Equal(t, 200, w.Code)2059- assert.Equal(t, "pong", w.Body.String())2060-}2061-```2062-2063-## Users2064-2065-Awesome project lists using [Gin](https://github.com/gin-gonic/gin) web framework.2066-2067-* [gorush](https://github.com/appleboy/gorush): A push notification server written in Go.2068-* [fnproject](https://github.com/fnproject/fn): The container native, cloud agnostic serverless platform.2069-* [photoprism](https://github.com/photoprism/photoprism): Personal photo management powered by Go and Google TensorFlow.2070-* [krakend](https://github.com/devopsfaith/krakend): Ultra performant API Gateway with middlewares.2071-* [picfit](https://github.com/thoas/picfit): An image resizing server written in Go.