forked from plivo/plivo-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
baseclient.go
171 lines (139 loc) · 4.37 KB
/
baseclient.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
package plivo
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"github.com/google/go-querystring/query"
)
const sdkVersion = "7.2.2"
const lookupBaseUrl = "lookup.plivo.com"
type ClientOptions struct {
HttpClient *http.Client
}
type BaseClient struct {
httpClient *http.Client
AuthId string
AuthToken string
BaseUrl *url.URL
userAgent string
RequestInterceptor func(request *http.Request)
ResponseInterceptor func(response *http.Response)
}
func (client *BaseClient) NewRequest(method string, params interface{}, baseRequestString string, formatString string,
formatParams ...interface{}) (request *http.Request, err error) {
if client == nil || client.httpClient == nil {
err = errors.New("client and httpClient cannot be nil")
return
}
isCallInsightsRequest := false
var requestPath string
for i, param := range formatParams {
if !isCallInsightsRequest {
isCallInsightsRequest, requestPath = checkAndFetchCallInsightsRequestDetails(param)
}
if param == nil || param == "" {
err = errors.New(fmt.Sprintf("Request path parameter #%d is nil/empty but should not be so.", i))
return
}
}
requestUrl := *client.BaseUrl
requestUrl.Path = fmt.Sprintf(baseRequestString, fmt.Sprintf(formatString, formatParams...))
if isCallInsightsRequest {
requestUrl.Host = CallInsightsBaseURL
requestUrl.Path = requestPath
}
var buffer = new(bytes.Buffer)
if method == "GET" {
var values url.Values
if values, err = query.Values(params); err != nil {
return
}
requestUrl.RawQuery = values.Encode()
} else {
if reflect.ValueOf(params).Kind().String() != "map" {
if err = json.NewEncoder(buffer).Encode(params); err != nil {
return
}
} else if reflect.ValueOf(params).Kind().String() == "map" && !reflect.ValueOf(params).IsNil() {
if err = json.NewEncoder(buffer).Encode(params); err != nil {
return
}
}
}
request, err = http.NewRequest(method, requestUrl.String(), buffer)
request.Header.Add("User-Agent", client.userAgent)
request.Header.Add("Content-Type", "application/json")
request.SetBasicAuth(client.AuthId, client.AuthToken)
return
}
func (client *BaseClient) ExecuteRequest(request *http.Request, body interface{}, extra ...map[string]interface{}) (err error) {
isVoiceRequest := false
if extra != nil {
if _, ok := extra[0]["is_voice_request"]; ok {
isVoiceRequest = true
if extra[0]["retry"] == 0 {
request.URL.Host = voiceBaseUrlString
request.Host = voiceBaseUrlString
request.URL.Scheme = HttpsScheme
} else if extra[0]["retry"] == 1 {
request.URL.Host = voiceBaseUrlStringFallback1
request.Host = voiceBaseUrlStringFallback2
request.URL.Scheme = HttpsScheme
} else if extra[0]["retry"] == 2 {
request.URL.Host = voiceBaseUrlStringFallback2
request.Host = voiceBaseUrlStringFallback2
request.URL.Scheme = HttpsScheme
}
}
if _, ok := extra[0]["is_lookup_request"]; ok {
if request.URL.Host == "api.plivo.com" { // hack for unit tests
request.URL.Host = lookupBaseUrl
request.Host = lookupBaseUrl
request.URL.Scheme = HttpsScheme
}
}
}
if client == nil {
return errors.New("client cannot be nil")
}
if client.httpClient == nil {
return errors.New("httpClient cannot be nil")
}
bodyCopy, _ := ioutil.ReadAll(request.Body)
request.Body = ioutil.NopCloser(bytes.NewReader(bodyCopy))
response, err := client.httpClient.Do(request)
if err != nil {
return
}
data, err := ioutil.ReadAll(response.Body)
if err == nil && data != nil && len(data) > 0 {
if isVoiceRequest && response.StatusCode >= 500 {
if extra[0]["retry"] == 2 {
err = errors.New(string(data))
return
}
extra[0]["retry"] = extra[0]["retry"].(int) + 1
newRequest, _ := http.NewRequest(request.Method, request.URL.String(), bytes.NewReader(bodyCopy))
newRequest.Header.Add("User-Agent", client.userAgent)
newRequest.Header.Add("Content-Type", "application/json")
newRequest.SetBasicAuth(client.AuthId, client.AuthToken)
_ = client.ExecuteRequest(newRequest, body, extra...)
} else if response.StatusCode >= 200 && response.StatusCode < 300 {
if body != nil {
err = json.Unmarshal(data, body)
}
} else {
if string(data) == "{}" && response.StatusCode == 404 {
err = errors.New("Resource not found exception \n" + response.Status)
} else {
err = errors.New(string(data))
}
}
}
return
}