Documentation
¶
Overview ¶
Package binder provides a common binder to bind a value to any, for example, binding a struct to a map.
Index ¶
- Variables
- func Bind(dstptr, src interface{}) error
- func BindStructToHTTPHeader(structptr interface{}, tag string, data http.Header) error
- func BindStructToMap(structptr interface{}, tag string, data map[string]interface{}) (err error)
- func BindStructToMultipartFileHeaders(structptr interface{}, tag string, fhs map[string][]*multipart.FileHeader) error
- func BindStructToStringMap(structptr interface{}, tag string, data map[string]string) (err error)
- func BindStructToURLValues(structptr interface{}, tag string, data url.Values) error
- func BindWithTag(dstptr, src interface{}, tag string) error
- type Binder
- type Decoder
- type DecoderFunc
- type Hook
- type MuxDecoder
- type Setter
- type Unmarshaler
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var DefaultBinder = NewBinder()
DefaultBinder is the default binder.
Functions ¶
func BindStructToHTTPHeader ¶
BindStructToHTTPHeader binds the struct to http.Header.
For the key name, it will use textproto.CanonicalMIMEHeaderKey(s) to normalize it.
Example ¶
src := http.Header{ "X-Int": []string{"1", "2"}, "X-Ints": []string{"3", "4"}, "X-Str": []string{"a", "b"}, "X-Strs": []string{"c", "d"}, } var dst struct { unexported string `header:"-"` Other string `header:"Other"` Int int `header:"x-int"` Ints []int `header:"x-ints"` Str string `header:"x-str"` Strs []string `header:"x-strs"` } err := BindStructToHTTPHeader(&dst, "header", src) if err != nil { fmt.Println(err) } else { fmt.Printf("unexported=%s\n", dst.unexported) fmt.Printf("Other=%s\n", dst.Other) fmt.Printf("Int=%d\n", dst.Int) fmt.Printf("Ints=%d\n", dst.Ints) fmt.Printf("Str=%s\n", dst.Str) fmt.Printf("Strs=%s\n", dst.Strs) }
Output: unexported= Other= Int=1 Ints=[3 4] Str=a Strs=[c d]
func BindStructToMap ¶
BindStructToMap binds the struct to map[string]interface{}.
For the key name, it is case-sensitive.
func BindStructToMultipartFileHeaders ¶
func BindStructToMultipartFileHeaders(structptr interface{}, tag string, fhs map[string][]*multipart.FileHeader) error
BindStructToMultipartFileHeaders binds the struct to the multipart form file headers.
For the key name, it is case-sensitive.
Example ¶
src := map[string][]*multipart.FileHeader{ "file": {{Filename: "file"}}, "files": {{Filename: "file1"}, {Filename: "file2"}}, "_file": {{Filename: "file3"}}, } var dst struct { Other string `form:"Other"` _File *multipart.FileHeader `form:"_file"` // unexported, so ignored FileHeader *multipart.FileHeader `form:"file"` FileHeaders []*multipart.FileHeader `form:"files"` } err := BindStructToMultipartFileHeaders(&dst, "form", src) if err != nil { fmt.Println(err) } else { fmt.Println(dst.FileHeader.Filename) if dst._File != nil { fmt.Println(dst._File.Filename) } for _, fh := range dst.FileHeaders { fmt.Println(fh.Filename) } }
Output: file file1 file2
func BindStructToStringMap ¶
BindStructToStringMap binds the struct to map[string]string.
For the key name, it is case-sensitive.
Example ¶
src := map[string]string{ "Int": "123", "Str": "456", } var dst struct { Int int `tag:"-"` Int1 int `tag:"Int"` Int2 int `tag:"Str"` } err := BindStructToStringMap(&dst, "tag", src) if err != nil { fmt.Println(err) } else { fmt.Printf("Int=%d\n", dst.Int) fmt.Printf("Int1=%d\n", dst.Int1) fmt.Printf("Int2=%d\n", dst.Int2) }
Output: Int=0 Int1=123 Int2=456
func BindStructToURLValues ¶
BindStructToURLValues binds the struct to url.Values.
For the key name, it is case-sensitive.
Example ¶
src := url.Values{ "int": []string{"1", "2"}, "ints": []string{"3", "4"}, "str": []string{"a", "b"}, "strs": []string{"c", "d"}, } var dst struct { unexported string `qeury:"-"` Other string `query:"Other"` Int int `query:"int"` Ints []int `query:"ints"` Str string `query:"str"` Strs []string `query:"strs"` } err := BindStructToURLValues(&dst, "query", src) if err != nil { fmt.Println(err) } else { fmt.Printf("unexported=%s\n", dst.unexported) fmt.Printf("Other=%s\n", dst.Other) fmt.Printf("Int=%d\n", dst.Int) fmt.Printf("Ints=%d\n", dst.Ints) fmt.Printf("Str=%s\n", dst.Str) fmt.Printf("Strs=%s\n", dst.Strs) }
Output: unexported= Other= Int=1 Ints=[3 4] Str=a Strs=[c d]
func BindWithTag ¶
BindWithTag is used to bind dstptr to src, which uses the given tag to try to get the field name.
Types ¶
type Binder ¶
type Binder struct { // If true, convert src from slice/array, that's the first element, // to a single value on demand by the bound value. ConvertSliceToSingle bool // if true, convert src from a single value to slice/array on demand // by the bound value. ConvertSingleToSlice bool // GetFieldName is used to get the name and arg of the given field. // // If nil, use defaults.GetStructFieldName instead. // // If ignoring the field, return the empty string for the field name. // For the tag value, it maybe contain the argument, just like // type S struct { // OnlyName int `json:"fieldname"` // OnlyArg int `json:",fieldarg"` // NameAndArg int `json:"fieldname,fieldarg"` // NameAndArgs int `json:"fieldname,fieldarg1,fieldarg2"` // Ignore1 int `json:"-"` // Ignore2 int `json:"-,"` // } // // For the field argument, it only supports "squash" to squash // all the fields of the struct, just like the anonymous field. GetFieldName func(reflect.StructField) (name, arg string) // Hook is used to intercept the binding operation if set. // // If newsrc is not nil, the engine will continue to handle it. // Or, ignore it and go on to bind the next value. // So, if the hook has bound the value, return (nil, nil). // // Default: nil Hook Hook }
Binder is a common binder to bind a value to any.
In general, Binder is used to transform a value between different types.
func NewBinderWithHook ¶
NewBinderWithHook returns a default binder with the hook.
func (Binder) Bind ¶
Bind is used to bind the value dstptr to src.
In general, dstptr is a pointer to a contain variable. Moreover, dstptr may be a reflect.Value, but it must can be set or a pointer that the element can be set.
Support the types of the struct fields as follow:
- ~bool
- ~int
- ~int8
- ~int16
- ~int32
- ~int64
- ~uint
- ~uint8
- ~uint16
- ~uint32
- ~uint64
- ~string
- ~float32
- ~float64
- ~Array[E]
- ~Slice[E]
- ~Map[E]V
- time.Time
- time.Duration
- Struct
And any pointer to the types above, and the interfaces Unmarshaler and Setter.
type Decoder ¶ added in v0.2.0
type Decoder interface {
Decode(dst, src interface{}) error
}
Decoder is used to decode the data src to dst.
In general, Deocder is used to decode a byte stream to a type, such as struct or map.
var ( // It only supports to decode *http.Request with the tag "query" by default. DefaultQueryDecoder Decoder = DecoderFunc(func(dst, src interface{}) error { if req, ok := src.(*http.Request); ok { return BindStructToURLValues(dst, "query", req.URL.Query()) } return fmt.Errorf("binder.DefaultQueryDecoder: unsupport to decode %T", src) }) // It only supports to decode *http.Request with the tag "header" by default. DefaultHeaderDecoder Decoder = DecoderFunc(func(dst, src interface{}) error { if req, ok := src.(*http.Request); ok { return BindStructToHTTPHeader(dst, "header", req.Header) } return fmt.Errorf("binder.DefaultHeaderDecoder: unsupport to decode %T", src) }) // By default, during initializing the package, it will register // some decoders for the http request with the content-types: // - "application/xml" // - "application/json" // - "multipart/form-data" // - "application/x-www-form-urlencoded" // For the http request, it can be used like // DefaultMuxDecoder.Decode(dst, httpRequest). DefaultMuxDecoder = NewMuxDecoder() // It will use defaults.ValidateStruct to validate the struct value by default. DefaultStructValidationDecoder Decoder = StructValidationDecoder(nil) // Some encapsulated http decoders, which can be used directly. BodyDecoder Decoder = ComposeDecoders(DefaultMuxDecoder, DefaultStructValidationDecoder) QueryDecoder Decoder = ComposeDecoders(DefaultQueryDecoder, DefaultStructValidationDecoder) HeaderDecoder Decoder = ComposeDecoders(DefaultHeaderDecoder, DefaultStructValidationDecoder) )
Predefine some decoders to decode a value, such as body, query and header of the http request.
func ComposeDecoders ¶ added in v0.2.0
ComposeDecoders composes a group of decoders, which will be called in turn, to a Decoder.
func StructValidationDecoder ¶ added in v0.2.0
func StructValidationDecoder(validator assists.StructValidator) Decoder
StructValidationDecoder returns a struct validation decoder, which only validates whether the value dst is valid, not decodes any.
type DecoderFunc ¶ added in v0.2.0
type DecoderFunc func(dst, src interface{}) error
DecoderFunc is a function to decode the data src to dst.
func (DecoderFunc) Decode ¶ added in v0.2.0
func (f DecoderFunc) Decode(dst, src interface{}) error
Decode implements the interface Decoder.
type MuxDecoder ¶ added in v0.2.0
type MuxDecoder struct { // GetDecoder is used to get the deocder by the funciton get // with decoder that comes from src. // // If nil, use the default implementation, which inspects the decoder type // by the type of src, and supports the types as follow: // *http.Request: => Content-Type // interface{ DecodeType() string } // interface{ Type() string } GetDecoder func(src interface{}, get func(string) Decoder) (Decoder, error) // contains filtered or unexported fields }
MuxDecoder is a multiplexer for kinds of Decoders.
func NewMuxDecoder ¶ added in v0.2.0
func NewMuxDecoder() *MuxDecoder
NewMuxDecoder returns a new MuxDecoder.
func (*MuxDecoder) Add ¶ added in v0.2.0
func (md *MuxDecoder) Add(dtype string, decoder Decoder)
Add adds a decoder to decode the data of the given type.
func (*MuxDecoder) Decode ¶ added in v0.2.0
func (md *MuxDecoder) Decode(dst, src interface{}) (err error)
Decode implements the interface Decoder.
func (*MuxDecoder) Del ¶ added in v0.2.0
func (md *MuxDecoder) Del(dtype string)
Del removes the corresponding decoder by the type.
func (*MuxDecoder) Get ¶ added in v0.2.0
func (md *MuxDecoder) Get(dtype string) Decoder
Get returns the corresponding decoder by the type.
Return nil if not found.
type Setter ¶
type Setter interface {
Set(interface{}) error
}
Setter is an interface to set itself to the parameter.
type Unmarshaler ¶
type Unmarshaler interface {
UnmarshalBind(interface{}) error
}
Unmarshaler is an interface to unmarshal itself from the parameter.