请求参数gin Http请求Body和Header的获取 request post form Query header
POST /post?id=1234&page=1 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
test: test
name=manu&message=this_is_great
服务端代码
package main
import (
"fmt"
"github.com/gin-gonic/gin"
"io/ioutil"
)
func main() {
router := gin.Default()
router.POST("/test", func(c *gin.Context) {
// 查询请求URL后面拼接的参数
id := c.Query("id")
//查询请求URL后面的参数,如果没有填写默认值
page := c.DefaultQuery("page", "0")
// 从表单中查询参数
name := c.PostForm("name")
//从取得URL中参数,此处URL中没有name字段
name = c.Param("name")
// 从表单中查询参数,,如果没有就获取默认值
message := c.DefaultPostForm("message", "default")
// 获取Body值
bodyBytes, _ := ioutil.ReadAll(c.Request.Body)
// 获取header指定字段
headerTest := c.Request.Header.Get("test")
for k, v := range c.Request.Header {
fmt.Println(k, v)
}
fmt.Printf("id: %s; page: %s; name: %s; message: %s; header_test:%s; bodyBytes:%s", id, page, name, message, headerTest, bodyBytes)
})
router.Run(":8080")
}
postman请求
请求打印
Accept [*/*]
Postman-Token [fb0ab2f2-8653-4fc9-9dce-a18ed349d113]
Accept-Encoding [gzip, deflate]
Content-Length [31]
User-Agent [PostmanRuntime/7.15.0]
Test [test123]
Cache-Control [no-cache]
Connection [keep-alive]
Content-Type [application/x-www-form-urlencoded]
id: 123; page: 1; name: ; message: this_is_great; header_test:test123; bodyBytes:
gin文档:https://gin-gonic.com/zh-cn/docs/examples/query-and-post-form/
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)