用gin框架的數據驗證,可以不用解析數據,減少if else,會簡潔許多。
package main import ( "fmt" "github.com/gin-gonic/gin" "net/http" ) type Example struct{ Name string `form:"name" binding:"required" `//1。required表示該參數是必要參數,如果不傳或為空會報錯 Age int `form:"age" ` //2。如果用戶輸入數據類型不匹配會報錯 Sex string `form:"sex"` } func get(c *gin.Context){ var data Example //結構體只和查詢參數綁定 if err:=c.ShouldBindQuery(&data);err==nil{ fmt.Println(data.Name) fmt.Println(data.Age) fmt.Println(data.Sex) c.JSON(http.StatusOK,gin.H{"res":"success"}) }else{ fmt.Println(err.Error()) c.JSON(http.StatusOK,gin.H{"res":err.Error()}) } } func post(c *gin.Context){ var data Example //結構體和傳進來的json綁定 if err:=c.ShouldBindJSON(&data);err==nil{ fmt.Println(data.Name) fmt.Println(data.Age) fmt.Println(data.Sex) c.JSON(http.StatusOK,gin.H{"res":"success"})//gin.h()返回map[string]interface{}類型,返回數據這塊也可以將結構體類型返回 }else{ fmt.Println(err.Error()) c.JSON(http.StatusOK,gin.H{"res":err.Error()}) } } func main(){ router:=gin.Default() router.GET("/v1",get) router.POST("/v1",post) router.Run("127.0.0.1:8888") }
//1。輸入: { "name":"zh" "age":18, "sex":"sex" } //輸出: zh 18 sex //2。輸入 { "name":"", "age":18, "sex":"sex" } //輸出 { "res": "Key: 'Example.Name' Error:Field validation for 'Name' failed on the 'required' tag" } //3。輸入 { "name":18, "age":18, "sex":"sex" } //輸出 { "res": "json: cannot unmarshal number into Go struct field Example.Name of type string" }