-
Notifications
You must be signed in to change notification settings - Fork 4
/
goaxios_util.go
executable file
·88 lines (80 loc) · 1.74 KB
/
goaxios_util.go
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package goaxios
import (
"encoding/json"
"encoding/xml"
"errors"
"log"
"net/http"
"strings"
)
func (ga *GoAxios) validateBeforeRequest() error {
if ga.Url == "" {
return errors.New("url is required")
}
if ga.Method == "" {
return errors.New("method is required")
}
if ga.Body != nil || ga.Form != nil {
if ga.Method == "GET" {
return errors.New("body is not allowed for GET request")
}
if ga.Method == "DELETE" {
log.Default().Println("body may not be allowed for DELETE requests")
}
}
return nil
}
// marshalls the response body based on the content type and user-defined struct, if any.
func (ga *GoAxios) performResponseMarshalling(contentType string, response interface{}, data, body []byte, err error, res *http.Response) Response {
switch true {
case strings.Contains(contentType, "text/plain"):
if ga.ResponseStruct != nil {
err = json.Unmarshal(data, &response)
if err != nil {
return Response{
Response: res,
Bytes: body,
Body: response,
Error: err,
}
}
} else {
response = string(data)
}
case strings.Contains(contentType, "application/xml"):
if ga.ResponseStruct != nil {
err = xml.Unmarshal(data, &response)
if err != nil {
return Response{
Response: res,
Bytes: body,
Body: response,
Error: err,
}
}
} else {
response = string(data)
}
default:
err = json.Unmarshal(data, &response)
if err != nil {
if ga.ResponseStruct != nil {
return Response{
Response: res,
Bytes: body,
Body: response,
Error: err,
}
} else {
err = nil
response = string(data)
}
}
}
return Response{
Response: res,
Bytes: data,
Body: response,
Error: err,
}
}