0
点赞
收藏
分享

微信扫一扫

go使用gin框架之参数绑定

1、绑定GET请求参数

type Person struct {
Name string `form:"name"`
Age int `form:"age"`
}

需要先定义一个结构体用于和参数进行对应,这里的form后面对应的就是参数名

func main() {
r := gin.Default()
r.Handle("GET", "/hello", func(context *gin.Context) {
var person Person
err := context.ShouldBindQuery(&person)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(person.Name, person.Age)
context.Writer.Write([]byte("hello,"))
})
r.Run()
}

使用context.ShouldBindQuery(&person)来获取参数并赋值与person

2、绑定POST请求参数,和GET请求基本一样,只是ShouldBindQuery换成ShouldBind

r.Handle("POST", "/hellopost", func(context *gin.Context) {
var person Person
err := context.ShouldBind(&person)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(person.Name, person.Age)
context.Writer.Write([]byte("hello,"))
})

3、绑定JSON格式参数使用context.BindJSON(&person),其他都一样

r.Handle("POST", "/hellojson", func(context *gin.Context) {
var person Person
err := context.BindJSON(&person)
if err != nil {
fmt.Println(err.Error())
}
fmt.Println(person.Name, person.Age)
context.Writer.Write([]byte("hello,"))
})

举报

相关推荐

0 条评论