123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155 |
- package binding
- import "net/http"
- const (
- MIMEJSON = "application/json"
- MIMEHTML = "text/html"
- MIMEXML = "application/xml"
- MIMEXML2 = "text/xml"
- MIMEPlain = "text/plain"
- MIMEPOSTForm = "application/x-www-form-urlencoded"
- MIMEMultipartPOSTForm = "multipart/form-data"
- MIMEPROTOBUF = "application/x-protobuf"
- MIMEMSGPACK = "application/x-msgpack"
- MIMEMSGPACK2 = "application/msgpack"
- MIMEYAML = "application/x-yaml"
- )
- type Binding interface {
- Name() string
- Bind(*http.Request, interface{}) error
- }
- type BindingBody interface {
- Binding
- BindBody([]byte, interface{}) error
- }
- type BindingUri interface {
- Name() string
- BindUri(map[string][]string, interface{}) error
- }
- type StructValidator interface {
-
-
-
-
-
- ValidateStruct(interface{}) error
-
-
- Engine() interface{}
- }
- var (
- JSON = jsonBinding{}
- XML = xmlBinding{}
- Form = formBinding{}
- Query = queryBinding{}
- FormPost = formPostBinding{}
- FormMultipart = formMultipartBinding{}
- ProtoBuf = protobufBinding{}
- MsgPack = msgpackBinding{}
- YAML = yamlBinding{}
- Uri = uriBinding{}
- )
- func Default(method, contentType string) Binding {
- if method == "GET" {
- return Form
- }
- switch contentType {
- case MIMEJSON:
- return JSON
- case MIMEXML, MIMEXML2:
- return XML
- case MIMEPROTOBUF:
- return ProtoBuf
- case MIMEMSGPACK, MIMEMSGPACK2:
- return MsgPack
- case MIMEYAML:
- return YAML
- case MIMEMultipartPOSTForm:
- return FormMultipart
- default:
- return Form
- }
- }
- func validate(obj interface{}) error {
- return nil
-
- }
- func Bind(req *http.Request, obj interface{}) error {
- b := Default(req.Method, ContentType(req))
- return MustBindWith(req, obj, b)
- }
- func BindQuery(req *http.Request, obj interface{}) error {
- return MustBindWith(req, obj, Form)
- }
- func MustBindWith(req *http.Request, obj interface{}, b Binding) (err error) {
- return b.Bind(req, obj)
- }
- func ContentType(req *http.Request) string {
- return filterFlags(req.Header.Get("Content-Type"))
- }
- func filterFlags(content string) string {
- for i, char := range content {
- if char == ' ' || char == ';' {
- return content[:i]
- }
- }
- return content
- }
|