Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Force content type during MakeRequest() #216

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
}