天天看點

Gin架構資料綁定和資料驗證的使用方法

作者:GoGoer

Gin是一種基于Go語言的輕量級Web架構,它提供了一種簡單、快速的方法來建構高性能的Web應用程式。其中一個重要的特性就是資料綁定,它可以将請求中的資料綁定到Go結構體中,進而友善處理和驗證請求資料。

以JSON資料綁定為例,當用戶端發送JSON格式的請求資料時,我們可以使用Gin的BindJSON方法将請求資料綁定到Go結構體中。具體代碼如下:

前端代碼:

{{define "user/bind_json.html"}}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>JSON資料綁定</title>
    <script src="/static/js/jquery.min.js"></script>
</head>
<body>
    <form action="">
        <input type="text" id="name">
        <input type="password" id="password">
        <input type="button" id="btn_add" value="送出">
    </form>
    <script>
        var btn_add = document.getElementById("btn_add");
        btn_add.onclick = function(){
            var name = document.getElementById("name").value;
            var password = document.getElementById("password").value;
            $.ajax({
                url:"/bind_json_user",
                type:"POST",
                data:JSON.stringify({
                    "name":name,
                    "password":password,
                }),
                dataType:"json",
                contentType:"application/json",
                success:function(data){
                    alert(data["status"]);
                    alert(data["msg"]);
                },
                fail:function(data){
                    alert(data["error"])
                },
            })
        }
    </script>
</body>
</html>
{{end}}           

後端代碼:

package main
import (
    "fmt"
    "net/http"
    "github.com/gin-gonic/gin"
)
type User struct {
    Name     string `json:"name" binding:"required"`
    Password string `json:"password" `
}
func main() {
    r := gin.Default()
    r.LoadHTMLGlob("template/**/*")
    r.Static("/static", "./static")
    r.GET("/to_bind_json", func(c *gin.Context) {
        c.HTML(http.StatusOK, "user/bind_json.html", nil)
    })
    r.POST("/bind_json_user", func(c *gin.Context) {
        var user User
        //err := c.BindJSON(&user)
        err := c.ShouldBindJSON(&user)
        if err != nil {
            c.JSON(http.StatusOK, gin.H{
                "status": "error",
                "msg":    err.Error(),
            })
            return
        }
        // 處理請求資料
        fmt.Println(user)
        c.JSON(http.StatusOK, gin.H{
            "status": "success",
            "msg":    "成功",
        })
    })
    r.Run(":8080")
}           

在上面的代碼中,我們首先定義了一個User結構體,然後在處理POST請求的回調函數中,使用ShouldBindJSON方法将請求資料綁定到user變量中。如果綁定失敗,則傳回錯誤資訊,否則處理請求資料并傳回成功狀态。binding标簽指定了該字段是否是必需的。或者缺少必需的字段,gin會傳回一個錯誤,提示請求不合法。

Bindxxx與ShouldBindxxx的差別:

bind方法會在綁定參數出錯時傳回一個錯誤,解析錯誤會在head中添加400的傳回資訊。

shouldbind方法則不會傳回錯誤,而是将錯誤資訊存儲在gin.Context的Error屬性中,需要手動處理。

繼續閱讀