為了能夠更方便的獲取請求相關引數,提高開發效率,我們可以基于請求的Content-Type識別請求資料型別并利用反射機制自動提取請求中QueryString、form表單、JSON、XML等引數到結構體中, 下面的示例代碼演示了.ShouldBind()強大的功能,它能夠基于請求自動提取JSON、form表單和QueryString型別的資料,并把值系結到指定的結構體物件,
前端
#index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ShouldBind</title>
</head>
<body>
<form action="/form" method="post">
用戶名:
<input type="text" name="username">
密碼:
<input type="password" name="password">
<input type="submit" value="https://www.cnblogs.com/zisefeizhu/p/提交">
</form>
</body>
</html>
后端
#main.go
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"net/http"
)
type UserInfo struct {
Username string `form:"username" json:"user"`
Password string `form:"password" json:"pass"`
}
func main() {
r := gin.Default()
r.LoadHTMLFiles("./index.html")
r.GET("/user", func(c *gin.Context) {
//username := c.Query("username")
//password := c.Query("password")
//u := UserInfo{
// username: username,
// password: password,
//}
var u UserInfo //宣告一個UserInfo型別的變數u
err := c.ShouldBind(&u) //?
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
} else {
fmt.Printf("%#v\n",u)
c.JSON(http.StatusOK, gin.H{
"status":"ok",
})
}
})
r.GET("/index", func(c *gin.Context) {
c.HTML(http.StatusOK,"index.html",nil)
})
r.POST("/json", func(c *gin.Context) {
var u UserInfo //宣告一個UserInfo型別的變數u
err := c.ShouldBind(&u) //?
if err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": err.Error(),
})
} else {
fmt.Printf("%#v\n",u)
c.JSON(http.StatusOK, gin.H{
"status":"ok",
})
}
})
//c.JSON(http.StatusOK,gin.H{
// "message": "ok",
//})
r.Run(":9090")
}
驗證
json:對應的是user、pass




總結
ShouldBind會按照下面的順序決議請求中的資料完成系結:
如果是 GET 請求,只使用 Form 系結引擎(query),
如果是 POST 請求,首先檢查 content-type 是否為 JSON 或 XML,然后再使用 Form(form-data),
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/20825.html
標籤:Go
下一篇:Delphi創建臨時表總是報execption edbengineerror in module bdertl60.bpl
