func (cd *ContentTypeDecoders) DecodeBody(req *rest.Request, trace retrace.Tracer) error { switch req.Raw.Method { case "GET", "DELETE", "HEAD": return nil } ctype := req.Raw.Header["Content-Type"] decoder := cd.Get(ctype) //new empty instance body := req.Definition.RequestBody() var bts []byte var err error if bts, err = req.Bytes(); err != nil { return err } if body != nil { if isBytes(reflect.TypeOf(body)) { //if body type is castable to []byte, then we don't encode, just set directly req.Body = bts return nil } else if decoder != nil { decoder.Decode(bytes.NewReader(bts), &body, trace) req.Body = body } else if containsType(ctype, "application/x-www-form-urlencoded") { req.Raw.ParseForm() if err := util.MapHeaderToStruct(req.Raw.Form, &body); err != nil { return err } trace.Annotate(retrace.FromRequestData, "body", fmt.Sprintf("%+v", body)) req.Body = body } else { if err = json.Unmarshal(bts, &body); err != nil { return err } trace.Annotate(retrace.FromRequestData, "body", fmt.Sprintf("%s", bts)) req.Body = body } } return nil }
import ( "bytes" "io/ioutil" "net/http" "reflect" "github.com/gotgo/resti/rest" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) var _ = Describe("Request", func() { var request *rest.Request BeforeEach(func() { def := &rest.ResourceDef{ ResourceArgs: reflect.TypeOf(rest.IdIntArg{}), } ct := []string{"application/json"} request = rest.NewRequest(&http.Request{}, &rest.RequestContext{}, rest.NewServerResource(def, ct, ct)) }) It("should DecodeArgs", func() { v := make(map[string]string) v["id"] = "9" err := request.DecodeArgs(v) Expect(err).To(BeNil())