go語言web框架gin 從請求中取引數
阿新 • • 發佈:2018-12-26
-
POST /post/123?id=1234&page=1 HTTP/1.1
-
Content-Type: application/x-www-form-urlencoded
-
name=manu&message=this_is_great
func main() { router := gin.Default() router.POST("/post/:uuid", func(c *gin.Context) { id := c.Query("id") //查詢請求URL後面的引數 page := c.DefaultQuery("page", "0") //查詢請求URL後面的引數,如果沒有填寫預設值 name := c.PostForm("name") //從表單中查詢引數
name := c.Request.FormValue("name") //POST and PUT body parameters take precedence over URL query string values
name := c.Request.PostFormValue("name") //return POST and PUT body parameters, URL query parameters are ignored
message := c.DefaultPostForm("message", "aa") //從表單中查詢引數,如果沒有填寫預設值
uuid := c.Param("uuid") //取得URL中引數
s, _ := c.Get("current_manager") //從使用者上下文讀取值
var u User
err1 := c.BindWith(&u, binding.Form) //從http.Request中讀取值到User結構體中,手動確定繫結型別binding.Form
err2 := c.Bind(&u) //從http.Request中讀取值到User結構體中,根據請求方法型別和請求內容格式型別自動確定繫結型別
user := sessions.Default(c).get("user") //從session中讀取值
使用者上下文和session生命週期不同,每一次請求會生成一個對應的上下文,一次http請求結束,該次請求的上下文結束,一般來說session(會話)會留存一段時間
session(會話)中一般儲存使用者登入狀態等資訊,context(上下文)主要用於在一次http請求中,在中介軟體(流)中進行資訊傳遞
fmt.Printf("id: %s; page: %s; name: %s; message: %s", id, page, name, message) }) router.Run(":8080") }
轉自https://blog.csdn.net/btqszl/article/details/60880386