Golang uses the parameter bindings of the GIN framework
Bind the GET request parameters
type Person struct {
Name string `form:"name"`
Age int `form:"age"`
}
You need to define a structure that corresponds to the parameter. In this case, the form corresponds to the parameter name
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()
}
Use context.shouldbindQuery (& Person) to get arguments and assign values to Person
Bind the POST request parameter, which is basically the same as the GET request, except ShouldBindQuery is replaced with 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,"))
})
The binding JSON format parameter uses context.bindjson (& Person), otherwise identical
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,"))
})