-
Notifications
You must be signed in to change notification settings - Fork 1
/
httprequest.go
71 lines (57 loc) · 1.57 KB
/
httprequest.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
package biteship
import (
"encoding/json"
"io"
"net/http"
)
type IHttpRequest interface {
Call(method string, url string, secretKey string, body io.Reader, result interface{}) *Error
}
type HttpRequest struct{}
func NewHttp() IHttpRequest {
return &HttpRequest{}
}
func (client *HttpRequest) Call(method string, url string, secretKey string, body io.Reader, result interface{}) *Error {
if secretKey == "" {
return &Error{
Status: http.StatusUnauthorized,
Message: "missing/invalid secret key",
}
}
req, errNewReq := http.NewRequest(method, url, body)
if errNewReq != nil {
return &Error{
Status: http.StatusInternalServerError,
Message: "Cannot create request",
RawError: errNewReq.Error(),
}
}
req.Header.Add("Authorization", secretKey)
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
return client.doRequest(req, result)
}
func (client *HttpRequest) doRequest(req *http.Request, result interface{}) *Error {
httpClient := &http.Client{}
response, errRequest := httpClient.Do(req)
if errRequest != nil {
return ErrorGo(errRequest)
}
defer func() {
if err := response.Body.Close(); err != nil {
panic(err)
}
}()
respBody, errRead := io.ReadAll(response.Body)
if errRead != nil {
return ErrorGo(errRead)
}
if response.StatusCode < http.StatusOK || response.StatusCode >= http.StatusMultipleChoices {
return ErrorHttp(response.StatusCode, respBody)
}
errUnmarshall := json.Unmarshal(respBody, &result)
if errUnmarshall != nil {
return ErrorGo(errUnmarshall)
}
return nil
}