type User struct{ Name string`form:"name"` role string`form:"role"` }
// 匹配users?name=xxx&role=xxx,role可选 r.GET("/users", func(c *gin.Context) { name := c.Query("name") role := c.DefaultQuery("role", "teacher") var user User err:=ctx.ShouldBindQuery(&user) if err== nil{ fmt.Println("user", user) } c.String(http.StatusOK, "%s is a %s", name, role) })
获取Post参数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
type User struct{ Name string`form:"name"` Pwd int`form:"password"` } // POST r.POST("/form", func(c *gin.Context) { username := c.PostForm("username") password := c.DefaultPostForm("password", "000000") // 可设置默认值 var user User err:=ctx.ShouldBind(&user) if err== nil{ fmt.Println("user", user) } c.JSON(http.StatusOK, gin.H{ "username": username, "password": password, }) })
// LoggerWithFormatter middleware will write the logs to gin.DefaultWriter // By default gin.DefaultWriter = os.Stdout router.Use(gin.LoggerWithFormatter(func(param gin.LogFormatterParams)string {
var bookableDate validator.Func = func(fl validator.FieldLevel)bool { date, ok := fl.Field().Interface().(time.Time) if ok { today := time.Now() if today.After(date) { returnfalse } } returntrue }
funcmain() { route := gin.Default()
if v, ok := binding.Validator.Engine().(*validator.Validate); ok { v.RegisterValidation("bookabledate", bookableDate) }
funcgetBookable(c *gin.Context) { var b Booking if err := c.ShouldBindWith(&b, binding.Query); err == nil { c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"}) } else { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } }
1 2 3 4 5 6 7 8
$ curl "localhost:8085/bookable?check_in=2030-04-16&check_out=2030-04-17" {"message":"Booking dates are valid!"}
$ curl "localhost:8085/bookable?check_in=2030-03-10&check_out=2030-03-09" {"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"}
$ curl "localhost:8085/bookable?check_in=2000-03-09&check_out=2000-03-10" {"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}%
funcstartPage(c *gin.Context) { var person Person if c.ShouldBindQuery(&person) == nil { log.Println("====== Only Bind By Query String ======") log.Println(person.Name) log.Println(person.Address) } c.String(200, "Success") }
funcstartPage(c *gin.Context) { var person Person // If `GET`, only `Form` binding engine (`query`) used. // If `POST`, first checks the `content-type` for `JSON` or `XML`, then uses `Form` (`form-data`). // See more at https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L48 if c.ShouldBind(&person) == nil { log.Println(person.Name) log.Println(person.Address) log.Println(person.Birthday) log.Println(person.CreateTime) log.Println(person.UnixTime) }
c.String(200, "Success") }
1
curl -X GET "localhost:8085/testing?name=appleboy&address=xyz&birthday=1992-03-15&createTime=1562400033000000123&unixTime=1562400033"