Golang's gin framework, the differences between various ways of receiving parameters and various bindings?
look at the documents of gin , and receive various parameters sent from the client. There are two main ways:
1. Use various methods to receive a single parameter:
c.Param()
c.Query
c.DefaultQuery
c.PostForm
c.DefaultPostForm
c.QueryMap
c.PostFormMap
c.FormFile
c.MultipartForm
2. Use various binding methods
c.Bind
c.BindJSON
c.BindXML
c.BindQuery
c.BindYAML
c.ShouldBind
c.ShouldBindJSON
c.ShouldBindXML
c.ShouldBindQuery
c.ShouldBindYAML
question:
what is the advantage of binding over the above one? Why should the two coexist? if binding is convenient, why not use binding? Ask the boss for guidance.
is actually something of the http protocol ( take a look at the http protocol )
for example, use c.Query for request url query parameters
as in the following official example, ? id=1234&page=1
this is the query parameter (query params)
. You will see the
that this parameter is placed in url.
if the parameter is not in url, it can also be in body, such as x-www-form-urlencoded
parameter in body, such as name=manu&message=this_is_great
for gin, use name: = c.PostForm ("name")
api
follow the field Content-Type
, which indicates the type of body. Read more about this article
https://imququ.com/post/four-.
.
there are also things like c.FormFile
, which are used to handle
uploaded files.
request example
POST /post?id=1234&page=1 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
name=manu&message=this_is_great
Code example
func main() {
router := gin.Default()
router.POST("/post", func(c *gin.Context) {
id := c.Query("id") //
page := c.DefaultQuery("page", "0")
name := c.PostForm("name") // body x-www-form-urlencoded
message := c.PostForm("message")
fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
})
router.Run(":8080")
}
result output
id: 1234; page: 1; name: manu; message: this_is_great
these are the abstractions provided by the framework, making it easier for you to deal with json,xml, etc.