Browse Source

default bind

ls 3 years ago
parent
commit
700220ad3a
1 changed files with 34 additions and 0 deletions
  1. 34 0
      binding/binding.go

+ 34 - 0
binding/binding.go

@@ -75,3 +75,37 @@ func Default(method, contentType string) Binding {
 func validate(obj interface{}) error {
 	return nil
 }
+
+// Bind checks the Content-Type to select a binding engine automatically,
+// Depending the "Content-Type" header different bindings are used:
+//     "application/json" --> JSON binding
+//     "application/xml"  --> XML binding
+// otherwise --> returns an error.
+// It parses the request's body as JSON if Content-Type == "application/json" using JSON or XML as a JSON input.
+// It decodes the json payload into the struct specified as a pointer.
+// It writes a 400 error and sets Content-Type header "text/plain" in the response if input is not valid.
+func Bind(req *http.Request, obj interface{}) error {
+	b := Default(req.Method, ContentType(req))
+	return MustBindWith(req, obj, b)
+}
+
+// MustBindWith binds the passed struct pointer using the specified binding engine.
+// It will abort the request with HTTP 400 if any error occurs.
+// See the binding package.
+func MustBindWith(req *http.Request, obj interface{}, b Binding) (err error) {
+	return b.Bind(req, obj)
+}
+
+// ContentType returns the Content-Type header of the request.
+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
+}