原生
Urlencoded Form
即content-type 為 x-www-form-urlencode的數據。
r.Form["param"]
r.PostForm["param"]
r.FormValue("param")
r.PostFormValue("param")
其中r.Form和r.PostForm必須在調用ParseForm之后,才會有數據,否則則是空數組。
而r.FormValue和r.PostFormValue("lang")無需ParseForm的調用就能讀取數據。
MutilpartFrom
即content-type為form-data的數據使用ParseMutilpartFrom方法解析參數,但是不會解析url query的參數的
r.Form["param"]
r.PostForm["param"]
r.FormValue("param")
r.PostFormValue("param")
r.MultipartForm.Value["param"]
r.MultipartForm.File包含圖片數據
r.FormFile可以直接讀取上傳文件數據
gin
Parameters in path
func main() {
router := gin.Default()
// This handler will match /user/john but will not match neither /user/ or /user
router.GET("/user/:name", func(c *gin.Context) {
name := c.Param("name")
c.String(http.StatusOK, "Hello %s", name)
})
// However, this one will match /user/john/ and also /user/john/send
// If no other routers match /user/john, it will redirect to /user/john/
router.GET("/user/:name/*action", func(c *gin.Context) {
name := c.Param("name")
action := c.Param("action")
message := name + " is " + action
c.String(http.StatusOK, message)
})
router.Run(":8080")
}
Querystring parameters
func main() {
router := gin.Default()
// Query string parameters are parsed using the existing underlying request object.
// The request responds to a url matching: /welcome?firstname=Jane&lastname=Doe
router.GET("/welcome", func(c *gin.Context) {
firstname := c.DefaultQuery("firstname", "Guest")
lastname := c.Query("lastname") // shortcut for c.Request.URL.Query().Get("lastname")
c.String(http.StatusOK, "Hello %s %s", firstname, lastname)
})
router.Run(":8080")
}
Multipart/Urlencoded Form
func main() {
router := gin.Default()
router.POST("/form_post", func(c *gin.Context) {
message := c.PostForm("message")
nick := c.DefaultPostForm("nick", "anonymous")
c.JSON(200, gin.H{
"status": "posted",
"message": message,
"nick": nick,
})
})
router.Run(":8080")
}
query + post form
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")
message := c.PostForm("message")
fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message)
})
router.Run(":8080")
}