Gin框架介紹
Gin
是一個用Go語言編寫的web框架。它是一個類似於martini
但擁有更好性能的API框架, 由於使用了httprouter
,速度提高了近40倍。 如果你是性能和高效的追求者, 你會愛上Gin
。Go世界里最流行的Web框架,Github上有32K+
star。 基於httprouter開發的Web框架。 中文文檔齊全,簡單易用的輕量級框架。
- 安裝:
go get -u github.com/gin-gonic/gin
- 第一個Gin實例
package main import ( "github.com/gin-gonic/gin" ) func main() { // 創建一個默認的路由引擎 r := gin.Default() // GET:請求方式;/hello:請求的路徑 // 當客戶端以GET方法請求/hello路徑時,會執行后面的匿名函數 r.GET("/hello", func(c *gin.Context) { // c.JSON:返回JSON格式的數據 c.JSON(200, gin.H{ "message": "Hello world!", }) }) // 啟動HTTP服務,默認在0.0.0.0:8080啟動服務 r.Run() }
// 將上面的代碼保存並編譯執行,然后使用瀏覽器打開127.0.0.1:8080/hello
就能看到一串JSON字符串。
RESTful API
REST與技術無關,代表的是一種軟件架構風格,REST是Representational State Transfer的簡稱,中文翻譯為“表征狀態轉移”或“表現層狀態轉化”。
簡單來說,REST的含義就是客戶端與Web服務器之間進行交互的時候,使用HTTP協議中的4個請求方法代表不同的動作(主要的部分,具體還有api的格式)。
GET
用來獲取資源POST
用來新建資源PUT
用來更新資源DELETE
用來刪除資源。
只要API程序遵循了REST風格,那就可以稱其為RESTful API。目前在前后端分離的架構中,前后端基本都是通過RESTful API來進行交互。
func main() { r := gin.Default() r.GET("/book", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "GET", }) }) r.POST("/book", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "POST", }) }) r.PUT("/book", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "PUT", }) }) r.DELETE("/book", func(c *gin.Context) { c.JSON(200, gin.H{ "message": "DELETE", }) }) }
Gin渲染
HTML渲染
我們首先定義一個存放模板文件的templates文件,然后在其內部按照業務分別定義一個post文件和一個users文件夾。posts/index.html:
{{define "posts/index.html"}} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>posts/index</title> </head> <body> {{.title}} </body> </html> {{end}}
users/index.html
文件的內容如下:
{{define "users/index.html"}} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>users/index</title> </head> <body> {{.title}} </body> </html> {{end}}
Gin框架使用LoadHTMLGlob()或者LoadHTMLFiles() 方法進行HTML模板渲染。main.go代碼
func main() { r := gin.Default() r.LoadHTMLGlob("templates/**/*") //r.LoadHTMLFiles("templates/posts/index.html", "templates/users/index.html") r.GET("/posts/index", func(c *gin.Context) { c.HTML(http.StatusOK, "posts/index.html", gin.H{ "title": "我是posts/index", }) }) r.GET("users/index", func(c *gin.Context) { c.HTML(http.StatusOK, "users/index.html", gin.H{ "title": "我是users/index", }) }) r.Run(":8080") }
自定義模板函數
定義一個不轉義相應內容的safe
模板函數如下:
func main() { router := gin.Default() router.SetFuncMap(template.FuncMap{ "safe": func(str string) template.HTML{ return template.HTML(str) }, }) router.LoadHTMLFiles("templates/index.tmpl") router.GET("/index", func(c *gin.Context) { c.HTML(http.StatusOK, "index.tmpl", "<a href='https://www.baidu.com'>百度</a>") }) router.Run(":8080") }
templates/index.tmpl文件內容如下:
<!DOCTYPE html> <html lang="zh-CN"> <head> <title>修改模板引擎的標識符</title> </head> <body> <div>{{ . | safe }}</div> </body> </html>
靜態文件處理
當我們渲染的HTML文件中引用了靜態文件時,我們只需要按照以下方式在渲染頁面前調用gin.Static
方法即可。
func main() { r := gin.Default() r.Static("/static", "./static") r.LoadHTMLGlob("templates/**/*") // ... r.Run(":8080") }
使用模板繼承
Gin框架默認都是使用單模板,如果需要使用block template
功能,可以通過"github.com/gin-contrib/multitemplate"
庫實現。
獲取參數
獲取querystring參數
querystring
指的是URL中?
后面攜帶的參數,例如:/user/search?username=小王子&address=沙河
。 獲取請求的querystring參數的方法如下:
func main() { //Default返回一個默認的路由引擎 r := gin.Default() r.GET("/user/search", func(c *gin.Context) {
// 如果沒有則使用默認值 username := c.DefaultQuery("username", "小王子") //username := c.Query("username") address := c.Query("address") //輸出json結果給調用方 c.JSON(http.StatusOK, gin.H{ "message": "ok", "username": username, "address": address, }) }) r.Run() }
此時我們訪問:http://127.0.0.1:8080/user/search?username=wanglixing即可獲得相關參數
獲取form參數
請求的數據通過form表單來提交,例如向/user/search
發送一個POST請求,獲取請求數據的方式如下:
func main() { //Default返回一個默認的路由引擎 r := gin.Default() r.POST("/user/search", func(c *gin.Context) { // DefaultPostForm取不到值時會返回指定的默認值 //username := c.DefaultPostForm("username", "小王子") username := c.PostForm("username") address := c.PostForm("address") //輸出json結果給調用方 c.JSON(http.StatusOK, gin.H{ "message": "ok", "username": username, "address": address, }) }) r.Run(":8080") }
獲取path參數
請求的參數通過URL路徑傳遞,例如:/user/search/小王子/沙河
。 獲取請求URL路徑中的參數的方式如下
func main() { //Default返回一個默認的路由引擎 r := gin.Default() r.GET("/user/search/:username/:address", func(c *gin.Context) { username := c.Param("username") address := c.Param("address") //輸出json結果給調用方 c.JSON(http.StatusOK, gin.H{ "message": "ok", "username": username, "address": address, }) }) r.Run(":8080") }
參數綁定
為了能夠更方便的獲取請求相關參數,提高開發效率,我們可以基於請求的Content-Type
識別請求數據類型並利用反射機制自動提取請求中QueryString
、form表單
、JSON
、XML
等參數到結構體中。 下面的示例代碼演示了.ShouldBind()
強大的功能,它能夠基於請求自動提取JSON
、form表單
和QueryString
類型的數據,並把值綁定到指定的結構體對象。
// Binding from JSON type Login struct { User string `form:"user" json:"user" binding:"required"` Password string `form:"password" json:"password" binding:"required"` } func main() { router := gin.Default() // 綁定JSON的示例 ({"user": "q1mi", "password": "123456"}) router.POST("/loginJSON", func(c *gin.Context) { var login Login if err := c.ShouldBind(&login); err == nil { fmt.Printf("login info:%#v\n", login) c.JSON(http.StatusOK, gin.H{ "user": login.User, "password": login.Password, }) } else { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } }) // 綁定form表單示例 (user=q1mi&password=123456) router.POST("/loginForm", func(c *gin.Context) { var login Login // ShouldBind()會根據請求的Content-Type自行選擇綁定器 if err := c.ShouldBind(&login); err == nil { c.JSON(http.StatusOK, gin.H{ "user": login.User, "password": login.Password, }) } else { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } }) // 綁定QueryString示例 (/loginQuery?user=q1mi&password=123456) router.GET("/loginForm", func(c *gin.Context) { var login Login // ShouldBind()會根據請求的Content-Type自行選擇綁定器 if err := c.ShouldBind(&login); err == nil { c.JSON(http.StatusOK, gin.H{ "user": login.User, "password": login.Password, }) } else { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } }) // Listen and serve on 0.0.0.0:8080 router.Run(":8080") }
ShouldBind
會按照下面的順序解析請求中的數據完成綁定:
- 如果是
GET
請求,只使用Form
綁定引擎(query
)。 - 如果是
POST
請求,首先檢查content-type
是否為JSON
或XML
,然后再使用Form
(form-data
)。
文件上傳
單個文件上傳
文件上傳前端頁面代碼:注意form提交數據的格式
<!DOCTYPE html> <html lang="zh-CN"> <head> <title>上傳文件示例</title> </head> <body> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="f1"> <input type="submit" value="上傳"> </form> </body> </html>
后端gin框架部分代碼:
func main() { router := gin.Default() // 處理multipart forms提交文件時默認的內存限制是32 MiB // 可以通過下面的方式修改 // router.MaxMultipartMemory = 8 << 20 // 8 MiB router.POST("/upload", func(c *gin.Context) { // 單個文件 file, err := c.FormFile("f1") if err != nil { c.JSON(http.StatusInternalServerError, gin.H{ "message": err.Error(), }) return } log.Println(file.Filename) dst := fmt.Sprintf("C:/tmp/%s", file.Filename) // 上傳文件到指定的目錄 c.SaveUploadedFile(file, dst) c.JSON(http.StatusOK, gin.H{ "message": fmt.Sprintf("'%s' uploaded!", file.Filename), }) }) router.Run() }
多個文件上傳時,后端代碼
func main() { router := gin.Default() // 處理multipart forms提交文件時默認的內存限制是32 MiB // 可以通過下面的方式修改 // router.MaxMultipartMemory = 8 << 20 // 8 MiB router.POST("/upload", func(c *gin.Context) { // Multipart form form, _ := c.MultipartForm() files := form.File["file"] for index, file := range files { log.Println(file.Filename) dst := fmt.Sprintf("C:/tmp/%s_%d", file.Filename, index) // 上傳文件到指定的目錄 c.SaveUploadedFile(file, dst) } c.JSON(http.StatusOK, gin.H{ "message": fmt.Sprintf("%d files uploaded!", len(files)), }) }) router.Run() }
重定向
路由重定向,使用HandleContext
:
r.GET("/test", func(c *gin.Context) { // 指定重定向的URL c.Request.URL.Path = "/test2" r.HandleContext(c) }) r.GET("/test2", func(c *gin.Context) { c.JSON(http.StatusOK, gin.H{"hello": "world"}) })
Gin路由
普通路由
r.GET("/index", func(c *gin.Context) {...}) r.GET("/login", func(c *gin.Context) {...}) r.POST("/login", func(c *gin.Context) {...})
此外,還有一個可以匹配所有請求方法的Any
方法如下:
r.Any("/test", func(c *gin.Context) {...})
為沒有配置處理函數的路由添加處理程序,默認情況下它返回404代碼,下面的代碼為沒有匹配到路由的請求都返回views/404.html
頁面。
r.NoRoute(func(c *gin.Context) { c.HTML(http.StatusNotFound, "views/404.html", nil) })
路由組
我們可以將擁有共同URL前綴的路由划分為一個路由組。習慣性一對{}
包裹同組的路由,這只是為了看着清晰,你用不用{}
包裹功能上沒什么區別。
func main() { r := gin.Default() userGroup := r.Group("/user") { userGroup.GET("/index", func(c *gin.Context) {...}) userGroup.GET("/login", func(c *gin.Context) {...}) userGroup.POST("/login", func(c *gin.Context) {...}) } shopGroup := r.Group("/shop") { shopGroup.GET("/index", func(c *gin.Context) {...}) shopGroup.GET("/cart", func(c *gin.Context) {...}) shopGroup.POST("/checkout", func(c *gin.Context) {...}) } r.Run() }
路由組也是支持嵌套的,例如:
shopGroup := r.Group("/shop") { shopGroup.GET("/index", func(c *gin.Context) {...}) shopGroup.GET("/cart", func(c *gin.Context) {...}) shopGroup.POST("/checkout", func(c *gin.Context) {...}) // 嵌套路由組 xx := shopGroup.Group("xx") xx.GET("/oo", func(c *gin.Context) {...}) } // 通常我們將路由分組用在划分業務邏輯或划分API版本時。
路由原理:Gin框架中的路由使用的是httprouter這個庫。其基本原理就是構造一個路由地址的前綴樹。
Gin中間件
Gin框架允許開發者在處理請求的過程中,加入用戶自己的鈎子(Hook)函數。這個鈎子函數就叫中間件,中間件適合處理一些公共的業務邏輯,比如登錄認證、權限校驗、數據分頁、記錄日志、耗時統計等。
定義中間件
Gin中的中間件必須是一個gin.HandlerFunc
類型。例如我們像下面的代碼一樣定義一個統計請求耗時的中間件。
// StatCost 是一個統計耗時請求耗時的中間件 func StatCost() gin.HandlerFunc { return func(c *gin.Context) { start := time.Now() c.Set("name", "小王子") // 可以通過c.Set在請求上下文中設置值,后續的處理函數能夠取到該值 // 調用該請求的剩余處理程序 c.Next() // 不調用該請求的剩余處理程序 // c.Abort() // 計算耗時 cost := time.Since(start) log.Println(cost) } }
注冊中間件
在gin框架中,我們可以為每個路由添加任意數量的中間件。
為全局路由注冊:
func main() { // 新建一個沒有任何默認中間件的路由 r := gin.New() // 注冊一個全局中間件 r.Use(StatCost()) r.GET("/test", func(c *gin.Context) { name := c.MustGet("name").(string) // 從上下文取值 log.Println(name) c.JSON(http.StatusOK, gin.H{ "message": "Hello world!", }) }) r.Run() }
為某個路由單獨注冊:
// 給/test2路由單獨注冊中間件(可注冊多個) r.GET("/test2", StatCost(), func(c *gin.Context) { name := c.MustGet("name").(string) // 從上下文取值 log.Println(name) c.JSON(http.StatusOK, gin.H{ "message": "Hello world!", }) })
為路由組注冊中間件:
// 寫法一 shopGroup := r.Group("/shop", StatCost()) { shopGroup.GET("/index", func(c *gin.Context) {...}) ... } //寫法二 shopGroup := r.Group("/shop") shopGroup.Use(StatCost()) { shopGroup.GET("/index", func(c *gin.Context) {...}) ... }
中間件注意事項
gin默認中間件
gin.Default()
默認使用了Logger
和Recovery
中間件,其中:
Logger
中間件將日志寫入gin.DefaultWriter
,即使配置了GIN_MODE=release
。Recovery
中間件會recover任何panic
。如果有panic的話,會寫入500響應碼。
如果不想使用上面兩個默認的中間件,可以使用gin.New()
新建一個沒有任何默認中間件的路由。
gin中間件中使用goroutine
當在中間件或handler
中啟動新的goroutine
時,不能使用原始的上下文(c *gin.Context),必須使用其只讀副本(c.Copy()
)。
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, } // 借助errgroup.Group或者自行開啟兩個goroutine分別啟動兩個服務 g.Go(func() error { return server01.ListenAndServe() }) g.Go(func() error { return server02.ListenAndServe() }) if err := g.Wait(); err != nil { log.Fatal(err) } }
參考文檔:https://www.liwenzhou.com/posts/Go/Gin_framework/