diff --git a/binding/binding.go b/binding/binding.go index 520c5109..6d58c3cd 100644 --- a/binding/binding.go +++ b/binding/binding.go @@ -78,6 +78,7 @@ var ( MsgPack = msgpackBinding{} YAML = yamlBinding{} Uri = uriBinding{} + Header = headerBinding{} ) // Default returns the appropriate Binding instance based on the HTTP method diff --git a/binding/form_mapping.go b/binding/form_mapping.go index ebf3b199..7b84e2ea 100644 --- a/binding/form_mapping.go +++ b/binding/form_mapping.go @@ -21,6 +21,10 @@ 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") } diff --git a/binding/header.go b/binding/header.go new file mode 100644 index 00000000..0f9e5fd4 --- /dev/null +++ b/binding/header.go @@ -0,0 +1,18 @@ +package binding + +import "net/http" + +type headerBinding struct{} + +func (headerBinding) Name() string { + return "header" +} + +func (headerBinding) Bind(req *http.Request, obj interface{}) error { + + if err := mapHeader(obj, req.Header); err != nil { + return err + } + + return validate(obj) +} diff --git a/context.go b/context.go index 77cdc182..d9fcc285 100644 --- a/context.go +++ b/context.go @@ -583,6 +583,11 @@ func (c *Context) BindYAML(obj interface{}) error { return c.MustBindWith(obj, binding.YAML) } +// BindHeader is a shortcut for c.MustBindWith(obj, binding.Header). +func (c *Context) BindHeader(obj interface{}) error { + return c.MustBindWith(obj, binding.Header) +} + // BindUri binds the passed struct pointer using binding.Uri. // It will abort the request with HTTP 400 if any error occurs. func (c *Context) BindUri(obj interface{}) error { @@ -637,6 +642,11 @@ func (c *Context) ShouldBindYAML(obj interface{}) error { return c.ShouldBindWith(obj, binding.YAML) } +// ShouldBindHeader is a shortcut for c.ShouldBindWith(obj, binding.Header). +func (c *Context) ShouldBindHeader(obj interface{}) error { + return c.ShouldBindWith(obj, binding.Header) +} + // ShouldBindUri binds the passed struct pointer using the specified binding engine. func (c *Context) ShouldBindUri(obj interface{}) error { m := make(map[string][]string)