-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
69 lines (63 loc) · 1.86 KB
/
http.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
package mytokenlib
import (
"bytes"
"encoding/json"
"net/http"
"github.com/oidc-mytoken/api/v0"
)
const (
errSendingHttpRequest = "error while sending http request"
errDecodingHttpResponse = "could not decode response"
errDecodingErrorResponse = "could not decode error response"
errEncodingRequest = "could not encode request"
)
const mimetypeJSON = "application/json"
func doHTTPRequest(method, url string, reqBody, responseData interface{}) error {
return doHTTPRequestWithAuth(method, url, reqBody, responseData, "")
}
func doHTTPRequestWithAuth(
method, url string, reqBody interface{}, responseData interface{},
bearerAuth string,
) error {
b := new(bytes.Buffer)
if err := json.NewEncoder(b).Encode(reqBody); err != nil {
return newMytokenErrorFromError(errEncodingRequest, err)
}
req, err := http.NewRequestWithContext(ctx, method, url, b)
if err != nil {
return newMytokenErrorFromError(errSendingHttpRequest, err)
}
if userAgent != "" {
req.Header.Set("User-Agent", userAgent)
}
if reqBody != nil {
req.Header.Set("Content-Type", mimetypeJSON)
}
if responseData != nil {
req.Header.Set("Accept", mimetypeJSON)
}
if bearerAuth != "" {
req.Header.Set("Authorization", "Bearer "+bearerAuth)
}
resp, err := httpClient.Do(req)
if err != nil {
return newMytokenErrorFromError(errSendingHttpRequest, err)
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
var apiError api.Error
if err = json.NewDecoder(resp.Body).Decode(&apiError); err != nil {
return newMytokenErrorFromError(errDecodingErrorResponse, err)
}
return MytokenError{
err: apiError.Error,
errorDetails: apiError.ErrorDescription,
}
}
if responseData != nil && resp.ContentLength != 0 {
if err = json.NewDecoder(resp.Body).Decode(responseData); err != nil {
return newMytokenErrorFromError(errDecodingHttpResponse, err)
}
}
return nil
}