获取请求数据
获取Json请求数据
通过调用 c.Request.Body 方法绑定数据,但只能调用一次,之后将获取不到数据。
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"io/ioutil"
)
func GetParam(c *gin.Context){
param := make(map[string]interface{})
request, _ := ioutil.ReadAll(c.Request.Body)
err := json.Unmarshal(request, ¶m)
if err != nil{
fmt.Println("param parse error:", err)
}
fmt.Println(param)
}
获取请求头数据
import (
"fmt"
"github.com/gin-gonic/gin"
)
func GetHeader(c *gin.Context){
token := c.GetHeader("Token")
fmt.Println(token)
}
获取Form Data数据
import (
"fmt"
"github.com/gin-gonic/gin"
)
func GetParam(c *gin.Context){
id := c.Query("id")
page := c.DefaultQuery("page", "0")
name := c.PostForm("name")
nick := c.DefaultPostForm("nick", "anonymous")
fmt.Println(id, page, name, nick)
}