gin demo
gin demo
演示参数校验
package main import ( "fmt" "io/ioutil" "net/http" "github.com/gin-gonic/gin" // "context" ) type Userinfo struct { Username string `form:"username" json:"username" xml:"username" binding:"required,oneof=public private"` Password string `form:"password" json:"password" xml:"password" binding:"required"` // Password string `form:"password" json:"password" xml:"password" binding:"required"` } type Login struct { User string `form:"user" json:"user" xml:"user" binding:"required"` Password string `form:"password" json:"password" xml:"password" binding:"required"` } func readAllRequest(ctx *gin.Context) (error, []byte) { data, err := ioutil.ReadAll(ctx.Request.Body) if err != nil { return err, nil } return nil, data } func main() { r := gin.Default() r.POST("/pingpost", func(c *gin.Context) { // err, data := readAllRequest(c) // if err != nil { // fmt.Println(err) // } // obj := gjson.Parse(string(data)) // fmt.Println(obj) // id1 := c.PostForm("username") // id2 := c.PostForm("password") // fmt.Printf("id1: %v; id2: %v", id1, id2) var json Userinfo if err := c.ShouldBind(&json); err != nil { c.JSON(200, gin.H{"message": err.Error()}) return } fmt.Println(json) c.JSON(200, gin.H{ "message": "pong", }) }) r.POST("/login", func(c *gin.Context) { var json Login if err := c.ShouldBindJSON(&json); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } fmt.Println(json) c.JSON(200, gin.H{"status": "you are logged in"}) }) r.Run(":8081") // listen and serve on 0.0.0.0:8080 (for windows "localhost:8080") }