参数绑定
GET
Query
//查询请求URL后面的参数Body
- 使用
ShouldBindJSON - 适用于
POST/PUT/PATCH
type Person struct { Name string `json:"username" binding:"required,min=3,max=20"` Nickname string `json:"nickname" binding:"nefield=Name"` Age json.Number `json:"age"` CreateTime time.Time `json:"create_time" ` Password string `json:"password" binding:"required,min=3"` RePassword string `json:"re_password" binding:"required,eqfield=Password"` Tel string `json:"tel"`}
userGroup := server.Group("/") { userGroup.POST("/add", func(context *gin.Context) {
bindError := context.ShouldBindJSON(&join) if bindError != nil { context.JSON(http.StatusBadRequest, gin.H{ "msg": bindError.Error(), }) return } context.JSON(http.StatusOK, gin.H{ "person": join, }) }) }Param
参数
- 使用
ShouldBindQuery, 参数绑定需要使用form这个tag, 与Body体的json不同 - 适用于
POST/GET/PUT/PATCH
type Person struct { Name string `json:"name" form:"name"` Age json.Number `json:"age" form:"age"` Gender string `json:"gender" form:"gender"`}
userGroup.POST("/", func(context *gin.Context) { err := context.ShouldBindQuery(&join) if err != nil { context.JSON(http.StatusBadRequest, gin.H{ "msg": err.Error(), }) return } context.JSON(http.StatusOK, gin.H{ "Person": join, })})动态参数
使用ShouldBindUri
type Person struct { Name string `json:"name" form:"name" uri:"name"`}
userGroup.GET("/:name/profile", func(context *gin.Context) {
err := context.ShouldBindUri(&join) if err != nil { context.JSON(http.StatusBadRequest, gin.H{ "msg": err.Error(), }) return } context.JSON(http.StatusOK, gin.H{ "name": join, })
})form-data/x-www-form-urlencode
前端发送form请求
const submit = () => { const userInfo: FormData = new FormData() userInfo.append('account', "account") userInfo.append('password', "password") userInfo.append('avatar', "avatar") userInfo.append('email', "email") userInfo.append('nickname', "nickname") userInfo.append('gender', "gender") userInfo.append('createdAt', "new Date().getTime().toString()") userInfo.append('updatedAt', "new Date().getTime().toString()") fetch('http://localhost:4000/register', { method: 'PUT', body: userInfo, }) .then((res) => { if (res.ok){ return res.json() } throw new Error('请求失败') }) .then((res) => { console.log(res) }) .catch((err) => { console.error(err) })}使用ShoulBind tag为form
package http
import ( "context" "github.com/gin-gonic/gin" "im/db" "im/schema" "log" "net/http")
type UserBasic struct { Account string `form:"account" json:"account"` Password string `form:"password" json:"password"` Avatar string `form:"avatar" json:"avatar"` Email string `form:"email" json:"email"` Nickname string `form:"nickname" json:"nickname"` Gender string `form:"gender" json:"gender"` CreatedAt string `form:"createdAt" json:"createdAt"` UpdatedAt string `form:"updatedAt" json:"updatedAt"`}
func Register(c *gin.Context) { var userInfo UserBasic if err := c.ShouldBind(&userInfo); err != nil { log.Println("转换JSON失败") return }
result, err := db.Mongo. Database("im"). Collection(schema.UserBasic{}.Collection()). InsertOne(context.TODO(), userInfo) log.Println("result:", result) if err != nil { log.Println("插入数据失败" + err.Error()) return } c.JSON(http.StatusOK, gin.H{ "data": "OK", "message": "注册成功", "code": http.StatusOK, })}