gin/json-form-uri-bind-json/main.go

86 lines
2.2 KiB
Go
Raw Normal View History

2024-09-18 00:04:45 +08:00
package main
import (
"github.com/gin-gonic/gin"
"net/http"
)
type Login struct {
//binding:"required" required 修饰的字段,若接受为控制 则报错 是必选字段
User string `form:"username" json:"user" uri:"user" xml:"user" binding:"required"`
Password string `form:"password" json:"password" uri:"password" xml:"password" binding:"required"`
}
func main() {
//绑定JSON-结构体
//bindJson()
//绑定form-结构体
//bindForm()
//绑定uri-结构体
//bindUri()
}
func bindJson() {
r := gin.Default()
//Json绑定
r.POST("/loginJSON", func(c *gin.Context) {
//声明接收的变量
var json Login
//将request中的body自动按照json格式解析到结构体
//gin.H封装了生成json数据的工具
if err := c.ShouldBindJSON(&json); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
//判断用户名密码是否正确
if json.User != "admin" || json.Password != "admin" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "wrong username or password"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "ok"})
})
r.Run(":8000")
}
func bindForm() {
r := gin.Default()
r.POST("/loginform", func(c *gin.Context) {
var form Login
//Bind()默认解析并绑定form格式
//根据请求头中的content-type自动推断
if err := c.Bind(&form); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if form.User != "admin" || form.Password != "admin" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "wrong username or password"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "ok"})
})
r.Run(":8000")
}
// http://127.0.0.1/admin/admin
func bindUri() {
r := gin.Default()
r.GET("/:user/:password", func(c *gin.Context) {
var login Login
//Bind()默认解析并绑定form格式
//根据请求头中的content-type自动推断
if err := c.ShouldBindUri(&login); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
if login.User != "admin" || login.Password != "admin" {
c.JSON(http.StatusUnauthorized, gin.H{"error": "wrong username or password"})
return
}
c.JSON(http.StatusOK, gin.H{"message": "ok"})
})
r.Run(":8000")
}