Thanks to vkd for suggestions, modifying code

This commit is contained in:
guonaihong 2019-06-24 22:20:46 +08:00
parent ce723d2c12
commit 159224bc62
3 changed files with 34 additions and 19 deletions

View File

@ -667,6 +667,22 @@ func TestExistsFails(t *testing.T) {
assert.Error(t, err)
}
func TestHeaderBinding(t *testing.T) {
h := Header
assert.Equal(t, "header", h.Name())
type tHeader struct {
Limit int `header:"limit"`
}
var theader tHeader
req := requestWithBody("GET", "/", "")
req.Header.Add("limit", "1000")
assert.NoError(t, h.Bind(req, &theader))
assert.Equal(t, 1000, theader.Limit)
}
func TestUriBinding(t *testing.T) {
b := Uri
assert.Equal(t, "uri", b.Name())

View File

@ -7,7 +7,6 @@ package binding
import (
"errors"
"fmt"
"net/textproto"
"reflect"
"strconv"
"strings"
@ -22,10 +21,6 @@ func mapUri(ptr interface{}, m map[string][]string) error {
return mapFormByTag(ptr, m, "uri")
}
func mapHeader(ptr interface{}, m map[string][]string) error {
return mapFormByTag(ptr, m, "header")
}
func mapForm(ptr interface{}, form map[string][]string) error {
return mapFormByTag(ptr, form, "form")
}
@ -107,7 +102,6 @@ func mapping(value reflect.Value, field reflect.StructField, setter setter, tag
type setOptions struct {
isDefaultExists bool
isHeader bool
defaultValue string
}
@ -129,7 +123,6 @@ func tryToSetValue(value reflect.Value, field reflect.StructField, setter setter
}
var opt string
setOpt.isHeader = tag == "header"
for len(opts) > 0 {
opt, opts = head(opts, ",")
@ -143,17 +136,7 @@ func tryToSetValue(value reflect.Value, field reflect.StructField, setter setter
}
func setByForm(value reflect.Value, field reflect.StructField, form map[string][]string, tagValue string, opt setOptions) (isSetted bool, err error) {
var (
vs []string
ok bool
)
if opt.isHeader {
vs, ok = form[textproto.CanonicalMIMEHeaderKey(tagValue)]
} else {
vs, ok = form[tagValue]
}
vs, ok := form[tagValue]
if !ok && !opt.isDefaultExists {
return false, nil
}

View File

@ -1,6 +1,10 @@
package binding
import "net/http"
import (
"net/http"
"net/textproto"
"reflect"
)
type headerBinding struct{}
@ -16,3 +20,15 @@ func (headerBinding) Bind(req *http.Request, obj interface{}) error {
return validate(obj)
}
func mapHeader(ptr interface{}, h map[string][]string) error {
return mappingByPtr(ptr, headerSource(h), "header")
}
type headerSource map[string][]string
//var _ setter = headerSource(nil)
func (hs headerSource) TrySet(value reflect.Value, field reflect.StructField, tagValue string, opt setOptions) (isSetted bool, err error) {
return setByForm(value, field, hs, textproto.CanonicalMIMEHeaderKey(tagValue), opt)
}