gin中绑定查询字符串或表单数据

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 main() {
	r := gin.Default()
	r.GET("/", someHandler)
	r.Run()
}

func someHandler(c *gin.Context) {
	var person Person
	// 如果是GET请求,只使用Form绑定引擎Query
	// 如果是POST请求,首先检查Content-Type是否为Json或Xml,然后再使用Form(form-data)
	// 查看更多:https://github.com/gin-gonic/gin/blob/master/binding/binding.go#L88
	if c.ShouldBind(&person) == nil {
		log.Println(person.Name)
		log.Println(person.Address)
		log.Println(person.Birthday)
	}
}

  

posted @ 2021-10-27 16:55  专职  阅读(26)  评论(0编辑  收藏  举报