MCPcopy Index your code
hub / github.com/go-spring/go-spring / decodeBody

Function decodeBody

stdlib/httpsvr/handler.go:77–129  ·  view source on GitHub ↗

decodeBody reads and decodes the request body into the given RequestObject based on Content-Type.

(r *http.Request, i RequestObject)

Source from the content-addressed store, hash-verified

75// decodeBody reads and decodes the request body into the given
76// RequestObject based on Content-Type.
77func decodeBody(r *http.Request, i RequestObject) error {
78
79 b, err := ReadBody(r)
80 if err != nil {
81 return err
82 }
83
84 contentType := r.Header.Get("Content-Type")
85 mediaType, _, _ := mime.ParseMediaType(contentType)
86
87 var asJSON bool
88 switch mediaType {
89 case "application/json":
90 asJSON = true
91 case "application/x-www-form-urlencoded":
92 asJSON = false
93 default:
94 if b = bytes.TrimSpace(b); len(b) == 0 {
95 return nil
96 }
97 if b[0] == '{' || b[0] == '[' { // Looks like JSON
98 asJSON = true
99 } else {
100 asJSON = false
101 }
102 }
103
104 if asJSON {
105 d := jsonflow.NewDecoder(bytes.NewReader(b))
106 v, ok := i.(interface {
107 DecodeJSON(d jsonflow.Decoder) error
108 })
109 if !ok {
110 return errutil.Explain(nil, "decode form error: not a DecodeJSON implementer")
111 }
112 if err = v.DecodeJSON(d); err != nil {
113 return errutil.Explain(err, "json decode error")
114 }
115 if err = jsonflow.DecodeEOF(d); err != nil {
116 return errutil.Explain(err, "json decode error")
117 }
118 } else {
119 v, ok := i.(interface{ DecodeForm(b []byte) error })
120 if !ok {
121 return errutil.Explain(nil, "decode form error: not a DecodeForm implementer")
122 }
123 if err = v.DecodeForm(b); err != nil {
124 return errutil.Explain(err, "decode form error")
125 }
126 }
127
128 return nil
129}
130
131// ReadRequest parses the request body based on Content-Type and
132// decodes it into the given RequestObject.

Callers 1

ReadRequestFunction · 0.85

Calls 3

DecodeJSONMethod · 0.65
GetMethod · 0.45
DecodeFormMethod · 0.45

Tested by

no test coverage detected