-
Notifications
You must be signed in to change notification settings - Fork 8
/
http_wrapper.go
67 lines (56 loc) · 1.54 KB
/
http_wrapper.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
package abios
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"time"
"github.com/AbiosGaming/go-sdk-v2/v3/structs"
)
// performRequest creates the request, sends it and return the response's statuscode along
// with the response's body.
func performRequest(targetUrl string, params Parameters) (int, []byte, error) {
u, err := url.Parse(targetUrl)
if err != nil {
return 0, nil, err
}
u.RawQuery = params.encode()
httpReq := &http.Request{
Method: "GET",
URL: u,
Header: http.Header{
"Content-Type": {"application/x-www-form-urlencoded"},
},
}
return apiCall(httpReq)
}
// apiCall performs the actual http request and returns the resulting statuscode and body.
func apiCall(req *http.Request) (int, []byte, error) {
client := &http.Client{Timeout: 55 * time.Second}
resp, err := client.Do(req)
if err != nil {
return 0, nil, err
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return 0, nil, err
}
// If it is an error try to unmarshal it into a structs.Error.
// 410 still returns data in the expected format
if resp.StatusCode != 410 && (resp.StatusCode < 200 || 300 <= resp.StatusCode) {
target := structs.Error{}
err := json.Unmarshal(body, &target)
if err != nil {
return 0, nil, err
}
// We didn't manage to actually unmarshal into the struct. Create an error with what
// we have
if target.ErrorMessage == "" {
return resp.StatusCode, body, fmt.Errorf(string(body))
}
return resp.StatusCode, nil, target
}
return resp.StatusCode, body, nil
}