Gin web 框架
Gin 是Golang編寫的web框架。它具有類似于martini
的API接口,同時比httprouter
快40倍的性能。如果你需要較好的性能和友好的開發(fā)方式,你會喜歡上Gin
。
安裝
如果想要安裝Gin依賴,你需要安裝Go并正確的設置工作空間。
- 已經(jīng)安裝Go(1.11以上版本,并且啟用Go Mod),你可以下面的指令加入依賴:
$ go get -u github.com/gin-gonic/gin
- 在你的代碼中引入:
import "github/gin-gonic/gin"
- (可選的)引入
net/http
。在使用諸如http.StatusOk
的時候,他是必須引入的:
import "net/http"
簡單使用
# 假設example.go文件中,存在以下代碼
$ cat example.go
package main
import "github.com/gin-gonic/gin"
func main() {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.JSON(200, gin.H{
"message": "pong",
})
})
r.Run() // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080")
}
# 運行example.go文件,并且在瀏覽器上瀏覽0.0.0.0:8080/ping (對于windows :“l(fā)ocalhost:8080/ping”)
$ go run example.go
性能測試
Gin 使用了定制版的https://github.com/julienschmidt/httprouter
Benchmark name | (1) | (2) | (3) | (4) | |
---|---|---|---|---|---|
Benchmark Gin_GithubAll | 43550 | 27364 ns/op | 0 B/op | 0 allocs/op | |
Benchmark Ace_GithubAll | 40543 | 29670 ns/op | 0 B/op | 0 allocs/op | |
Benchmark Aero_GithubAll | 57632 | 20648 ns/op | 0 B/op | 0 allocs/op | |
Benchmark Bear_GithubAll | 9234 | 216179 ns/op | 86448 B/op | 943 allocs/op | |
Benchmark Beego_GithubAll | 7407 | 243496 ns/op | 71456 B/op | 609 allocs/op | |
Benchmark Bone_GithubAll | 420 | 2922835 ns/op | 720160 B/op | 8620 allocs/op | |
Benchmark Chi_GithubAll | 7620 | 238331 ns/op | 87696 B/op | 609 allocs/op | |
Benchmark Denco_GithubAll | 18355 | 64494 ns/op | 20224 B/op | 167 allocs/op | |
Benchmark Echo_GithubAll | 31251 | 38479 ns/op | 0 B/op | 0 allocs/op | |
Benchmark GocraftWeb_GithubAll | 4117 | 300062 ns/op | 131656 B/op | 1686 allocs/op | |
Benchmark Goji_GithubAll | 3274 | 416158 ns/op | 56112 B/op | 334 allocs/op | |
Benchmark Gojiv2_GithubAll | 1402 | 870518 ns/op | 352720 B/op | 4321 allocs/op | |
Benchmark GoJsonRest_GithubAll | 2976 | 401507 ns/op | 134371 B/op | 2737 allocs/op | |
Benchmark GoRestful_GithubAll | 410 | 2913158 ns/op | 910144 B/op | 2938 allocs/op | |
Benchmark GorillaMux_GithubAll | 346 | 3384987 ns/op | 251650 B/op | 1994 allocs/op | |
Benchmark GowwwRouter_GithubAll | 10000 | 143025 ns/op | 72144 B/op | 501 allocs/op | |
Benchmark HttpRouter_GithubAll | 55938 | 21360 ns/op | 0 B/op | 0 allocs/op | |
Benchmark HttpTreeMux_GithubAll | 10000 | 153944 ns/op | 65856 B/op | 671 allocs/op | |
Benchmark Kocha_GithubAll | 10000 | 106315 ns/op | 23304 B/op | 843 allocs/op | |
Benchmark LARS_GithubAll | 47779 | 25084 ns/op | 0 B/op | 0 allocs/op | |
Benchmark Macaron_GithubAll | 3266 | 371907 ns/op | 149409 B/op | 1624 allocs/op | |
Benchmark Martini_GithubAll | 331 | 3444706 ns/op | 226551 B/op | 2325 allocs/op | |
Benchmark Pat_GithubAll | 273 | 4381818 ns/op | 1483152 B/op | 26963 allocs/op | |
Benchmark Possum_GithubAll | 10000 | 164367 ns/op | 84448 B/op | 609 allocs/op | |
Benchmark R2router_GithubAll | 10000 | 160220 ns/op | 77328 B/op | 979 allocs/op | |
Benchmark Rivet_GithubAll | 14625 | 82453 ns/op | 16272 B/op | 167 allocs/op | |
Benchmark Tango_GithubAll | 6255 | 279611 ns/op | 63826 B/op | 1618 allocs/op | |
Benchmark TigerTonic_GithubAll | 2008 | 687874 ns/op | 193856 B/op | 4474 allocs/op | |
Benchmark Traffic_GithubAll | 355 | 3478508 ns/op | 820744 B/op | 14114 allocs/op | |
Benchmark Vulcan_GithubAll | 6885 | 193333 ns/op | 19894 B/op | 609 allocs/op |
- (1): 恒定時間的重復操作,數(shù)值越高,性能越高。
- (2): 定量的重復操作,時間越低,性能越高。
- (3): 占用內(nèi)存量,數(shù)值越低,性能越高。
- (4): 每次重復操作的平均之間,數(shù)值越低,性能越高。
Gin v1 穩(wěn)定版
- 零內(nèi)存(Zero allocation, 內(nèi)存控制對于web服務來說非常重要,性能影響非常大)路由。
- 是最快的路由、框架。
- 完整的單元測試組件。
- 經(jīng)歷過正規(guī)校驗。
- 固定的API,版本更替不會導致代碼修改。
使用jsoniter
json iterator 是一個性能很高的json處理組件
Gin 使用encoding/json
作為默認json解析工具,但是你可以通過其他tag
改變?yōu)?code>jsoniter。
$ go build -tags=jsoniter .
API 示例
你可以在Gin 示例倉庫 找到一些可以運行的示例。
使用GET, POST, PUT, PATCH, DELETE and OPTIONS
func main() {
// 使用默認中間件創(chuàng)建gin路由器
// 日志、恢復中間件,
// 日志中間件用于記錄請求等日志信息。
// 恢復中間件用戶在發(fā)生以外的時候,返回500狀態(tài)碼,
// 避免請求阻塞等意外情況發(fā)生
router := gin.Default()
router.GET("/someGet", getting)
router.POST("/somePost", posting)
router.PUT("/somePut", putting)
router.DELETE("/someDelete", deleting)
router.PATCH("/somePatch", patching)
router.HEAD("/someHead", head)
router.OPTIONS("/someOptions", options)
// 默認情況下,服務將會監(jiān)聽8080端口,或者使用PORT環(huán)境變量
router.Run()
// router.Run(":3000") 可以指定監(jiān)聽端口
}
路徑參數(shù)
func main() {
router := gin.Default()
// 匹配 /user/john
// 不匹配 /user 或 /john
router.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
// 匹配 /user/john 和 /user/john/send
// 如果其他路由都不匹配 /user/john, 這個請求才會被定向到這個路由
// However, this one will match /user/john/ and also /user/john/send
// If no other routers match /user/john, it will redirect to /user/john/
router.GET("/user/:name/*action", func(c *gin.Context) {
name := c.Param("name")
action := c.Param("action")
message := name + " is " + action
c.String(http.StatusOK, message)
})
// 每個請求的上下文中都會保存定義的路由
router.POST("/user/:name/*action", func(c *gin.Context) {
c.FullPath() == "/user/:name/*action" // true
})
router.Run(":8080")
}
查詢字符串參數(shù)(querystring parameters)
func main() {
router := gin.Default()
// 查詢字符串參數(shù)使用現(xiàn)有的基礎請求對象進行解析。
// 響應下列請求的url為: /welcome?firstname=Jane&lastname=Doe
router.GET("/welcome", func(c *gin.Context) {
firstname := c.DefaultQuery("firstname", "Guest")
lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")
c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
})
router.Run(":8080")
}
Multipart/Urlencoded Form(表單)
func main() {
router := gin.Default()
router.POST("/form_post", func(c *gin.Context) {
message := c.PostForm("message")
nick := c.DefaultPostForm("nick", "anonymous")
c.JSON(200, gin.H{
"status": "posted",
"message": message,
"nick": nick,
})
})
router.Run(":8080")
}
其他示例:query + post form(表單)
請求
POST /post?id=1234&page=1 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
name=manu&message=this_is_great
目標服務
func main() {
router := gin.Default()
router.POST("/post", func(c *gin.Context) {
id := c.Query("id")
page := c.DefaultQuery("page", "0")
name := c.PostForm("name")
message := c.PostForm("message")
fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
})
router.Run(":8080")
}
響應
id: 1234; page: 1; name: manu; message: this_is_great
將字符串參數(shù)(querystring)或 提交表單(postform) 轉換為Map
請求
POST /post?ids[a]=1234&ids[b]=hello HTTP/1.1
Content-Type: application/x-www-form-urlencoded
names[first]=thinkerou&names[second]=tianou
目標服務
func main() {
router := gin.Default()
router.POST("/post", func(c *gin.Context) {
ids := c.QueryMap("ids")
names := c.PostFormMap("names")
fmt.Printf("ids: %v; names: %v", ids, names)
})
router.Run(":8080")
}
響應
ids: map[b:hello a:1234]; names: map[second:tianou first:thinkerou]
上傳文件
單文件
系統(tǒng)不應該信任(直接使用)文件的文件名。
詳情參考:Content-Disposition on MDN 、#1693
文件名始終是可選的,并且不能被應用程序直接使用:路徑信息應被刪除,并且應完成向服務器文件系統(tǒng)規(guī)則的轉換。
func main() {
router := gin.Default()
// 為組合表單(multipart)設置低內(nèi)存(默認32MiB)
router.MaxMultipartMemory = 8 << 20 // 8 MiB
router.POST("/upload", func(c *gin.Context) {
// 單文件
file, _ := c.FormFile("file")
log.Println(file.Filename)
// 上傳到指定的目的地
c.SaveUploadedFile(file, dst)
c.String(http.StatusOK, fmt.Sprintf("'%s' uploaded!", file.Filename))
})
router.Run(":8080")
}
使用curl
curl -X POST http://localhost:8080/upload \
-F "file=@/Users/appleboy/test.zip" \
-H "Content-Type: multipart/form-data"
多文件
查看更詳細的示例代碼
func main() {
router := gin.Default()
// 為組合表單(multipart)設置低內(nèi)存(默認32MiB)
router.MaxMultipartMemory = 8 << 20 // 8 MiB
router.POST("/upload", func(c *gin.Context) {
// 多表單
form, _ := c.MultipartForm()
files := form.File["upload[]"]
for _, file := range files {
log.Println(file.Filename)
// 上傳到指定位置
c.SaveUploadedFile(file, dst)
}
c.String(http.StatusOK, fmt.Sprintf("%d files uploaded!", len(files)))
})
router.Run(":8080")
}
使用curl
curl -X POST http://localhost:8080/upload \
-F "upload[]=@/Users/appleboy/test1.zip" \
-F "upload[]=@/Users/appleboy/test2.zip" \
-H "Content-Type: multipart/form-data"
分組路由
func main() {
router := gin.Default()
// 分組示例:v1
v1 := router.Group("/v1")
{
v1.POST("/login", loginEndpoint)
v1.POST("/submit", submitEndpoint)
v1.POST("/read", readEndpoint)
}
// 分組示例:v2
v2 := router.Group("/v2")
{
v2.POST("/login", loginEndpoint)
v2.POST("/submit", submitEndpoint)
v2.POST("/read", readEndpoint)
}
router.Run(":8080")
}
使用沒有中間件的空白Gin
將:
// 默認使用日志和恢復中間件
r := gin.Default()
替換為:
r := gin.New()
使用中間件
func main() {
// 創(chuàng)建一個默認不帶任何中間件的路由器
r := gin.New()
// 全局中間件
// 即使設置GIN_MODE=release,日志中間件也會將日志寫入到gin.DefaultWriter。
// 默認情況下,gin.DefaultWriter = os.Stdout
r.Use(gin.Logger())
// 恢復中間件將會從任何異常種復原,并且返回500狀態(tài)碼
r.Use(gin.Recovery())
// 對于每個路由中間件,您可以根據(jù)需要添加任意數(shù)量。
r.GET("/benchmark", MyBenchLogger(), benchEndpoint)
// 權限、認證路由組
// authorized := r.Group("/", AuthRequired())
// 如下
authorized := r.Group("/")
// 組級別中間件,可以定制化創(chuàng)建
// AuthRequired()中間件僅會存在于認證路由組
authorized.Use(AuthRequired())
{
authorized.POST("/login", loginEndpoint)
authorized.POST("/submit", submitEndpoint)
authorized.POST("/read", readEndpoint)
// 嵌套組
testing := authorized.Group("testing")
testing.GET("/analytics", analyticsEndpoint)
}
// 監(jiān)聽端口:8080
r.Run(":8080")
}
自定義恢復行為
func main() {
// 創(chuàng)建一個默認不帶任何中間件的路由器
r := gin.New()
// 全局中間件
// 即使設置GIN_MODE=release,日志中間件也會將日志寫入到gin.DefaultWriter。
// 默認情況下,gin.DefaultWriter = os.Stdout
r.Use(gin.Logger())
// 恢復中間件將會從任何異常種復原,并且返回500狀態(tài)碼
r.Use(gin.CustomRecovery(func(c *gin.Context, recovered interface{}) {
if err, ok := recovered.(string); ok {
c.String(http.StatusInternalServerError, fmt.Sprintf("error: %s", err))
}
c.AbortWithStatus(http.StatusInternalServerError)
}))
r.GET("/panic", func(c *gin.Context) {
// 字符串-異常 -- 定制化中間件可以保存該異常到數(shù)據(jù)庫或者通知用戶
// panic with a string -- the custom middleware could save this to a database or report it to the user
panic("foo")
})
r.GET("/", func(c *gin.Context) {
c.String(http.StatusOK, "ohai")
})
// Listen and serve on 0.0.0.0:8080
r.Run(":8080")
}
如何將日志寫入到文件
func main() {
// 關閉控制臺顏色,在日志寫入到文件的時候不需要開啟控制臺顏色。
gin.DisableConsoleColor()
// 將日志記錄到文件
f, _ := os.Create("gin.log")
gin.DefaultWriter = io.MultiWriter(f)
// 如果你希望將日志同時輸出到文件和控制臺,使用下列代碼
// gin.DefaultWriter = io.MultiWriter(f, os.Stdout)
router := gin.Default()
router.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
router.Run(":8080")
}
自定義日志格式
func main() {
router := gin.New()
// 格式化日志中間件會將日志寫入到gin.DefaultWriter
// 默認情況下 gin.DefaultWriter = os.Stdout
router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams) string {
// 你自定義的格式
return fmt.Sprintf("%s - [%s] \"%s %s %s %d %s \"%s\" %s\"\n",
param.ClientIP,
param.TimeStamp.Format(time.RFC1123),
param.Method,
param.Path,
param.Request.Proto,
param.StatusCode,
param.Latency,
param.Request.UserAgent(),
param.ErrorMessage,
)
}))
router.Use(gin.Recovery())
router.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
router.Run(":8080")
}
樣例輸出
::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" "
控制日志輸出的顏色
默認情況下,控制臺上輸出的日志應根據(jù)檢測到的TTY進行著色。
無顏色的日志
func main() {
// 關閉日志顏色
gin.DisableConsoleColor()
// 創(chuàng)建默認gin路由器
// 日志和恢復中間件
router := gin.Default()
router.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
router.Run(":8080")
}
存在顏色的日志
func main() {
// 強制使用顏色
gin.ForceConsoleColor()
// 創(chuàng)建默認gin路由器
// 日志和恢復中間件
router := gin.Default()
router.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
router.Run(":8080")
}
模型綁定與校驗
如果要將請求體綁定到一種類型,可以使用模型綁定。Gin當前支持綁定json
、XML
、YAML
和標準的表單數(shù)據(jù)(foo=bar&boo=baz)。
Gin 使用go-playground/validator/v10進行校驗。查看使用文檔
請注意,您需要在要綁定的所有字段上設置相應的綁定標簽(tag)。例如,當需要綁定json類型的數(shù)據(jù),進行如下設置json:"filedname"
。
Gin提供了兩種方式綁定數(shù)據(jù)
- 類型:強制綁定(Must bind)
- 方法:
Bind
、BindJSON
、BindXML
、BindQuery
、BindYAML
、BindHeader
- 行為: 這些方法的底層會調(diào)用
mustBindWith
。如果發(fā)生了綁定異常,請求(request)將會直接失敗,并返回c.AbortWithError(400,err).SetType(ErrorTypeBind)
。
這將導致直接返回400狀態(tài)碼,并且Content-Type
頭將會被設置為text/plain; charset=utf-8
。
如果你嘗試在發(fā)生綁定異常之前設置返回狀態(tài)碼,將會有警告出現(xiàn)[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 witch 422
。
如果你希望控制綁定的更多行為,可以考慮使用ShouldBind
。
- 方法:
- 類型:弱綁定(Should bind)
- 方法:
ShouldBind
、ShouldBindJSON
、ShouldBindXML
、ShouldBindQuery
、ShouldBindYAML
、ShouldBindHeader
- 行為:這些方法的底層回調(diào)用
ShouldBindJSON
。如果發(fā)生了綁定異常,該異常會返回給開發(fā)人員,開發(fā)者可以適當?shù)靥幚碚埱蠛湾e誤。
- 方法:
當使用綁定方法時,Gin會嘗試從請求頭中的Content-Type
值推斷綁定依賴。如果你確定需要綁定什么數(shù)據(jù),可以使用ShouldBind
或者MustBind
。
你可以指定那些字段是必須的。如果一個字段聲明了:binding:"required"
,并且在解析的時候,沒有該字段,將會返回一個error。
// 從json綁定
type Login struct {
User string `form:"user" json:"user" xml:"user" binding:"required"`
Password string `form:"password" json:"password" xml:"password" binding:"required"`
}
func main() {
router := gin.Default()
// 樣例:JOSN綁定 ({"user": "manu", "password": "123"})
router.POST("/loginJSON", func(c *gin.Context) {
var json Login
if err := c.ShouldBindJSON(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if json.User != "manu" || json.Password != "123" {
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
return
}
c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
})
// 樣例:XML綁定 (
// <?xml version="1.0" encoding="UTF-8"?>
// <root>
// <user>user</user>
// <password>123</password>
// </root>)
router.POST("/loginXML", func(c *gin.Context) {
var xml Login
if err := c.ShouldBindXML(&xml); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if xml.User != "manu" || xml.Password != "123" {
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
return
}
c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
})
// 例如:綁定HTML表單(form)(user=manu&password=123)
router.POST("/loginForm", func(c *gin.Context) {
var form Login
// 將會從請求頭中content-type推斷綁定類型
//This will infer what binder to use depending on the content-type header.
if err := c.ShouldBind(&form); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if form.User != "manu" || form.Password != "123" {
c.JSON(http.StatusUnauthorized, gin.H{"status": "unauthorized"})
return
}
c.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
})
// 監(jiān)聽8080端口
router.Run(":8080")
}
樣例請求
$ curl -v -X POST \
http://localhost:8080/loginJSON \
-H 'content-type: application/json' \
-d '{ "user": "manu" }'
> POST /loginJSON HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.51.0
> Accept: */*
> content-type: application/json
> Content-Length: 18
>
* upload completely sent off: 18 out of 18 bytes
< HTTP/1.1 400 Bad Request
< Content-Type: application/json; charset=utf-8
< Date: Fri, 04 Aug 2017 03:51:31 GMT
< Content-Length: 100
<
{"error":"Key: 'Login.Password' Error:Field validation for 'Password' failed on the 'required' tag"}
跳過認證
使用上面的curl
命令運行上面的示例時,它返回錯誤。因為該示例對密碼使用binding:"required"
。如果對密碼使用binding:"-"
,則在再次運行以上示例時不會返回錯誤。
定制化認證器
注冊自定義驗證器。詳情請查示例代碼
package main
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
)
// Booking 包含綁定和驗證數(shù)據(jù)
type Booking struct {
CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`
CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`
}
var bookableDate validator.Func = func(fl validator.FieldLevel) bool {
date, ok := fl.Field().Interface().(time.Time)
if ok {
today := time.Now()
if today.After(date) {
return false
}
}
return true
}
func main() {
route := gin.Default()
if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("bookabledate", bookableDate)
}
route.GET("/bookable", getBookable)
route.Run(":8085")
}
func getBookable(c *gin.Context) {
var b Booking
if err := c.ShouldBindWith(&b, binding.Query); err == nil {
c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
} else {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
}
}
$ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17"
{"message":"Booking dates are valid!"}
$ curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09"
{"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"}
$ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10"
{"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}%
結構體等級的校驗 可以通過同樣的方式進行注冊。更多信息請查看結構體校驗 。
僅綁定 QueryString
ShouldBindQuery
方法僅綁定查詢參數(shù)。詳情請看詳細信息
package main
import (
"log"
"github.com/gin-gonic/gin"
)
type Person struct {
Name string `form:"name"`
Address string `form:"address"`
}
func main() {
route := gin.Default()
route.Any("/testing", startPage)
route.Run(":8085")
}
func startPage(c *gin.Context) {
var person Person
if c.ShouldBindQuery(&person) == nil {
log.Println("====== Only Bind By Query String ======")
log.Println(person.Name)
log.Println(person.Address)
}
c.String(200, "Success")
}
綁定QueryString或Post數(shù)據(jù)
詳細請看詳細信息
package main
import (
"log"
"time"
"github.com/gin-gonic/gin"
)
type Person struct {
Name string `form:"name"`
Address string `form:"address"`
Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`
CreateTime time.Time `form:"createTime" time_format:"unixNano"`
UnixTime time.Time `form:"unixTime" time_format:"unix"`
}
func main() {
route := gin.Default()
route.GET("/testing", startPage)
route.Run(":8085")
}
func startPage(c *gin.Context) {
var person Person
// 如果為Get方法,僅處理Form數(shù)據(jù)
// 如果為Post方法,首先檢查`content-type`,如果是JSON或者XML將會是使用表單數(shù)據(jù)
if c.ShouldBind(&person) == nil {
log.Println(person.Name)
log.Println(person.Address)
log.Println(person.Birthday)
log.Println(person.CreateTime)
log.Println(person.UnixTime)
}
c.String(200, "Success")
}
使用如下代碼進行測試
$ curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"
綁定URI
詳情請看詳細信息
package main
import "github.com/gin-gonic/gin"
type Person struct {
ID string `uri:"id" binding:"required,uuid"`
Name string `uri:"name" binding:"required"`
}
func main() {
route := gin.Default()
route.GET("/:name/:id", func(c *gin.Context) {
var person Person
if err := c.ShouldBindUri(&person); err != nil {
c.JSON(400, gin.H{"msg": err})
return
}
c.JSON(200, gin.H{"name": person.Name, "uuid": person.ID})
})
route.Run(":8088")
}
使用如下代碼進行測試
$ curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3
$ curl -v localhost:8088/thinkerou/not-uuid
綁定Header
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
type testHeader struct {
Rate int `header:"Rate"`
Domain string `header:"Domain"`
}
func main() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
h := testHeader{}
if err := c.ShouldBindHeader(&h); err != nil {
c.JSON(200, err)
}
fmt.Printf("%#v\n", h)
c.JSON(200, gin.H{"Rate": h.Rate, "Domain": h.Domain})
})
r.Run()
// 客戶端
// curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/
// 輸出
// {"Domain":"music","Rate":300}
}
綁定HTML的多選框
查看詳細信息
main.go
...
type myForm struct {
Colors []string `form:"colors[]"`
}
...
func formHandler(c *gin.Context) {
var fakeForm myForm
c.ShouldBind(&fakeForm)
c.JSON(200, gin.H{"color": fakeForm.Colors})
}
...
form.html
<form action="/" method="POST">
<p>Check some colors</p>
<label for="red">Red</label>
<input type="checkbox" name="colors[]" value="red" id="red">
<label for="green">Green</label>
<input type="checkbox" name="colors[]" value="green" id="green">
<label for="blue">Blue</label>
<input type="checkbox" name="colors[]" value="blue" id="blue">
<input type="submit">
</form>
結果:
{"color":["red","green","blue"]}
Multipart/Urlencoded數(shù)據(jù)綁定
type ProfileForm struct {
Name string `form:"name" binding:"required"`
Avatar *multipart.FileHeader `form:"avatar" binding:"required"`
// 或者多文件
// Avatars []*multipart.FileHeader `form:"avatar" binding:"required"`
}
func main() {
router := gin.Default()
router.POST("/profile", func(c *gin.Context) {
//您可以使用顯式綁定聲明來綁定多部分表單:
// c.ShouldBindWith(&form, binding.Form)
// 或者配合ShouldBind使用autobinding方法
var form ProfileForm
// 在這種情況下,將自動選擇適當?shù)慕壎? if err := c.ShouldBind(&form); err != nil {
c.String(http.StatusBadRequest, "bad request")
return
}
err := c.SaveUploadedFile(form.Avatar, form.Avatar.Filename)
if err != nil {
c.String(http.StatusInternalServerError, "unknown error")
return
}
// db.Save(&form)
c.String(http.StatusOK, "ok")
})
router.Run(":8080")
}
使用下列代碼進行測試
$ curl -X POST -v --form name=user --form "avatar=@./avatar.png" http://localhost:8080/profile
XML, JSON, YAML 和 ProtoBuf 渲染
func main() {
r := gin.Default()
// gin.H is a shortcut for map[string]interface{}
// gin.H 是map[string]interface{}快捷方式(等效)
r.GET("/someJSON", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
r.GET("/moreJSON", func(c *gin.Context) {
// 你也可以使用一個結構體
var msg struct {
Name string `json:"user"`
Message string
Number int
}
msg.Name = "Lena"
msg.Message = "hey"
msg.Number = 123
// 注意: msg.Name 在JSON文件中將會變?yōu)?"user"
// 輸出: {"user": "Lena", "Message": "hey", "Number": 123}
c.JSON(http.StatusOK, msg)
})
r.GET("/someXML", func(c *gin.Context) {
c.XML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
r.GET("/someYAML", func(c *gin.Context) {
c.YAML(http.StatusOK, gin.H{"message": "hey", "status": http.StatusOK})
})
r.GET("/someProtoBuf", func(c *gin.Context) {
reps := []int64{int64(1), int64(2)}
label := "test"
// protobuf的特定定義寫在testdata / protoexample文件中。
data := &protoexample.Test{
Label: &label,
Reps: reps,
}
// 注意: data 將會在應答中變?yōu)槎M制數(shù)據(jù)
// 輸出: protoexample.Test protobuf serialized data
c.ProtoBuf(http.StatusOK, data)
})
// 服務運行并監(jiān)聽: 0.0.0.0:8080
r.Run(":8080")
}
SecureJSON
使用SecureJSON防止json劫持。如果給定的結構是數(shù)組值,則默認值在響應主體前加上“ while(1)”。
func main() {
r := gin.Default()
// 你可以使用你自定義的JSON安全前綴
// r.SecureJsonPrefix(")]}',\n")
r.GET("/someJSON", func(c *gin.Context) {
names := []string{"lena", "austin", "foo"}
// 輸出: while(1);["lena","austin","foo"]
c.SecureJSON(http.StatusOK, names)
})
// 服務運行并監(jiān)聽: 0.0.0.0:8080
r.Run(":8080")
}
JSONP
使用JSONP從其他域中的服務器請求數(shù)據(jù)。如果查詢參數(shù)回調(diào)存在,則將回調(diào)添加到響應主體。
func main() {
r := gin.Default()
r.GET("/JSONP", func(c *gin.Context) {
data := gin.H{
"foo": "bar",
}
// 回調(diào)為:x
// 輸出 : x({\"foo\":\"bar\"})
c.JSONP(http.StatusOK, data)
})
// 服務運行并監(jiān)聽: 0.0.0.0:8080
r.Run(":8080")
// 客戶端
// curl http://127.0.0.1:8080/JSONP?callback=x
}
AsciiJSON
通常,JSON用其unicode實體替換特殊的HTML字符,例如<變成\ u003c。如果要按字面意義編碼此類字符,則可以改用PureJSON。此功能在Go 1.6及更低版本中不可用。
func main() {
r := gin.Default()
// 服務unicode實體
r.GET("/json", func(c *gin.Context) {
c.JSON(200, gin.H{
"html": "<b>Hello, world!</b>",
})
})
// 提供文字字符
r.GET("/purejson", func(c *gin.Context) {
c.PureJSON(200, gin.H{
"html": "<b>Hello, world!</b>",
})
})
// 服務運行并監(jiān)聽:0.0.0.0:8080
r.Run(":8080")
}
靜態(tài)文件
func main() {
router := gin.Default()
router.Static("/assets", "./assets")
router.StaticFS("/more_static", http.Dir("my_file_system"))
router.StaticFile("/favicon.ico", "./resources/favicon.ico")
// 服務運行并監(jiān)聽:0.0.0.0:8080
router.Run(":8080")
}
從文件中讀取數(shù)據(jù)
func main() {
router := gin.Default()
router.GET("/local/file", func(c *gin.Context) {
c.File("local/file.go")
})
var fs http.FileSystem = // ...
router.GET("/fs/file", func(c *gin.Context) {
c.FileFromFS("fs/file.go", fs)
})
}
從Reader讀取數(shù)據(jù)
func main() {
router := gin.Default()
router.GET("/someDataFromReader", func(c *gin.Context) {
response, err := http.Get("https://raw.githubusercontent.com/gin-gonic/logo/master/color.png")
if err != nil || response.StatusCode != http.StatusOK {
c.Status(http.StatusServiceUnavailable)
return
}
reader := response.Body
defer reader.Close()
contentLength := response.ContentLength
contentType := response.Header.Get("Content-Type")
extraHeaders := map[string]string{
"Content-Disposition": `attachment; filename="gopher.png"`,
}
c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)
})
router.Run(":8080")
}
翻譯HTML
使用 LoadHTMLGlob() 或 LoadHTMLFiles()
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/*")
//router.LoadHTMLFiles("templates/template1.html", "templates/template2.html")
router.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "index.tmpl", gin.H{
"title": "Main website",
})
})
router.Run(":8080")
}
templates/index.tmpl
<html>
<h1>
{{ .title }}
</h1>
</html>
使用不同文件夾下的相同名的模版
func main() {
router := gin.Default()
router.LoadHTMLGlob("templates/**/*")
router.GET("/posts/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
"title": "Posts",
})
})
router.GET("/users/index", func(c *gin.Context) {
c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
"title": "Users",
})
})
router.Run(":8080")
}
templates/posts/index.tmpl
{{ define "posts/index.tmpl" }}
<html><h1>
{{ .title }}
</h1>
<p>Using posts/index.tmpl</p>
</html>
{{ end }}
templates/users/index.tmpl
{{ define "users/index.tmpl" }}
<html><h1>
{{ .title }}
</h1>
<p>Using users/index.tmpl</p>
</html>
{{ end }}
自定義模版翻譯器
你可以使用自己的html模版
翻譯器
import "html/template"
func main() {
router := gin.Default()
html := template.Must(template.ParseFiles("file1", "file2"))
router.SetHTMLTemplate(html)
router.Run(":8080")
}
自定義分隔符
例如使用如下分隔符
r := gin.Default()
r.Delims("{[{", "}]}")
r.LoadHTMLGlob("/path/to/templates")
自定義模版函數(shù)
詳情請看[示例代碼](See the detail example code.)
main.go
import (
"fmt"
"html/template"
"net/http"
"time"
"github.com/gin-gonic/gin"
)
func formatAsDate(t time.Time) string {
year, month, day := t.Date()
return fmt.Sprintf("%d%02d/%02d", year, month, day)
}
func main() {
router := gin.Default()
router.Delims("{[{", "}]}")
router.SetFuncMap(template.FuncMap{
"formatAsDate": formatAsDate,
})
router.LoadHTMLFiles("./testdata/template/raw.tmpl")
router.GET("/raw", func(c *gin.Context) {
c.HTML(http.StatusOK, "raw.tmpl", gin.H{
"now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
})
})
router.Run(":8080")
}
raw.tmpl
Date: {[{.now | formatAsDate}]}
結果
Date: 2017/07/01
多模版
Gin默認僅允許使用html.Template. 檢查多模板渲染是否使用諸如go 1.6塊模板之類的功能.
重定向
發(fā)起重定向很簡單,內(nèi)部和外部都可以使用。
r.GET("/test", func(c *gin.Context) {
c.Redirect(http.StatusMovedPermanently, "http://www.google.com/")
})
Post請求重定向。Issue:#444
r.POST("/test", func(c *gin.Context) {
c.Redirect(http.StatusFound, "/foo")
})
發(fā)起路由重定向,仿照下方示例使用HandleContext()
r.GET("/test", func(c *gin.Context) {
c.Request.URL.Path = "/test2"
r.HandleContext(c)
})
r.GET("/test2", func(c *gin.Context) {
c.JSON(200, gin.H{"hello": "world"})
})
自定義中間件
func Logger() gin.HandlerFunc {
return func(c *gin.Context) {
t := time.Now()
// 設置變量:example
c.Set("example", "12345")
// 請求之前
c.Next()
// 請求之后
latency := time.Since(t)
log.Print(latency)
// 訪問我們正在發(fā)送的狀態(tài)
status := c.Writer.Status()
log.Println(status)
}
}
func main() {
r := gin.New()
r.Use(Logger())
r.GET("/test", func(c *gin.Context) {
example := c.MustGet("example").(string)
// 將會打印12345
log.Println(example)
})
// 服務啟動并監(jiān)聽8080端口
r.Run(":8080")
}
使用BaseAuth()中間件
// 模擬一些私有的數(shù)據(jù)
var secrets = gin.H{
"foo": gin.H{"email": "foo@bar.com", "phone": "123433"},
"austin": gin.H{"email": "austin@example.com", "phone": "666"},
"lena": gin.H{"email": "lena@guapa.com", "phone": "523443"},
}
func main() {
r := gin.Default()
// Group 使用 gin.BasicAuth() 中間件
// gin.Accounts 的類型是 map[string]string
authorized := r.Group("/admin", gin.BasicAuth(gin.Accounts{
"foo": "bar",
"austin": "1234",
"lena": "hello2",
"manu": "4321",
}))
// /admin/secrets 終點
// 隱藏 "localhost:8080/admin/secrets
authorized.GET("/secrets", func(c *gin.Context) {
// 獲取用戶, 有BaseAuth中間件控制
user := c.MustGet(gin.AuthUserKey).(string)
if secret, ok := secrets[user]; ok {
c.JSON(http.StatusOK, gin.H{"user": user, "secret": secret})
} else {
c.JSON(http.StatusOK, gin.H{"user": user, "secret": "NO SECRET :("})
}
})
// 服務運行并監(jiān)聽8080端口
r.Run(":8080")
}
中間件的Goroutines
在中間件或處理程序中啟動新的Goroutines時,不應使用其內(nèi)部的原始上下文,而必須使用只讀副本
func main() {
r := gin.Default()
r.GET("/long_async", func(c *gin.Context) {
// 創(chuàng)建要在goroutine中使用的副本
cCp := c.Copy()
go func() {
// 用time.Sleep()模擬一個長任務。 5秒
time.Sleep(5 * time.Second)
// 請注意,您正在使用復制的上下文“ cCp”,重要
log.Println("Done! in path " + cCp.Request.URL.Path)
}()
})
r.GET("/long_sync", func(c *gin.Context) {
// 用time.Sleep()模擬一個長任務,5秒
time.Sleep(5 * time.Second)
// 因為我們沒有使用goroutine,所以我們不必復制上下文
log.Println("Done! in path " + c.Request.URL.Path)
})
// 服務啟動并監(jiān)聽8080端口
r.Run(":8080")
}
自定義Http配置
直接使用http.ListenAndServe(),如下
func main() {
router := gin.Default()
http.ListenAndServe(":8080", router)
}
或者
func main() {
router := gin.Default()
s := &http.Server{
Addr: ":8080",
Handler: router,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
MaxHeaderBytes: 1 << 20,
}
s.ListenAndServe()
}
支持 Let'sEncrypt
1行LetsEncrypt HTTPS服務器的示例。
package main
import (
"log"
"github.com/gin-gonic/autotls"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
// 監(jiān)聽ping路徑
r.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
log.Fatal(autotls.Run(r, "example1.com", "example2.com"))
}
自定義自動證書管理器的示例
package main
import (
"log"
"github.com/gin-gonic/autotls"
"github.com/gin-gonic/gin"
"golang.org/x/crypto/acme/autocert"
)
func main() {
r := gin.Default()
// 監(jiān)聽ping路徑
r.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
m := autocert.Manager{
Prompt: autocert.AcceptTOS,
HostPolicy: autocert.HostWhitelist("example1.com", "example2.com"),
Cache: autocert.DirCache("/var/www/.cache"),
}
log.Fatal(autotls.RunWithManager(r, &m))
}
使用Gin啟動多個服務
查看相關問題,并嘗試以下代碼
package main
import (
"log"
"net/http"
"time"
"github.com/gin-gonic/gin"
"golang.org/x/sync/errgroup"
)
var (
g errgroup.Group
)
func router01() http.Handler {
e := gin.New()
e.Use(gin.Recovery())
e.GET("/", func(c *gin.Context) {
c.JSON(
http.StatusOK,
gin.H{
"code": http.StatusOK,
"error": "Welcome server 01",
},
)
})
return e
}
func router02() http.Handler {
e := gin.New()
e.Use(gin.Recovery())
e.GET("/", func(c *gin.Context) {
c.JSON(
http.StatusOK,
gin.H{
"code": http.StatusOK,
"error": "Welcome server 02",
},
)
})
return e
}
func main() {
server01 := &http.Server{
Addr: ":8080",
Handler: router01(),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
server02 := &http.Server{
Addr: ":8081",
Handler: router02(),
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
}
g.Go(func() error {
err := server01.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
return err
})
g.Go(func() error {
err := server02.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
log.Fatal(err)
}
return err
})
if err := g.Wait(); err != nil {
log.Fatal(err)
}
}
正常關機、重啟
您可以使用幾種方法正常執(zhí)行關機或重新啟動。您可以使用為此專門構建的第三方程序包,也可以使用內(nèi)置程序包中的功能和方法手動執(zhí)行相同的操作。
第三方組件
我們可以使用fvbock/endless替換掉默認的ListenAndServe。具體信息請查看:問題#296
router := gin.Default()
router.GET("/", handler)
// [...]
endless.ListenAndServe(":4242", router)
備選方案
- manners: 優(yōu)雅的關閉Http服務
- graceful: Graceful是Go軟件包,可用于正常關閉http.Handler服務器。
- grace: 為Go服務器實現(xiàn)平穩(wěn)重啟和零停機部署。
手動關閉
如果使用的是Go 1.8或更高版本,則可能不需要使用這些庫。考慮使用http.Server的內(nèi)置Shutdown()方法進行正常關閉。下面的示例描述了它的用法,我們在這里有更多使用gin的示例。
// +build go1.8
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/", func(c *gin.Context) {
time.Sleep(5 * time.Second)
c.String(http.StatusOK, "Welcome Gin Server")
})
srv := &http.Server{
Addr: ":8080",
Handler: router,
}
// Initializing the server in a goroutine so that
// it won't block the graceful shutdown handling below
go func() {
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("listen: %s\n", err)
}
}()
// Wait for interrupt signal to gracefully shutdown the server with
// a timeout of 5 seconds.
quit := make(chan os.Signal)
// kill (no param) default send syscall.SIGTERM
// kill -2 is syscall.SIGINT
// kill -9 is syscall.SIGKILL but can't be catch, so don't need add it
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down server...")
// The context is used to inform the server it has 5 seconds to finish
// the request it is currently handling
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := srv.Shutdown(ctx); err != nil {
log.Fatal("Server forced to shutdown:", err)
}
log.Println("Server exiting")
}
使用模板構建一個二進制文件
您可以使用 go-assets 將服務器構建為包含模板的單個二進制文件。
func main() {
r := gin.New()
t, err := loadTemplate()
if err != nil {
panic(err)
}
r.SetHTMLTemplate(t)
r.GET("/", func(c *gin.Context) {
c.HTML(http.StatusOK, "/html/index.tmpl",nil)
})
r.Run(":8080")
}
// loadTemplate加載go-assets-builder嵌入的模板
func loadTemplate() (*template.Template, error) {
t := template.New("")
for name, file := range Assets.Files {
defer file.Close()
if file.IsDir() || !strings.HasSuffix(name, ".tmpl") {
continue
}
h, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
t, err = t.New(name).Parse(string(h))
if err != nil {
return nil, err
}
}
return t, nil
}
請參閱https://github.com/gin-gonic/examples/tree/master/assets-in-binary目錄中的完整示例。
將表單數(shù)據(jù)請求與自定義結構綁定
以下示例使用自定義結構:
type StructA struct {
FieldA string `form:"field_a"`
}
type StructB struct {
NestedStruct StructA
FieldB string `form:"field_b"`
}
type StructC struct {
NestedStructPointer *StructA
FieldC string `form:"field_c"`
}
type StructD struct {
NestedAnonyStruct struct {
FieldX string `form:"field_x"`
}
FieldD string `form:"field_d"`
}
func GetDataB(c *gin.Context) {
var b StructB
c.Bind(&b)
c.JSON(200, gin.H{
"a": b.NestedStruct,
"b": b.FieldB,
})
}
func GetDataC(c *gin.Context) {
var b StructC
c.Bind(&b)
c.JSON(200, gin.H{
"a": b.NestedStructPointer,
"c": b.FieldC,
})
}
func GetDataD(c *gin.Context) {
var b StructD
c.Bind(&b)
c.JSON(200, gin.H{
"x": b.NestedAnonyStruct,
"d": b.FieldD,
})
}
func main() {
r := gin.Default()
r.GET("/getb", GetDataB)
r.GET("/getc", GetDataC)
r.GET("/getd", GetDataD)
r.Run()
}
Using the command curl command result:
使用指令curl
的結果如下:
$ curl "http://localhost:8080/getb?field_a=hello&field_b=world"
{"a":{"FieldA":"hello"},"b":"world"}
$ curl "http://localhost:8080/getc?field_a=hello&field_c=world"
{"a":{"FieldA":"hello"},"c":"world"}
$ curl "http://localhost:8080/getd?field_x=hello&field_d=world"
{"d":"world","x":{"FieldX":"hello"}}
嘗試將主體綁定到不同的結構體
綁定請求正文的常規(guī)方法消耗c.Request.Body
,不能多次調(diào)用它們。
type formA struct {
Foo string `json:"foo" xml:"foo" binding:"required"`
}
type formB struct {
Bar string `json:"bar" xml:"bar" binding:"required"`
}
func SomeHandler(c *gin.Context) {
objA := formA{}
objB := formB{}
// 此c.ShouldBind消耗c.Request.Body,并且無法重用
if errA := c.ShouldBind(&objA); errA == nil {
c.String(http.StatusOK, `the body should be formA`)
// 由于c.Request.Body現(xiàn)在是EOF,因此總是會發(fā)生錯誤
} else if errB := c.ShouldBind(&objB); errB == nil {
c.String(http.StatusOK, `the body should be formB`)
} else {
...
}
}
為此,您可以使用c.ShouldBindBodyWith。
func SomeHandler(c *gin.Context) {
objA := formA{}
objB := formB{}
// 這將讀取c.Request.Body并將結果存儲到上下文中。
if errA := c.ShouldBindBodyWith(&objA, binding.JSON); errA == nil {
c.String(http.StatusOK, `the body should be formA`)
// 此時,它會重用存儲在上下文中的請求體。
} else if errB := c.ShouldBindBodyWith(&objB, binding.JSON); errB == nil {
c.String(http.StatusOK, `the body should be formB JSON`)
// 它可以接受其他格式
} else if errB2 := c.ShouldBindBodyWith(&objB, binding.XML); errB2 == nil {
c.String(http.StatusOK, `the body should be formB XML`)
} else {
...
}
}
-
c.ShouldBindBodyWith
在綁定之前將主體存儲到上下文中。這對性能有輕微影響,因此,如果足以一次調(diào)用綁定,則不應使用此方法。 - 僅某些格式需要此功能
JSON
,XML
,MsgPack
,ProtoBuf
。對于其他格式,c.ShouldBind()
可以多次調(diào)用Query
,Form
,FormPost
,FormMultipart
,而不會對性能造成任何損害(請參閱#1341)。
http2 服務端推送功能
http.Pusher功能在go.18版本后才開始支持,有關詳細信息,請參見golang 博客
package main
import (
"html/template"
"log"
"github.com/gin-gonic/gin"
)
var html = template.Must(template.New("https").Parse(`
<html>
<head>
<title>Https Test</title>
<script src="/assets/app.js"></script>
</head>
<body>
<h1 style="color:red;">Welcome, Ginner!</h1>
</body>
</html>
`))
func main() {
r := gin.Default()
r.Static("/assets", "./assets")
r.SetHTMLTemplate(html)
r.GET("/", func(c *gin.Context) {
if pusher := c.Writer.Pusher(); pusher != nil {
// use pusher.Push() to do server push
if err := pusher.Push("/assets/app.js", nil); err != nil {
log.Printf("Failed to push: %v", err)
}
}
c.HTML(200, "https", gin.H{
"status": "success",
})
})
// 服務運行并監(jiān)聽8080端口
r.RunTLS(":8080", "./testdata/server.pem", "./testdata/server.key")
}
聲明路由的日志格式
默認的日志格式為:
[GIN-debug] POST /foo --> main.main.func1 (3 handlers)
[GIN-debug] GET /bar --> main.main.func2 (3 handlers)
[GIN-debug] GET /status --> main.main.func3 (3 handlers)
你可以使用gin.DebugPrintRouteFunc來聲明指定的日志格式信息(例如:json、鍵值對或其他)進行日志打印。在下面的示例中,我們使用標準日志包記錄所有路由,但是您可以使用其他適合您需求的日志工具。
import (
"log"
"net/http"
"github.com/gin-gonic/gin"
)
func main() {
r := gin.Default()
gin.DebugPrintRouteFunc = func(httpMethod, absolutePath, handlerName string, nuHandlers int) {
log.Printf("endpoint %v %v %v %v\n", httpMethod, absolutePath, handlerName, nuHandlers)
}
r.POST("/foo", func(c *gin.Context) {
c.JSON(http.StatusOK, "foo")
})
r.GET("/bar", func(c *gin.Context) {
c.JSON(http.StatusOK, "bar")
})
r.GET("/status", func(c *gin.Context) {
c.JSON(http.StatusOK, "ok")
})
// 服務運行并監(jiān)聽8080端口
r.Run()
}
設置、獲取Cookie
import (
"fmt"
"github.com/gin-gonic/gin"
)
func main() {
router := gin.Default()
router.GET("/cookie", func(c *gin.Context) {
cookie, err := c.Cookie("gin_cookie")
if err != nil {
cookie = "NotSet"
c.SetCookie("gin_cookie", "test", 3600, "/", "localhost", false, true)
}
fmt.Printf("Cookie value: %s \n", cookie)
})
router.Run()
}
測試
net/http/httptest
軟件包是HTTP測試的首選方法。
package main
func setupRouter() *gin.Engine {
r := gin.Default()
r.GET("/ping", func(c *gin.Context) {
c.String(200, "pong")
})
return r
}
func main() {
r := setupRouter()
r.Run(":8080")
}
上方代碼的測試用例
package main
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/stretchr/testify/assert"
)
func TestPingRoute(t *testing.T) {
router := setupRouter()
w := httptest.NewRecorder()
req, _ := http.NewRequest("GET", "/ping", nil)
router.ServeHTTP(w, req)
assert.Equal(t, 200, w.Code)
assert.Equal(t, "pong", w.Body.String())
}