Skip to content

Commit

Permalink
fixed parnurzeal#204: force content type during MakeRequest()
Browse files Browse the repository at this point in the history
  • Loading branch information
anggorodewanto committed Feb 7, 2019
1 parent b060445 commit f73fe13
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 14 deletions.
29 changes: 15 additions & 14 deletions gorequest.go
Original file line number Diff line number Diff line change
Expand Up @@ -1148,20 +1148,6 @@ func (s *SuperAgent) getResponseBytes() (Response, []byte, []error) {
if len(s.Errors) != 0 {
return nil, nil, s.Errors
}
// check if there is forced type
switch s.ForceType {
case TypeJSON, TypeForm, TypeXML, TypeText, TypeMultipart:
s.TargetType = s.ForceType
// If forcetype is not set, check whether user set Content-Type header.
// If yes, also bounce to the correct supported TargetType automatically.
default:
contentType := s.Header.Get("Content-Type")
for k, v := range Types {
if contentType == v {
s.TargetType = k
}
}
}

// if slice and map get mixed, let's bounce to rawstring
if len(s.Data) != 0 && len(s.SliceData) != 0 {
Expand Down Expand Up @@ -1241,6 +1227,21 @@ func (s *SuperAgent) MakeRequest() (*http.Request, error) {
return nil, errors.New("No method specified")
}

// check if there is forced type
switch s.ForceType {
case TypeJSON, TypeForm, TypeXML, TypeText, TypeMultipart:
s.TargetType = s.ForceType
// If forcetype is not set, check whether user set Content-Type header.
// If yes, also bounce to the correct supported TargetType automatically.
default:
contentType := s.Header.Get("Content-Type")
for k, v := range Types {
if contentType == v {
s.TargetType = k
}
}
}

// !!! Important Note !!!
//
// Throughout this region, contentReader and contentType are only set when
Expand Down
18 changes: 18 additions & 0 deletions gorequest_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2569,3 +2569,21 @@ func TestSetDebugByEnvironmentVar(t *testing.T) {
t.Fatalf("\nExpected gorequest not to log request and response object if GOREQUEST_DEBUG is not set.")
}
}

func TestForceContentType(t *testing.T) {
endpoint := "http://github.com/parnurzeal/gorequest"

request, err := New().
Post(endpoint).
Type(TypeJSON).
SendString(`notJSON`).
MakeRequest()

if err != nil {
t.Errorf("Error is not nil: %v", err)
}

if contentType := request.Header.Get("Content-Type"); contentType != Types[TypeJSON] {
t.Errorf("Content-Type is not JSON: %v", contentType)
}
}

0 comments on commit f73fe13

Please sign in to comment.