1. 程式人生 > 其它 >gin中模型的繫結和驗證

gin中模型的繫結和驗證

要將請求體繫結到結構體中,使用模型繫結。 Gin目前支援JSON、XML、YAML和標準表單值的繫結(foo=bar&boo=baz)。

Gin使用go-playground/validator/v10進行驗證。 檢視標籤用法的全部文件.

使用時,需要在要繫結的所有欄位上,設定相應的tag。 例如,使用 JSON 繫結時,設定欄位標籤為json:"fieldname"

Gin提供了兩類繫結方法:

  • Type- Must bind
    • Methods-Bind,BindJSON,BindXML,BindQuery,BindYAML
    • Behavior- 這些方法屬於MustBindWith的具體呼叫。 如果發生繫結錯誤,則請求終止,並觸發c.AbortWithError(400, err).SetType(ErrorTypeBind)
      。響應狀態碼被設定為 400 並且Content-Type被設定為text/plain; charset=utf-8。 如果您在此之後嘗試設定響應狀態碼,Gin會輸出日誌[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422。 如果您希望更好地控制繫結,考慮使用ShouldBind等效方法。
  • Type- Should bind
    • Methods-ShouldBind,ShouldBindJSON,ShouldBindXML,ShouldBindQuery,ShouldBindYAML
    • Behavior- 這些方法屬於ShouldBindWith的具體呼叫。 如果發生繫結錯誤,Gin 會返回錯誤並由開發者處理錯誤和請求。

使用 Bind 方法時,Gin 會嘗試根據 Content-Type 推斷如何繫結。 如果你明確知道要繫結什麼,可以使用MustBindWithShouldBindWith

你也可以指定必須繫結的欄位。 如果一個欄位的 tag 加上了binding:"required",但繫結時是空值, Gin 會報錯。

package main

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

type Login struct {
	// binding: "-"      // - 表示可以不傳遞該引數
	User string `json:"user" form:"user" xml:"user" binding:"required"`
	Password string `json:"password" form:"password" xml:"password" binding:"required"`
}

func main() {
	// 模型的繫結和驗證

	// 1. JSON的繫結和驗證
	//r := gin.Default()
	//r.POST("/", func(context *gin.Context) {
	//	var login Login
	//	if err := context.ShouldBindJSON(&login); err != nil {
	//		context.String(http.StatusBadRequest, err.Error())
	//		return
	//	}
	//	if login.User != "li" || login.Password != "123456" {
	//		context.JSON(http.StatusUnauthorized, gin.H{"err": "unauthorized"})
	//		return
	//	}
	//	context.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
	//})
	//r.Run()

	// 2. 表單的繫結和驗證
	//r := gin.Default()
	//r.POST("/", func(context *gin.Context) {
	//	var login Login
	//	// 根據Content-Type header 推斷用哪個繫結器
	//	if err := context.ShouldBind(&login); err != nil {
	//		context.String(http.StatusBadRequest, err.Error())
	//		return
	//	}
	//	if login.User != "li" || login.Password != "123456" {
	//		context.JSON(http.StatusUnauthorized, gin.H{"err": "unauthorized"})
	//		return
	//	}
	//	context.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
	//})
	//r.Run()

	// 3. xml的繫結和驗證
	/* xml格式:
		<?xml version="1.0" encoding="UTF-8"?>
		<root>
	    	<user>li</user>
	    	<password>123456</password>
		</root>
	*/
	r := gin.Default()
	r.POST("/", func(context *gin.Context) {
		var login Login
		if err := context.ShouldBindXML(&login); err != nil {
			context.String(http.StatusBadRequest, err.Error())
			return
		}
		if login.User != "li" || login.Password != "123456" {
			context.JSON(http.StatusUnauthorized, gin.H{"err": "unauthorized"})
			return
		}
		context.JSON(http.StatusOK, gin.H{"status": "you are logged in"})
	})
	r.Run()

}

  

validator 參考連結:

1. github: https://github.com/go-playground/validator

2. document: https://pkg.go.dev/github.com/go-playground/validator/v10#section-documentation