Gin 使用示例(四):绑定查询字符串或 POST 数据


示例代码(src/gin-demo/examples/request_data.go):

package main

import (
  "github.com/gin-gonic/gin"
  "log"
  "time"
)

type Person struct {
  Name     string    `form:"name"`
  Address  string    `form:"address"`
  Birthday time.Time `form:"birthday" time_format:"2006-01-02" time_utc:"1"`
}

func startPage(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)
  }

  c.String(200, "Success")
}

func main() {
  route := gin.Default()
  // GET 请求
  route.GET("/testing", startPage)
  // POST 请求
  route.POST("/testing", startPage)
  route.Run(":8085")
}

启动服务器:

-w918

通过 curl 请求:

-w878

-w1129


点赞 取消点赞 收藏 取消收藏

<< 上一篇: Gin 使用示例(三):绑定 HTML 复选框 checkbox

>> 下一篇: Gin 使用示例(五):绑定 URL 路由参数