1. 程式人生 > 其它 >Gin框架系列之資料繫結

Gin框架系列之資料繫結

一、問題引出

如果通過前端向後端傳遞資料,你可能會這樣進行接收:

1、前臺

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/do_index" method="post">
    使用者名稱:<input type="text" name="username"> <br>
    密  碼:
<input type="password" name="password"> <br> <input type="submit"> </form> </body> </html>

顯然,前臺提交了一個form表單到後臺。

2、後臺

...
func DoIndex(ctx *gin.Context) {
    username := ctx.PostForm("username")
    password := ctx.PostForm("password")
    fmt.Printf("username:%s,pasword:%s", username, password)
    ctx.String(http.StatusOK, 
"submit success!") } ...

可以看到後臺通過ctx.PostForm方式逐一獲取所有的引數值,那麼有沒有一種簡單方式來解決這個問題,這就是我們所說的通過資料繫結的方式。

二、資料繫結引入

Gin提供了兩種型別的繫結:

  • MustBind
  • ShouldBind

1、ShouldBind

它包含多種方法,如:ShouldBind,ShouldBindJSON,ShouldBindXML,ShouldBindQuery,ShouldBindYAML。這些方法屬於ShouldBindWith的具體呼叫, 如果發生繫結錯誤,Gin 會返回錯誤並由開發者處理錯誤和請求。

ShouldBind可以繫結Form、QueryString、Json,uri

  • 前臺
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/do_bind_index" method="post">
    使用者名稱:<input type="text" name="username"> <br>
    密  碼:<input type="password" name="password"> <br>
    <input type="submit">
</form>
</body>
</html>
  • 後臺
package main

import (
    "fmt"
    "github.com/gin-gonic/gin"
    "net/http"
)

type LoginInfo struct {
    UserName string `form:"username" json:"username"`
    PassWord string `form:"password" json:"password"`
}

func BindIndex(ctx *gin.Context) {

    ctx.HTML(http.StatusOK, "bind_index.html", nil)

}

func DoBindIndex(ctx *gin.Context) {
     // 將form表單欄位繫結到結構體上
    var loginInfo LoginInfo
    _ = ctx.ShouldBind(&loginInfo)
    fmt.Printf("UserName:%s,PassWord:%s", loginInfo.UserName, loginInfo.PassWord)
    ctx.String(http.StatusOK, "submit success!")
}

func main() {

    router := gin.Default()

    router.LoadHTMLGlob("template/*")

    // 資料繫結
    router.GET("/bind_index", BindIndex)
    router.POST("/do_bind_index", DoBindIndex)

    router.Run(":8080")
}

2、MustBind

可以繫結Form、QueryString、Json等,與ShouldBind的區別在於,ShouldBind沒有繫結成功不報錯,就是空值,MustBind會報錯。