【go語言學習】web開發框架gin

一、gin簡介

Gin 是一個用 Go (Golang) 編寫的 HTTP web 框架。 它是一個類似于 martini 但擁有更好性能的 API 框架,由于 httprouter,速度提高了近 40 倍,是最快的 http 路由器和框架。 如果你是性能和高效的追求者,你會愛上 Gin。

二、gin安裝和使用

安裝

  1. 下載并安裝 gin:
$ go get -u github.com/gin-gonic/gin

2、將gin引入到項目中:

import "github.com/gin-gonic/gin"

3、如果使用諸如 http.StatusOK 之類的常量,則需要引入 net/http 包:

import "net/http"

使用

// main.go
package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    // 創建一個默認的路由引擎
    r := gin.Default()
    // 當客戶端以GET方法請求/路徑時,會執行后面的匿名函數
    r.GET("/", func(c *gin.Context) {
        // 返回json格式的數據
        c.JSON(http.StatusOK, gin.H{
            "message": "hello world",
        })
    })
    // 監聽并在 0.0.0.0:8080 上啟動服務
    r.Run()
}

然后,執行 go run main.go 命令來運行代碼,并且在瀏覽器中訪問 0.0.0.0:8080/,頁面顯示:

{"message":"hello world"}

三、RESTful API

REST與技術無關,代表的是一種軟件架構風格,REST是Representational State Transfer的簡稱,中文翻譯為“表征狀態轉移”或“表現層狀態轉化”。

簡單來說,REST的含義就是客戶端與Web服務器之間進行交互的時候,使用HTTP協議中的4個請求方法代表不同的動作。

  • GET用來獲取資源
  • POST用來新建資源
  • PUT用來更新資源
  • DELETE用來刪除資源。

只要API程序遵循了REST風格,那就可以稱其為RESTful API。目前在前后端分離的架構中,前后端基本都是通過RESTful API來進行交互。

例如,我們現在要編寫一個管理書籍的系統,我們可以查詢對一本書進行查詢、創建、更新和刪除等操作,我們在編寫程序的時候就要設計客戶端瀏覽器與我們Web服務端交互的方式和路徑。按照經驗我們通常會設計成如下模式:

請求方法 URL 動作
GET /book 查詢書籍
POST /create_book 添加書籍
POST /update_book 更新書籍
POST /delete_book 刪除書籍

同樣的需求我們按照RESTful API設計如下:

請求方法 URL 動作
GET /book 查詢書籍
POST /book 添加書籍
PUT /book 更新書籍
DELETE /book 刪除書籍

示例代碼:

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()
    r.GET("/book", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message": "GET",
        })
    })
    r.POST("/book", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message": "POST",
        })
    })
    r.PUT("/book", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message": "PUT",
        })
    })
    r.DELETE("/book", func(c *gin.Context) {
        c.JSON(http.StatusOK, gin.H{
            "message": "DELETE",
        })
    })
    r.Run()
}

四、HTML渲染

1、模板解析與渲染

使用 LoadHTMLGlob () 或者 LoadHTMLFiles ()

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    r := gin.Default()
    // r.LoadHTMLFiles("templates/posts/index.tmpl", "templates/users/index.tmpl")
    r.LoadHTMLGlob("templates/**/*")
    r.GET("/posts/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "posts/index.tmpl", gin.H{
            "tittle": "posts",
        })
    })
    r.GET("/users/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "users/index.tmpl", gin.H{
            "tittle": "users",
        })
    })
    r.Run()
}

templates/posts/index.tmpl

{{ define "posts/index.tmpl" }}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    {{ .tittle }}
</body>
</html>
{{ end }}

templates/users/index.tmpl

{{ define "users/index.tmpl" }}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    {{ .tittle }}
</body>
</html>
{{ end }}
2、自定義分隔符
r.Delims("{[", "]}")
3、自定義模板函數
package main

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 now() string {
    year, month, day := time.Now().Date()
    return fmt.Sprintf("%d年%02d月%02d日", year, month, day)
}
func main() {
    r := gin.Default()
    r.SetFuncMap(template.FuncMap{
        "formatAsDate": formatAsDate,
        "now":          now,
    })
    r.LoadHTMLFiles("index.tmpl")
    r.GET("/", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", gin.H{
            "now": time.Now(),
        })
    })
    r.Run()
}
4、靜態文件處理
package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()
    router.Static("/statics", "./statics/")
    router.LoadHTMLFiles("index.tmpl")
    router.GET("/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", nil)
    })
    router.Run()
}
<!-- index.tmpl -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="/statics/css/main.css">
    <title>Document</title>
</head>
<body>
    <h2>hello world</h2>
    <img src="/statics/pictures/10.jpg" alt="">
    <script src="/statics/js/main.js"></script>
</body>
</html>

五、獲取參數

Gin框架將處理HTTP請求參數以及如何響應等操作都封裝到了gin.Conetxt結構體,并為gin.Context提供了非常多的方法,因此了解gin.Context的結構定義與方法,對使用Gin框架編寫Web項目非常重要。

// gin.Context
type Context struct {
    Request *http.Request
    Writer  ResponseWriter
    Params Params
    // Keys is a key/value pair exclusively for the context of each request.
    Keys map[string]interface{}
    // Errors is a list of errors attached to all the handlers/middlewares who used this context.
    Errors errorMsgs
    // Accepted defines a list of manually accepted formats for content negotiation.
    Accepted []string
    // contains filtered or unexported fields
}

從上面的gin.Context的結構定義來看,gin.Context封裝了http.Request和http.ResponseWriter。

1、獲取路徑中的參數(path)

path是指請求的url中域名之后從/開始的部分,如訪問web地址:https://localhost:8080/user/jack/user/jack部分便是path,可以使用gin.Context中提供的方法獲取這部分參數。

獲取路徑中的參數有兩種方法:

  • 使用gin.Context的中Param()方法獲取path中的參數
  • 使用gin.Context中的Params字段獲取path中的參數
func (c *Context) Param(key string) string {}
type Params []Param
func (ps Params) ByName(name string) (va string) {}
func (ps Params) Get(name string) (string, bool) {}

示例代碼:

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()

    // 此規則能夠匹配/user/john這種格式,但不能匹配/user/ 或 /user這種格式
    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,它將重定向到/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.GET("/user/:id", func(c *gin.Context) {
        id, _ := c.Params.Get("id")
        // id := c.Params.ByName("id")
        c.JOSN(http.StatusOK, gin.H{
            "id": id,
        })
    })
    router.Run()
}
2、獲取get請求參數(query)

query是指url請求地址中的問號后面的部,稱為查詢參數。如https://localhost:8080/index?name=jack&id=100name=jack&id=100就是查詢參數。

gin.Context提供了以下幾個方法,用于獲取Query部分的參數:

  • 獲取單個參數
func (c *Context) GetQuery(key string) (string, bool) {}
func (c *Context) Query(key string) string {}
func (c *Context) DefaultQuery(key, defaultValue string) string {}

上面三個方法用于獲取單個數值,GetQuery比Query多返回一個error類型的參數,實際上Query方法只是封裝了GetQuery方法,并忽略GetQuery方法返回的錯誤而已,而DefaultQuery方法則在沒有獲取相應參數值的返回一個默認值。

  • 獲取數組
func (c *Context) GetQueryArray(key string) ([]string, bool) {}
func (c *Context) QueryArray(key string) []string {}
  • 獲取map
func (c *Context) QueryMap(key string) map[string]string {}
func (c *Context) GetQueryMap(key string) (map[string]string, bool) {}

示例代碼:

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()
    router.GET("/index", func(c *gin.Context) {
        // name, _ := c.GetQuery("name")
        name := c.Query("name")
        id := c.DefaultQuery("id", "0000")
        c.String(http.StatusOK, "Hello, name:%s, id:%v", name, id)
    })
    router.GET("/user", func(c *gin.Context) {
        // ids, _ := c.GetQueryArray("id")
        ids := c.QueryArray("id")
        c.JSON(http.StatusOK, gin.H{
            "ids": ids,
        })
    })
    router.GET("/article", func(c *gin.Context) {
        article := c.QueryMap("articles")
        c.JSON(http.StatusOK, article)
    })
    router.Run()
}

請求:http://localhost:8080/index?name=jack&id=100
響應:Hello, name:jack, id:100
請求:http://localhost:8080/user?id=10&id=20&id=40
響應:{"ids":["10","20","40"]}
請求:http://localhost:8080/article?articles[tittle]=golang
響應:{"tittle":"golang"}

3、獲取post請求參數(body)

一般HTTP的Post請求參數都是通過body部分傳給服務器端的,尤其是數據量大或安全性要求較高的數據,如登錄功能中的賬號密碼等參數。

gin.Context提供了以下四個方法讓我們獲取body中的數據,不過要說明的是,下面的四個方法,只能獲取Content-type是application/x-www-form-urlencoded或multipart/form-data時body中的數據。

示例代碼:

func (c *Context) PostForm(key string) string {}
func (c *Context) PostFormArray(key string) []string {}
func (c *Context) PostFormMap(key string) map[string]string {}
func (c *Context) DefaultPostForm(key, defaultValue string) string {}
func (c *Context) GetPostForm(key string) (string, bool) {}
func (c *Context) GetPostFormArray(key string) ([]string, bool) {}
func (c *Context) GetPostFormMap(key string) (map[string]string, bool) {}
func (c *Context) GetRawData() ([]byte, error) {}
package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()
    router.LoadHTMLFiles("index.tmpl")
    router.GET("/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", nil)
    })
    router.POST("/index", func(c *gin.Context) {
        username := c.PostForm("username")
        password := c.PostForm("password")
        gender := c.DefaultPostForm("gender", "male")
        c.JSON(http.StatusOK, gin.H{
            "username": username,
            "password": password,
            "gender":   gender,
        })
    })
    router.Run()
}
<!-- index.tmpl -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="/index", method="POST">
        <input type="text", name="username"><br>
        <input type="password", name="password"><br>
        <input type="radio", name="gender" value="male">male
        <input type="radio", name="gender" value="female">female <br>
        <input type="submit" value="提交">
    </form>
</body>
</html>

六、數據綁定

我們直接使用gin.Context提供的方法獲取請求中通過path、query、body帶上來的參數,但使用前面的那些方法,并不能處理請求中比較復雜的數據結構,比如Content-type為application/json或application/xml時,其所帶上的數據會很復雜,因此我們需要使用另外一種方法獲取這些數據,這種方式叫數據綁定。

Gin框架將數據綁定的操作都封裝在gin/binding這個包中,下面是gin/binding包定義的常量,說明gin/binding包所支持的Content-type格式。

const (
    MIMEJSON              = "application/json"
    MIMEHTML              = "text/html"
    MIMEXML               = "application/xml"
    MIMEXML2              = "text/xml"
    MIMEPlain             = "text/plain"
    MIMEPOSTForm          = "application/x-www-form-urlencoded"
    MIMEMultipartPOSTForm = "multipart/form-data"
    MIMEPROTOBUF          = "application/x-protobuf"
    MIMEMSGPACK           = "application/x-msgpack"
    MIMEMSGPACK2          = "application/msgpack"
    MIMEYAML              = "application/x-yaml"
)

gin.binding包也定義處理不同Content-type提交數據的處理結構體,并以變量的形式讓其他包可以訪問,如下:

var (
    JSON          = jsonBinding{}
    XML           = xmlBinding{}
    Form          = formBinding{}
    Query         = queryBinding{}
    FormPost      = formPostBinding{}
    FormMultipart = formMultipartBinding{}
    ProtoBuf      = protobufBinding{}
    MsgPack       = msgpackBinding{}
    YAML          = yamlBinding{}
    Uri           = uriBinding{}
)

但實際上,我們并不需要調用gin/binding包的代碼來完成數據綁定的功能,因為gin.Context中已經在gin.Context的基礎上封裝了許多更加快捷的方法供我們使用,gin提供了兩套綁定方法:

  • Must bind
    Methods方法:Bind, BindJSON, BindXML, BindQuery, BindYAML
    Behavior行為:這些方法底層使用 MustBindWith,如果存在綁定錯誤,請求將被中止,返回http狀態為400的響應給客戶端。

  • Should bind
    Methods方法:ShouldBind, ShouldBindJSON, ShouldBindXML, ShouldBindQuery, ShouldBindYAML
    Behavior行為:這些方法底層使用 ShouldBindWith,如果存在綁定錯誤,則返回錯誤,開發人員可以正確處理請求和錯誤。

1、以Bind為前綴的系列方法
  • Path
func (c *Context) BindUri(obj interface{}) error {}
  • Query
func (c *Context) BindQuery(obj interface{}) error {}
  • Body

當我們在HTTP請求中Body設置不同數據格式,需要設置相應頭部Content-Type的值,比較常用的為json、xml、yaml,gin.Context提供下面三個方法綁定對應Content-type時body中的數據。

func (c *Context) BindJSON(obj interface{}) error {}
func (c *Context) BindXML(obj interface{}) error {]
func (c *Context) BindYAML(obj interface{}) error {}

除了上面三個方法外,更常用的Bind()方法,Bind()方法會自動根據Content-Type的值選擇不同的綁定類型。

func (c *Context) Bind(obj interface{}) error {}

上面幾個方法都是獲取固定Content-type或自動根據Content-type選擇綁定類型,我們也可以使用下面兩個方法自行選擇綁定類型。

// 第二個參數值是gin.binding中定義好的常量
func (c *Context) BindWith(obj interface{}, b binding.Binding) error {}
func (c *Context) MustBindWith(obj interface{}, b binding.Binding) error {}
2、以ShouldBind為前綴的系列方法
  • Path
func (c *Context) ShouldBindUri(obj interface{}) error {}
  • Query
func (c *Context) ShouldBindQuery(obj interface{}) error {}
  • Body
func (c *Context) ShouldBind(obj interface{}) error {}
func (c *Context) ShouldBindJSON(obj interface{}) error {}
func (c *Context) ShouldBindXML(obj interface{}) error {}
func (c *Context) ShouldBindYAML(obj interface{}) error {}
func (c *Context) ShouldBindBodyWith(obj interface{}, bb  binding.BindingBody) (err error) {}
func (c *Context) ShouldBindWith(obj interface{}, b binding.Binding) error {}

示例代碼:

// main.go
package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

// User 結構體
type User struct {
    Username string   `form:"username" json:"username" uri:"username" binding:"required"`
    Passwrod string   `form:"password" json:"password" uri:"password" binding:"required"`
    Hobbys   []string `form:"hobbys" json:"bobbys" uri:"hobbys" binding:"required"`
}

func main() {
    router := gin.Default()
    router.LoadHTMLFiles("register.tmpl")
    // Path
    router.GET("/user/:username/:password", func(c *gin.Context) {
        var user User
        c.ShouldBindUri(&user)
        c.JSON(http.StatusOK, user)
    })
    // Query
    router.GET("/index", func(c *gin.Context) {
        var user User
        c.ShouldBind(&user)
        c.JSON(http.StatusOK, user)
    })
    // Body
    router.GET("/register", func(c *gin.Context) {
        c.HTML(http.StatusOK, "register.tmpl", nil)
    })
    router.POST("/register", func(c *gin.Context) {
        var user User
        c.ShouldBind(&user)
        c.JSON(http.StatusOK, user)
    })
    router.Run()
}
<!-- register.tmpl -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form action="/register" method="POST", enctype="multipart/form-data">
        username: <input type="text" name="username"><br>
        <p></p>
        password: <input type="password" name="password"><br>
        <p></p>
        hobbys: <input type="checkbox" name="hobbys" value="football">football
        <input type="checkbox" name="hobbys" value="basketball">basketball
        <input type="checkbox" name="hobbys" value="volleyball">volleyball<br>
        <p></p>
        <input type="submit" value="register">
    </form> 
</body>
</html>

請求:http://localhost:8080/user/jack/123456
響應:{"username":"jack","password":"123456","bobbys":null}
請求:http://localhost:8080/index?username=jack&password=123456
響應:{"username":"jack","password":"123456","bobbys":null}
請求:http://localhost:8080/register 輸入username和password、hobbys,提交
響應:{"username":"jack","password":"123456","bobbys":["football","basketball"]}

七、文件上傳

1、單文件上傳
package main

import (
    "fmt"
    "math/rand"
    "net/http"
    "path/filepath"
    "time"

    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()
    router.LoadHTMLFiles("index.tmpl")
    router.GET("/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", nil)
    })
    router.POST("/upload", func(c *gin.Context) {
        file, _ := c.FormFile("file")
        rand.Seed(time.Now().UnixNano())
        fileName := fmt.Sprintf("%d%d%s", time.Now().Unix(), rand.Intn(99999-10000)+10000, filepath.Ext(file.Filename))
        dst := "./upload/" + fileName
        fmt.Println(dst)
        c.SaveUploadedFile(file, dst)
        c.JSON(http.StatusOK, gin.H{
            "message":  "uploaded",
            "fileName": fileName,
        })
    })
    router.Run()
}
2、多文件上傳
package main

import (
    "fmt"
    "math/rand"
    "net/http"
    "path/filepath"
    "time"

    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()
    router.LoadHTMLFiles("index.tmpl")
    router.GET("/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.tmpl", nil)
    })
    router.POST("/upload", func(c *gin.Context) {
        form, _ := c.MultipartForm()
        files := form.File["file"]
        fmt.Println(files)
        rand.Seed(time.Now().UnixNano())
        for _, file := range files {
            fileName := fmt.Sprintf("%d%d%s", time.Now().Unix(), rand.Intn(99999-10000)+10000, filepath.Ext(file.Filename))
            dst := "./upload/" + fileName
            fmt.Println(dst)
            c.SaveUploadedFile(file, dst)
        }
        c.JSON(http.StatusOK, gin.H{
            "message": "uploaded",
            "file":    files,
        })
    })
    router.Run()
}

八、重定向

package main

import (
    "net/http"

    "github.com/gin-gonic/gin"
)

func main() {
    router := gin.Default()
    // 外部鏈接重定向
    router.GET("/index", func(c *gin.Context) {
        c.Redirect(http.StatusMovedPermanently, "http://www.baidu.com")
    })
    // 內部路由重定向
    router.GET("/home", func(c *gin.Context) {
        c.Request.URL.Path = "/"
        router.HandleContext(c)
    })
    router.GET("/", func(c *gin.Context) {
        c.String(http.StatusOK, "hello world")
    })
    router.Run()
}

九、gin路由

1、普通路由
router.GET("/index", func(c *gin.Context) {...})
router.GET("/login", func(c *gin.Context) {...})
router.POST("/login", func(c *gin.Context) {...})

還有一個可以匹配所有請求方法的Any方法如下:

router.Any("/test", func(c *gin.Context) {...})

為沒有配置處理函數的路由添加處理程序,默認情況下它返回404代碼,下面的代碼為沒有匹配到路由的請求都返回views/404.html頁面。

router.NoRoute(func(c *gin.Context) {
    c.HTML(http.StatusNotFound, "views/404.html", nil)
})
2、路由組

我們可以將擁有共同URL前綴的路由劃分為一個路由組。習慣性一對{}包裹同組的路由,這只是為了看著清晰,你用不用{}包裹功能上沒什么區別。

func main() {
    router := gin.Default()
    userGroup := router.Group("/user")
    {
        userGroup.GET("/index", func(c *gin.Context) {...})
        userGroup.GET("/login", func(c *gin.Context) {...})
        userGroup.POST("/login", func(c *gin.Context) {...})

    }
    shopGroup := router.Group("/shop")
    {
        shopGroup.GET("/index", func(c *gin.Context) {...})
        shopGroup.GET("/cart", func(c *gin.Context) {...})
        shopGroup.POST("/checkout", func(c *gin.Context) {...})
    }
    router.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) {...})
    }

十、gin中間件

Gin框架允許開發者在處理請求的過程中,加入用戶自己的鉤子(Hook)函數。這個鉤子函數就叫中間件,中間件適合處理一些公共的業務邏輯,比如登錄認證、權限校驗、數據分頁、記錄日志、耗時統計等。簡單來說,Gin中間件的作用有兩個:

  • Web請求到到達我們定義的HTTP請求處理方法之前,攔截請求并進行相應處理(比如:權限驗證,數據過濾等),這個可以類比為 前置攔截器 或 前置過濾器 ,

  • 在我們處理完成請求并響應客戶端時,攔截響應并進行相應的處理(比如:添加統一響應部頭或數據格式等),這可以類型為 后置攔截器 或 后置過濾器 。

1、內置中間件

Gin內置一些中間件,我們可以直接使用,下面是內置中間件列表:

func BasicAuth(accounts Accounts) HandlerFunc {}
func BasicAuthForRealm(accounts Accounts, realm string) HandlerFunc {}
func Bind(val interface{}) HandlerFunc {} //攔截請求參數并進行綁定
func ErrorLogger() HandlerFunc {}       //錯誤日志處理
func ErrorLoggerT(typ ErrorType) HandlerFunc {} //自定義類型的錯誤日志處理
func Logger() HandlerFunc {} //日志記錄
func LoggerWithConfig(conf LoggerConfig) HandlerFunc {}
func LoggerWithFormatter(f LogFormatter) HandlerFunc {}
func LoggerWithWriter(out io.Writer, notlogged ...string) HandlerFunc {}
func Recovery() HandlerFunc {}
func RecoveryWithWriter(out io.Writer) HandlerFunc {}
func WrapF(f http.HandlerFunc) HandlerFunc {} //將http.HandlerFunc包裝成中間件
func WrapH(h http.Handler) HandlerFunc {} //將http.Handler包裝成中間件
2、自定義中間件

Gin中的中間件必須是一個gin.HandlerFunc類型。

// gin
type HandlerFunc func(*Context)

(1)定義一個gin.HandleFunc類型的函數作為中間件:

示例代碼:

package main

import (
    "fmt"
    "net/http"
    "time"

    "github.com/gin-gonic/gin"
)

// StatCost 是一個計算耗時的中間件
func StatCost(c *gin.Context) {
    // 傳遞數據
    c.Set("name", "jack")
    start := time.Now()
    // 調用該請求的剩余處理程序
    c.Next()
    // 不調用該請求的剩余處理程序
    // c.Abort()
    // 計算耗時
    cost := time.Since(start)
    fmt.Println(cost)
}

func main() {
    router := gin.Default()
    // 為/路由注冊中間件StatCost
    router.GET("/", StatCost, func(c *gin.Context) {
        // 獲取中間件傳遞的數據
        name := c.MustGet("name").(string)
        c.JSON(http.StatusOK, gin.H{
            "name": name,
        })
    })
    router.Run()
}

(2)通過自定義方法,返回一個中間件函數,這是Gin框架中更常用的方式:

示例代碼:

//定義一個返回中間件的方法
func MyMiddleware(){
    //自定義邏輯
    
    //返回中間件
    return func(c *gin.Context){
        //中間件邏輯
    }
}
3、注冊中間件

在gin框架中,我們可以為每個路由添加任意數量的中間件。

  • 全局使用中間件

直拉使用 gin.Engine 結構體的 Use() 方法便可以在所有請求應用中間件,這樣做,中間件便會在全局起作用。

router.Use(gin.Recovery())//在全局使用內置中間件
  • 為某個路由單獨注冊

單個請求路由,也可以應用中間件,如下:

router := gin.New()
router.GET("/test",gin.Recovery(),gin.Logger(),func(c *gin.Context){
    c.JSON(200,"test")
})
  • 為路由組注冊中間件

根據業務不同劃分不同 路由分組(RouterGroup ),不同的路由分組再應用不同的中間件,這樣就達到了不同的請求由不同的中間件進行攔截處理。

為路由組注冊中間件有以下兩種寫法。

routerGroup := router.Group("/", MyMiddleware)
{
    routerGroup.GET("/user", func(c *gin.Context){})
    routerGroup.POST("/user", func(c *gin.Context){})
    ...
}
routerGroup := router.Group("/")
routerGroup.Use(MyMiddleware)
{
    routerGroup.GET("/user", func(c *gin.Context){})
    routerGroup.POST("/user", func(c *gin.Context){})
    ...
}
4、中間件使用

(1)gin默認中間件

gin.Default()默認使用了Logger和Recovery中間件,其中:

Logger中間件將日志寫入gin.DefaultWriter,即使配置了GIN_MODE=release。
Recovery中間件會recover任何panic。如果有panic的話,會寫入500響應碼。
如果不想使用上面兩個默認的中間件,可以使用gin.New()新建一個沒有任何默認中間件的路由。

(2)數據傳遞

當我們在中間件攔截并預先處理好數據之后,要如何將數據傳遞我們定義的處理請求的HTTP方法呢?可以使用 gin.Context 中的 Set() 方法,其定義如下, Set() 通過一個key來存儲作何類型的數據,方便下一層處理方法獲取。

func (c *Context) Set(key string, value interface{})

當我們在中間件中通過Set方法設置一些數值,在下一層中間件或HTTP請求處理方法中,可以使用下面列出的方法通過key獲取對應數據。

其中,gin.Context的Get方法返回 interface{} ,通過返回exists可以判斷key是否存在。

func (c *Context) Get(key string) (value interface{}, exists bool)

當我們確定通過Set方法設置對應數據類型的值時,可以使用下面方法獲取應數據類型的值。

func (c *Context) GetBool(key string) (b bool)
func (c *Context) GetDuration(key string) (d time.Duration)
func (c *Context) GetFloat64(key string) (f64 float64)
func (c *Context) GetInt(key string) (i int)
func (c *Context) GetInt64(key string) (i64 int64)
func (c *Context) GetString(key string) (s string)
func (c *Context) GetStringMap(key string) (sm map[string]interface{})
func (c *Context) GetStringMapString(key string) (sms map[string]string)
func (c *Context) GetStringMapStringSlice(key string) (smss map[string][]string)
func (c *Context) GetStringSlice(key string) (ss []string)
func (c *Context) GetTime(key string) (t time.Time)

(3)攔截請求與后置攔截

  • 攔截請求

中間件的最大作用就是攔截過濾請求,比如我們有些請求需要用戶登錄或者需要特定權限才能訪問,這時候便可以中間件中做過濾攔截,當用戶請求不合法時,可以使用下面列出的 gin.Context 的幾個方法中斷用戶請求:

下面三個方法中斷請求后,直接返回200,但響應的body中不會有數據。

func (c *Context) Abort()
func (c *Context) AbortWithError(code int, err error) *Error
func (c *Context) AbortWithStatus(code int)

使用AbortWithStatusJSON()方法,中斷用戶請求后,則可以返回 json格式的數據.

func (c *Context) AbortWithStatusJSON(code int, jsonObj interface{})
  • 后置攔截

前面我們講的都是到達我們定義的HTTP處理方法前進行攔截,其實,如果在中間件中調用 gin.Context 的 Next() 方法,則可以請求到達并完成業務處理后,再經過中間件后置攔截處理, Next() 方法定義如下:

func (c *Context) Next()

在中間件調用 Next() 方法, Next() 方法之前的代碼會在到達請求方法前執行, Next() 方法之后的代碼則在請求方法處理后執行:

func MyMiddleware(c *gin.Context){
    //請求前
    c.Next()
    //請求后
}

(4)gin中間件中使用goroutine

當在中間件或handler中啟動新的goroutine時,不能使用原始的上下文(c *gin.Context),必須使用其只讀副本(c.Copy())。

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,923評論 6 535
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,740評論 3 420
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,856評論 0 380
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,175評論 1 315
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,931評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,321評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,383評論 3 443
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,533評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,082評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,891評論 3 356
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,067評論 1 371
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,618評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,319評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,732評論 0 27
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,987評論 1 289
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,794評論 3 394
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,076評論 2 375