Skip to content
Myr

support bind http header param #1956 (#1957)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* support bind http header param #1956 update #1956 ``` package main import ( "fmt" "github.com/gin-gonic/gin" ) type testHeader struct { Rate int `header:"Rate"` Domain string `header:"Domain"` } func main() { r := gin.Default() r.GET("/", func(c *gin.Context) { h := testHeader{} if err := c.ShouldBindHeader(&h); err != nil { c.JSON(200, err) } fmt.Printf("%#v\n", h) c.JSON(200, gin.H{"Rate": h.Rate, "Domain": h.Domain}) }) r.Run() // client // curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/ // output // {"Domain":"music","Rate":300} } ``` * add unit test * Modify the code to get the http header When the http header is obtained in the standard library, the key value will be modified by the CanonicalMIMEHeaderKey function, and finally the value of the http header will be obtained from the map. As follows. ```go func (h MIMEHeader) Get(key string) string {         // ...          v := h[CanonicalMIMEHeaderKey(key)]         // ... } ``` This pr also follows this modification * Thanks to vkd for suggestions, modifying code * Increase test coverage env GOPATH=`pwd` go test github.com/gin-gonic/gin/binding -coverprofile=cover.prof ok github.com/gin-gonic/gin/binding 0.015s coverage: 100.0% of statements * Rollback check code * add use case to README.md

authored by guonaihong · committed by thinkerou · parent 09a3650 · Browse files · 6 files+152 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+152 added−0 removed

  • other:+152 added−0 removed

6 files+152 added−0 removed

modified:binding/binding_test.go+25 added
665 unmodified lines
666 err := JSON.Bind(req, &obj)667 assert.Error(t, err)668}669670func TestHeaderBinding(t *testing.T) {671 h := Header672 assert.Equal(t, "header", h.Name())673674 type tHeader struct {675 Limit int `header:"limit"`676 }677678 var theader tHeader679 req := requestWithBody("GET", "/", "")680 req.Header.Add("limit", "1000")681 assert.NoError(t, h.Bind(req, &theader))682 assert.Equal(t, 1000, theader.Limit)683684 req = requestWithBody("GET", "/", "")685 req.Header.Add("fail", `{fail:fail}`)686687 type failStruct struct {688 Fail map[string]interface{} `header:"fail"`689 }690691 err := h.Bind(req, &failStruct{})692 assert.Error(t, err)693}694695func TestUriBinding(t *testing.T) {696 b := Uri697 assert.Equal(t, "uri", b.Name())698
510 unmodified lines
modified:binding/binding.go+1 added
76 unmodified lines
77 ProtoBuf = protobufBinding{}78 MsgPack = msgpackBinding{}79 YAML = yamlBinding{}80 Uri = uriBinding{}81 Header = headerBinding{}82)8384// Default returns the appropriate Binding instance based on the HTTP method85// and the content type.
29 unmodified lines
added:binding/header.go+34 added
1package binding23import (4 "net/http"5 "net/textproto"6 "reflect"7)89type headerBinding struct{}1011func (headerBinding) Name() string {12 return "header"13}1415func (headerBinding) Bind(req *http.Request, obj interface{}) error {1617 if err := mapHeader(obj, req.Header); err != nil {18 return err19 }2021 return validate(obj)22}2324func mapHeader(ptr interface{}, h map[string][]string) error {25 return mappingByPtr(ptr, headerSource(h), "header")26}2728type headerSource map[string][]string2930var _ setter = headerSource(nil)3132func (hs headerSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (isSetted bool, err error) {33 return setByForm(value, field, hs, textproto.CanonicalMIMEHeaderKey(tagValue), opt)34}
modified:context_test.go+44 added
1434 unmodified lines
1435 assert.Equal(t, "BAR", obj.Bar)1436 assert.Equal(t, 0, w.Body.Len())1437}14381439func TestContextBindHeader(t *testing.T) {1440 w := httptest.NewRecorder()1441 c, _ := CreateTestContext(w)14421443 c.Request, _ = http.NewRequest("POST", "/", nil)1444 c.Request.Header.Add("rate", "8000")1445 c.Request.Header.Add("domain", "music")1446 c.Request.Header.Add("limit", "1000")14471448 var testHeader struct {1449 Rate int `header:"Rate"`1450 Domain string `header:"Domain"`1451 Limit int `header:"limit"`1452 }14531454 assert.NoError(t, c.BindHeader(&testHeader))1455 assert.Equal(t, 8000, testHeader.Rate)1456 assert.Equal(t, "music", testHeader.Domain)1457 assert.Equal(t, 1000, testHeader.Limit)1458 assert.Equal(t, 0, w.Body.Len())1459}14601461func TestContextBindWithQuery(t *testing.T) {1462 w := httptest.NewRecorder()1463 c, _ := CreateTestContext(w)1464
99 unmodified lines
1564 assert.Equal(t, "BAR", obj.Bar)1565 assert.Equal(t, 0, w.Body.Len())1566}15671568func TestContextShouldBindHeader(t *testing.T) {1569 w := httptest.NewRecorder()1570 c, _ := CreateTestContext(w)15711572 c.Request, _ = http.NewRequest("POST", "/", nil)1573 c.Request.Header.Add("rate", "8000")1574 c.Request.Header.Add("domain", "music")1575 c.Request.Header.Add("limit", "1000")15761577 var testHeader struct {1578 Rate int `header:"Rate"`1579 Domain string `header:"Domain"`1580 Limit int `header:"limit"`1581 }15821583 assert.NoError(t, c.ShouldBindHeader(&testHeader))1584 assert.Equal(t, 8000, testHeader.Rate)1585 assert.Equal(t, "music", testHeader.Domain)1586 assert.Equal(t, 1000, testHeader.Limit)1587 assert.Equal(t, 0, w.Body.Len())1588}15891590func TestContextShouldBindWithQuery(t *testing.T) {1591 w := httptest.NewRecorder()1592 c, _ := CreateTestContext(w)1593
297 unmodified lines
modified:context.go+10 added
581 unmodified lines
582func (c *Context) BindYAML(obj interface{}) error {583 return c.MustBindWith(obj, binding.YAML)584}585586// BindHeader is a shortcut for c.MustBindWith(obj, binding.Header).587func (c *Context) BindHeader(obj interface{}) error {588 return c.MustBindWith(obj, binding.Header)589}590591// BindUri binds the passed struct pointer using binding.Uri.592// It will abort the request with HTTP 400 if any error occurs.593func (c *Context) BindUri(obj interface{}) error {594 if err := c.ShouldBindUri(obj); err != nil {
46 unmodified lines
641func (c *Context) ShouldBindYAML(obj interface{}) error {642 return c.ShouldBindWith(obj, binding.YAML)643}644645// ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header).646func (c *Context) ShouldBindHeader(obj interface{}) error {647 return c.ShouldBindWith(obj, binding.Header)648}649650// ShouldBindUri binds the passed struct pointer using the specified binding engine.651func (c *Context) ShouldBindUri(obj interface{}) error {652 m := make(map[string][]string)653 for _, v := range c.Params {
420 unmodified lines
modified:README.md+38 added
38 unmodified lines
39 - [Custom Validators](#custom-validators)40 - [Only Bind Query String](#only-bind-query-string)41 - [Bind Query String or Post Data](#bind-query-string-or-post-data)42 - [Bind Uri](#bind-uri)43 - [Bind Header](#bind-header)44 - [Bind HTML checkboxes](#bind-html-checkboxes)45 - [Multipart/Urlencoded binding](#multiparturlencoded-binding)46 - [XML, JSON, YAML and ProtoBuf rendering](#xml-json-yaml-and-protobuf-rendering)47 - [JSONP rendering](#jsonp)
862 unmodified lines
910$ curl -v localhost:8088/thinkerou/987fbc97-4bed-5078-9f07-9141ba07c9f3911$ curl -v localhost:8088/thinkerou/not-uuid912```913914### Bind Header915916```go917package main918919import (920 "fmt"921 "github.com/gin-gonic/gin"922)923924type testHeader struct {925 Rate int `header:"Rate"`926 Domain string `header:"Domain"`927}928929func main() {930 r := gin.Default()931 r.GET("/", func(c *gin.Context) {932 h := testHeader{}933934 if err := c.ShouldBindHeader(&h); err != nil {935 c.JSON(200, err)936 }937938 fmt.Printf("%#v\n", h)939 c.JSON(200, gin.H{"Rate": h.Rate, "Domain": h.Domain})940 })941942 r.Run()943944// client945// curl -H "rate:300" -H "domain:music" 127.0.0.1:8080/946// output947// {"Domain":"music","Rate":300}948}949```950951### Bind HTML checkboxes952953See the [detail information](https://github.com/gin-gonic/gin/issues/129#issuecomment-124260092)954
1159 unmodified lines