1 // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
2 // Use of this source code is governed by a MIT style
3 // license that can be found in the LICENSE file.
9 // Content-Type MIME of the most common data formats.
11 MIMEJSON = "application/json"
12 MIMEHTML = "text/html"
13 MIMEXML = "application/xml"
15 MIMEPlain = "text/plain"
16 MIMEPOSTForm = "application/x-www-form-urlencoded"
17 MIMEMultipartPOSTForm = "multipart/form-data"
18 MIMEPROTOBUF = "application/x-protobuf"
19 MIMEMSGPACK = "application/x-msgpack"
20 MIMEMSGPACK2 = "application/msgpack"
23 // Binding describes the interface which needs to be implemented for binding the
24 // data present in the request such as JSON request body, query parameters or
26 type Binding interface {
28 Bind(*http.Request, interface{}) error
31 // BindingBody adds BindBody method to Binding. BindBody is similar with Bind,
32 // but it reads the body from supplied bytes instead of req.Body.
33 type BindingBody interface {
35 BindBody([]byte, interface{}) error
38 // StructValidator is the minimal interface which needs to be implemented in
39 // order for it to be used as the validator engine for ensuring the correctness
40 // of the reqest. Gin provides a default implementation for this using
41 // https://github.com/go-playground/validator/tree/v8.18.2.
42 type StructValidator interface {
43 // ValidateStruct can receive any kind of type and it should never panic, even if the configuration is not right.
44 // If the received type is not a struct, any validation should be skipped and nil must be returned.
45 // If the received type is a struct or pointer to a struct, the validation should be performed.
46 // If the struct is not valid or the validation itself fails, a descriptive error should be returned.
47 // Otherwise nil must be returned.
48 ValidateStruct(interface{}) error
50 // Engine returns the underlying validator engine which powers the
51 // StructValidator implementation.
55 // Validator is the default validator which implements the StructValidator
56 // interface. It uses https://github.com/go-playground/validator/tree/v8.18.2
58 var Validator StructValidator = &defaultValidator{}
60 // These implement the Binding interface and can be used to bind the data
61 // present in the request to struct instances.
66 Query = queryBinding{}
67 FormPost = formPostBinding{}
68 FormMultipart = formMultipartBinding{}
69 ProtoBuf = protobufBinding{}
70 MsgPack = msgpackBinding{}
73 // Default returns the appropriate Binding instance based on the HTTP method
74 // and the content type.
75 func Default(method, contentType string) Binding {
83 case MIMEXML, MIMEXML2:
87 case MIMEMSGPACK, MIMEMSGPACK2:
89 default: //case MIMEPOSTForm, MIMEMultipartPOSTForm:
94 func validate(obj interface{}) error {
98 return Validator.ValidateStruct(obj)