github.com/machinebox/remoto@v0.1.2-0.20191024144331-eff21a7d321f/go/remotohttp/decode.go (about) 1 package remotohttp 2 3 import ( 4 "encoding/json" 5 "net/http" 6 "strings" 7 8 "github.com/pkg/errors" 9 ) 10 11 // Decode extracts the incoming data from the http.Request. 12 func Decode(r *http.Request, v interface{}) error { 13 contentType := strings.ToLower(r.Header.Get("Content-Type")) 14 switch { 15 case strings.Contains(contentType, "application/json"): 16 return decodeJSON(r, v) 17 case strings.Contains(contentType, "application/x-www-form-urlencoded"), 18 strings.Contains(contentType, "multipart/form-data"): 19 return decodeFormdata(r, v) 20 } 21 return errors.New("unsupported Content-Type (use application/json, application/x-www-form-urlencoded or multipart/form-data)") 22 } 23 24 func decodeJSON(r *http.Request, v interface{}) error { 25 if err := json.NewDecoder(r.Body).Decode(v); err != nil { 26 return errors.Wrap(err, "decode json") 27 } 28 return nil 29 } 30 31 func decodeFormdata(r *http.Request, v interface{}) error { 32 j := r.FormValue("json") 33 if j == "" { 34 return errors.New("missing field: json") 35 } 36 if err := json.Unmarshal([]byte(j), v); err != nil { 37 return errors.Wrap(err, "decode json") 38 } 39 return nil 40 }