-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent_type.go
More file actions
48 lines (43 loc) · 1.29 KB
/
content_type.go
File metadata and controls
48 lines (43 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
package grequests
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"reflect"
)
// DetectContentType method is used to figure out `Request.Body` content type for request header
func DetectContentType(body interface{}) string {
contentType := plainTextType
kind := reflect.Indirect(reflect.ValueOf(body)).Kind()
switch kind {
case reflect.Struct, reflect.Slice, reflect.Map:
contentType = jsonContentType
case reflect.String:
contentType = plainTextType
default:
}
return contentType
}
func handleRequestBody(opt *Options, body interface{}) (*bytes.Buffer, error) {
if body == nil {
return new(bytes.Buffer), nil
}
contentType := opt.Header.Get(HeaderContentType)
if IsStringEmpty(contentType) {
contentType = DetectContentType(body)
opt.Header.Set(HeaderContentType, contentType)
}
bodyBytes, err := []byte{}, (error)(nil)
kind := reflect.Indirect(reflect.ValueOf(body)).Kind()
if reader, ok := body.(io.Reader); ok {
bodyBytes, err = ioutil.ReadAll(reader)
} else if b, ok := body.([]byte); ok {
bodyBytes = b
} else if s, ok := body.(string); ok {
bodyBytes = []byte(s)
} else if IsJSONContentType(contentType) && (kind == reflect.Struct || kind == reflect.Map || kind == reflect.Slice) {
bodyBytes, err = json.Marshal(body)
}
return bytes.NewBuffer(bodyBytes), err
}