-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
95 lines (78 loc) · 1.86 KB
/
client.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
package esi
import (
"encoding/json"
"io"
"io/ioutil"
"log"
"net/http"
"strings"
"time"
)
const (
protocol = "https"
host = "esi.tech.ccp.is"
version = "latest"
urlBase = protocol + "://" + host + "/" + version
userAgent = "esi-sdk-go"
source = "tranquility"
timeout = 5 * time.Second
)
type Client struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
}
func addDatasource(url string, source string) string {
if strings.Contains(url, "datasource=") {
log.Print("datasource already added")
return url
} else if strings.Contains(url, "?") {
url = url + "&"
} else {
url = url + "?"
}
return url + "datasource=" + source
}
func (c *Client) CreateRequest(method string, path string, body io.Reader,
useAuthorization bool) *http.Request {
url := urlBase + path
url = addDatasource(url, source)
req, err := http.NewRequest(method, url, body)
if err != nil {
log.Fatal(err)
}
req.Header.Add("User-Agent", userAgent)
req.Header.Add("Host", host)
if useAuthorization {
req.Header.Add("Authorization", "Bearer "+c.AccessToken)
}
return req
}
func PerformRequest(req *http.Request) *http.Response {
client := &http.Client{Timeout: timeout}
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
if resp.StatusCode != 200 {
log.Printf("Response code was %d.", resp.StatusCode)
if resp.Body != nil {
bodyBytes, _ := ioutil.ReadAll(resp.Body)
log.Printf("Body: %s.", bodyBytes)
}
for header, value := range resp.Header {
log.Printf("%s: %s", header, value)
}
}
return resp
}
func UnmarshalResponse(resp *http.Response, v interface{}) {
if resp.Body != nil {
bodyBytes, _ := ioutil.ReadAll(resp.Body)
err := json.Unmarshal(bodyBytes, v)
if err != nil {
log.Fatal(err)
}
}
}