docs: update markdown format (#3260)
Signed-off-by: Bo-Yi Wu <appleboy.tw@gmail.com>
This commit is contained in:
parent
c35bde97d5
commit
79dd72deb9
80
README.md
80
README.md
@ -14,7 +14,6 @@
|
|||||||
|
|
||||||
Gin is a web framework written in Go (Golang). It features a martini-like API with performance that is up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin.
|
Gin is a web framework written in Go (Golang). It features a martini-like API with performance that is up to 40 times faster thanks to [httprouter](https://github.com/julienschmidt/httprouter). If you need performance and good productivity, you will love Gin.
|
||||||
|
|
||||||
|
|
||||||
## Contents
|
## Contents
|
||||||
|
|
||||||
- [Gin Web Framework](#gin-web-framework)
|
- [Gin Web Framework](#gin-web-framework)
|
||||||
@ -23,7 +22,7 @@ Gin is a web framework written in Go (Golang). It features a martini-like API wi
|
|||||||
- [Quick start](#quick-start)
|
- [Quick start](#quick-start)
|
||||||
- [Benchmarks](#benchmarks)
|
- [Benchmarks](#benchmarks)
|
||||||
- [Gin v1. stable](#gin-v1-stable)
|
- [Gin v1. stable](#gin-v1-stable)
|
||||||
- [Build with jsoniter/go-json](#build-with-json-replacement)
|
- [Build with json replacement](#build-with-json-replacement)
|
||||||
- [Build without `MsgPack` rendering feature](#build-without-msgpack-rendering-feature)
|
- [Build without `MsgPack` rendering feature](#build-without-msgpack-rendering-feature)
|
||||||
- [API Examples](#api-examples)
|
- [API Examples](#api-examples)
|
||||||
- [Using GET, POST, PUT, PATCH, DELETE and OPTIONS](#using-get-post-put-patch-delete-and-options)
|
- [Using GET, POST, PUT, PATCH, DELETE and OPTIONS](#using-get-post-put-patch-delete-and-options)
|
||||||
@ -38,6 +37,7 @@ Gin is a web framework written in Go (Golang). It features a martini-like API wi
|
|||||||
- [Grouping routes](#grouping-routes)
|
- [Grouping routes](#grouping-routes)
|
||||||
- [Blank Gin without middleware by default](#blank-gin-without-middleware-by-default)
|
- [Blank Gin without middleware by default](#blank-gin-without-middleware-by-default)
|
||||||
- [Using middleware](#using-middleware)
|
- [Using middleware](#using-middleware)
|
||||||
|
- [Custom Recovery behavior](#custom-recovery-behavior)
|
||||||
- [How to write log file](#how-to-write-log-file)
|
- [How to write log file](#how-to-write-log-file)
|
||||||
- [Custom Log Format](#custom-log-format)
|
- [Custom Log Format](#custom-log-format)
|
||||||
- [Controlling Log output coloring](#controlling-log-output-coloring)
|
- [Controlling Log output coloring](#controlling-log-output-coloring)
|
||||||
@ -75,6 +75,7 @@ Gin is a web framework written in Go (Golang). It features a martini-like API wi
|
|||||||
- [Build a single binary with templates](#build-a-single-binary-with-templates)
|
- [Build a single binary with templates](#build-a-single-binary-with-templates)
|
||||||
- [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct)
|
- [Bind form-data request with custom struct](#bind-form-data-request-with-custom-struct)
|
||||||
- [Try to bind body into different structs](#try-to-bind-body-into-different-structs)
|
- [Try to bind body into different structs](#try-to-bind-body-into-different-structs)
|
||||||
|
- [Bind form-data request with custom struct and custom tag](#bind-form-data-request-with-custom-struct-and-custom-tag)
|
||||||
- [http2 server push](#http2-server-push)
|
- [http2 server push](#http2-server-push)
|
||||||
- [Define format for the log of routes](#define-format-for-the-log-of-routes)
|
- [Define format for the log of routes](#define-format-for-the-log-of-routes)
|
||||||
- [Set and get a cookie](#set-and-get-a-cookie)
|
- [Set and get a cookie](#set-and-get-a-cookie)
|
||||||
@ -89,7 +90,7 @@ To install Gin package, you need to install Go and set your Go workspace first.
|
|||||||
1. You first need [Go](https://golang.org/) installed (**version 1.15+ is required**), then you can use the below Go command to install Gin.
|
1. You first need [Go](https://golang.org/) installed (**version 1.15+ is required**), then you can use the below Go command to install Gin.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
$ go get -u github.com/gin-gonic/gin
|
go get -u github.com/gin-gonic/gin
|
||||||
```
|
```
|
||||||
|
|
||||||
2. Import it in your code:
|
2. Import it in your code:
|
||||||
@ -193,12 +194,15 @@ Gin uses a custom version of [HttpRouter](https://github.com/julienschmidt/httpr
|
|||||||
Gin uses `encoding/json` as default json package but you can change it by build from other tags.
|
Gin uses `encoding/json` as default json package but you can change it by build from other tags.
|
||||||
|
|
||||||
[jsoniter](https://github.com/json-iterator/go)
|
[jsoniter](https://github.com/json-iterator/go)
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
$ go build -tags=jsoniter .
|
go build -tags=jsoniter .
|
||||||
```
|
```
|
||||||
|
|
||||||
[go-json](https://github.com/goccy/go-json)
|
[go-json](https://github.com/goccy/go-json)
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
$ go build -tags=go_json .
|
go build -tags=go_json .
|
||||||
```
|
```
|
||||||
|
|
||||||
## Build without `MsgPack` rendering feature
|
## Build without `MsgPack` rendering feature
|
||||||
@ -206,7 +210,7 @@ $ go build -tags=go_json .
|
|||||||
Gin enables `MsgPack` rendering feature by default. But you can disable this feature by specifying `nomsgpack` build tag.
|
Gin enables `MsgPack` rendering feature by default. But you can disable this feature by specifying `nomsgpack` build tag.
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
$ go build -tags=nomsgpack .
|
go build -tags=nomsgpack .
|
||||||
```
|
```
|
||||||
|
|
||||||
This is useful to reduce the binary size of executable files. See the [detail information](https://github.com/gin-gonic/gin/pull/1852).
|
This is useful to reduce the binary size of executable files. See the [detail information](https://github.com/gin-gonic/gin/pull/1852).
|
||||||
@ -316,7 +320,7 @@ func main() {
|
|||||||
|
|
||||||
### Another example: query + post form
|
### Another example: query + post form
|
||||||
|
|
||||||
```
|
```sh
|
||||||
POST /post?id=1234&page=1 HTTP/1.1
|
POST /post?id=1234&page=1 HTTP/1.1
|
||||||
Content-Type: application/x-www-form-urlencoded
|
Content-Type: application/x-www-form-urlencoded
|
||||||
|
|
||||||
@ -340,13 +344,13 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
```
|
```sh
|
||||||
id: 1234; page: 1; name: manu; message: this_is_great
|
id: 1234; page: 1; name: manu; message: this_is_great
|
||||||
```
|
```
|
||||||
|
|
||||||
### Map as querystring or postform parameters
|
### Map as querystring or postform parameters
|
||||||
|
|
||||||
```
|
```sh
|
||||||
POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1
|
POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1
|
||||||
Content-Type: application/x-www-form-urlencoded
|
Content-Type: application/x-www-form-urlencoded
|
||||||
|
|
||||||
@ -368,7 +372,7 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
```
|
```sh
|
||||||
ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou]
|
ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou]
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -485,8 +489,8 @@ instead of
|
|||||||
r := gin.Default()
|
r := gin.Default()
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### Using middleware
|
### Using middleware
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func main() {
|
func main() {
|
||||||
// Creates a router without any middleware by default
|
// Creates a router without any middleware by default
|
||||||
@ -527,6 +531,7 @@ func main() {
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Custom Recovery behavior
|
### Custom Recovery behavior
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func main() {
|
func main() {
|
||||||
// Creates a router without any middleware by default
|
// Creates a router without any middleware by default
|
||||||
@ -560,6 +565,7 @@ func main() {
|
|||||||
```
|
```
|
||||||
|
|
||||||
### How to write log file
|
### How to write log file
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func main() {
|
func main() {
|
||||||
// Disable Console Color, you don't need console color when writing the logs to file.
|
// Disable Console Color, you don't need console color when writing the logs to file.
|
||||||
@ -582,6 +588,7 @@ func main() {
|
|||||||
```
|
```
|
||||||
|
|
||||||
### Custom Log Format
|
### Custom Log Format
|
||||||
|
|
||||||
```go
|
```go
|
||||||
func main() {
|
func main() {
|
||||||
router := gin.New()
|
router := gin.New()
|
||||||
@ -613,8 +620,9 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**Sample Output**
|
Sample Output
|
||||||
```
|
|
||||||
|
```sh
|
||||||
::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" "
|
::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" "
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -669,6 +677,7 @@ Gin uses [**go-playground/validator/v10**](https://github.com/go-playground/vali
|
|||||||
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"`.
|
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"`.
|
||||||
|
|
||||||
Also, Gin provides two sets of methods for binding:
|
Also, Gin provides two sets of methods for binding:
|
||||||
|
|
||||||
- **Type** - Must bind
|
- **Type** - Must bind
|
||||||
- **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`, `BindHeader`, `BindTOML`
|
- **Methods** - `Bind`, `BindJSON`, `BindXML`, `BindQuery`, `BindYAML`, `BindHeader`, `BindTOML`
|
||||||
- **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.
|
- **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.
|
||||||
@ -749,8 +758,9 @@ func main() {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**Sample request**
|
Sample request
|
||||||
```shell
|
|
||||||
|
```sh
|
||||||
$ curl -v -X POST \
|
$ curl -v -X POST \
|
||||||
http://localhost:8080/loginJSON \
|
http://localhost:8080/loginJSON \
|
||||||
-H 'content-type: application/json' \
|
-H 'content-type: application/json' \
|
||||||
@ -771,9 +781,7 @@ $ curl -v -X POST \
|
|||||||
{"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}
|
{"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}
|
||||||
```
|
```
|
||||||
|
|
||||||
**Skip validate**
|
Skip validate: 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.
|
||||||
|
|
||||||
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.
|
|
||||||
|
|
||||||
### Custom Validators
|
### Custom Validators
|
||||||
|
|
||||||
@ -927,8 +935,9 @@ func startPage(c *gin.Context) {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Test it with:
|
Test it with:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
$ curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"
|
curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"
|
||||||
```
|
```
|
||||||
|
|
||||||
### Bind Uri
|
### Bind Uri
|
||||||
@ -964,9 +973,10 @@ func main() {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Test it with:
|
Test it with:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
$ curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3
|
curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3
|
||||||
$ curl -v localhost:8088/thinkerou/not-uuid
|
curl -v localhost:8088/thinkerou/not-uuid
|
||||||
```
|
```
|
||||||
|
|
||||||
### Bind Header
|
### Bind Header
|
||||||
@ -1050,7 +1060,7 @@ form.html
|
|||||||
|
|
||||||
result:
|
result:
|
||||||
|
|
||||||
```
|
```json
|
||||||
{"color":["red","green","blue"]}
|
{"color":["red","green","blue"]}
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -1093,8 +1103,9 @@ func main() {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Test it with:
|
Test it with:
|
||||||
|
|
||||||
```sh
|
```sh
|
||||||
$ curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile
|
curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile
|
||||||
```
|
```
|
||||||
|
|
||||||
### XML, JSON, YAML and ProtoBuf rendering
|
### XML, JSON, YAML and ProtoBuf rendering
|
||||||
@ -1171,6 +1182,7 @@ func main() {
|
|||||||
r.Run(":8080")
|
r.Run(":8080")
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### JSONP
|
#### JSONP
|
||||||
|
|
||||||
Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists.
|
Using JSONP to request data from a server in a different domain. Add callback to response body if the query parameter callback exists.
|
||||||
@ -1452,7 +1464,8 @@ Date: {[{.now | formatAsDate}]}
|
|||||||
```
|
```
|
||||||
|
|
||||||
Result:
|
Result:
|
||||||
```
|
|
||||||
|
```sh
|
||||||
Date: 2017/07/01
|
Date: 2017/07/01
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -1471,6 +1484,7 @@ r.GET("/test", func(c *gin.Context) {
|
|||||||
```
|
```
|
||||||
|
|
||||||
Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444)
|
Issuing a HTTP redirect from POST. Refer to issue: [#444](https://github.com/gin-gonic/gin/issues/444)
|
||||||
|
|
||||||
```go
|
```go
|
||||||
r.POST("/test", func(c *gin.Context) {
|
r.POST("/test", func(c *gin.Context) {
|
||||||
c.Redirect(http.StatusFound, "/foo")
|
c.Redirect(http.StatusFound, "/foo")
|
||||||
@ -1489,7 +1503,6 @@ r.GET("/test2", func(c *gin.Context) {
|
|||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
|
|
||||||
### Custom Middleware
|
### Custom Middleware
|
||||||
|
|
||||||
```go
|
```go
|
||||||
@ -1612,6 +1625,7 @@ func main() {
|
|||||||
http.ListenAndServe(":8080", router)
|
http.ListenAndServe(":8080", router)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
or
|
or
|
||||||
|
|
||||||
```go
|
```go
|
||||||
@ -1794,9 +1808,9 @@ endless.ListenAndServe(":4242", router)
|
|||||||
|
|
||||||
Alternatives:
|
Alternatives:
|
||||||
|
|
||||||
* [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully.
|
|
||||||
* [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server.
|
|
||||||
* [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers.
|
* [grace](https://github.com/facebookgo/grace): Graceful restart & zero downtime deploy for Go servers.
|
||||||
|
* [graceful](https://github.com/tylerb/graceful): Graceful is a Go package enabling graceful shutdown of an http.Handler server.
|
||||||
|
* [manners](https://github.com/braintree/manners): A polite Go HTTP server that shuts down gracefully.
|
||||||
|
|
||||||
#### Manually
|
#### Manually
|
||||||
|
|
||||||
@ -1972,7 +1986,7 @@ func main() {
|
|||||||
|
|
||||||
Using the command `curl` command result:
|
Using the command `curl` command result:
|
||||||
|
|
||||||
```
|
```sh
|
||||||
$ curl "http://localhost:8080/getb?field_a=hello&field_b=world"
|
$ curl "http://localhost:8080/getb?field_a=hello&field_b=world"
|
||||||
{"a":{"FieldA":"hello"},"b":"world"}
|
{"a":{"FieldA":"hello"},"b":"world"}
|
||||||
$ curl "http://localhost:8080/getc?field_a=hello&field_c=world"
|
$ curl "http://localhost:8080/getc?field_a=hello&field_c=world"
|
||||||
@ -2031,10 +2045,10 @@ func SomeHandler(c *gin.Context) {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
* `c.ShouldBindBodyWith` stores body into the context before binding. This has
|
1. `c.ShouldBindBodyWith` stores body into the context before binding. This has
|
||||||
a slight impact to performance, so you should not use this method if you are
|
a slight impact to performance, so you should not use this method if you are
|
||||||
enough to call binding at once.
|
enough to call binding at once.
|
||||||
* This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`,
|
2. This feature is only needed for some formats -- `JSON`, `XML`, `MsgPack`,
|
||||||
`ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`,
|
`ProtoBuf`. For other formats, `Query`, `Form`, `FormPost`, `FormMultipart`,
|
||||||
can be called by `c.ShouldBind()` multiple times without any damage to
|
can be called by `c.ShouldBind()` multiple times without any damage to
|
||||||
performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)).
|
performance (See [#1341](https://github.com/gin-gonic/gin/pull/1341)).
|
||||||
@ -2146,7 +2160,8 @@ func main() {
|
|||||||
### Define format for the log of routes
|
### Define format for the log of routes
|
||||||
|
|
||||||
The default log of routes is:
|
The default log of routes is:
|
||||||
```
|
|
||||||
|
```sh
|
||||||
[GIN-debug] POST /foo --> main.main.func1 (3 handlers)
|
[GIN-debug] POST /foo --> main.main.func1 (3 handlers)
|
||||||
[GIN-debug] GET /bar --> main.main.func2 (3 handlers)
|
[GIN-debug] GET /bar --> main.main.func2 (3 handlers)
|
||||||
[GIN-debug] GET /status --> main.main.func3 (3 handlers)
|
[GIN-debug] GET /status --> main.main.func3 (3 handlers)
|
||||||
@ -2154,6 +2169,7 @@ The default log of routes is:
|
|||||||
|
|
||||||
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`.
|
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`.
|
||||||
In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs.
|
In the example below, we log all routes with standard log package but you can use another log tools that suits of your needs.
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import (
|
import (
|
||||||
"log"
|
"log"
|
||||||
@ -2257,6 +2273,7 @@ func main() {
|
|||||||
**Notice:** If you are using a CDN service, you can set the `Engine.TrustedPlatform`
|
**Notice:** If you are using a CDN service, you can set the `Engine.TrustedPlatform`
|
||||||
to skip TrustedProxies check, it has a higher priority than TrustedProxies.
|
to skip TrustedProxies check, it has a higher priority than TrustedProxies.
|
||||||
Look at the example below:
|
Look at the example below:
|
||||||
|
|
||||||
```go
|
```go
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
@ -2345,4 +2362,3 @@ Awesome project lists using [Gin](https://github.com/gin-gonic/gin) web framewor
|
|||||||
* [picfit](https://github.com/thoas/picfit): An image resizing server written in Go.
|
* [picfit](https://github.com/thoas/picfit): An image resizing server written in Go.
|
||||||
* [brigade](https://github.com/brigadecore/brigade): Event-based Scripting for Kubernetes.
|
* [brigade](https://github.com/brigadecore/brigade): Event-based Scripting for Kubernetes.
|
||||||
* [dkron](https://github.com/distribworks/dkron): Distributed, fault tolerant job scheduling system.
|
* [dkron](https://github.com/distribworks/dkron): Distributed, fault tolerant job scheduling system.
|
||||||
|
|
||||||
|
Loading…
Reference in New Issue
Block a user