-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhelpers.go
More file actions
97 lines (73 loc) · 1.96 KB
/
helpers.go
File metadata and controls
97 lines (73 loc) · 1.96 KB
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
package gowiraya
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"net/http"
)
func (c *WirayaClient) apiPostOld(endpoint string, body interface{}, data interface{}) error {
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(body)
req, err := http.NewRequest(http.MethodPost, c.baseUrlOldApi+endpoint, b)
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
req.Header.Add("X-ApiKey", c.xApiKey)
resp, err := c.HttpClientProxy.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(data)
}
func (c *WirayaClient) apiCallNew(httpMethod string, endpoint string, body interface{}, data interface{}) error {
bearerToken, err := c.getBearerToken()
if err != nil {
return err
}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(body)
req, err := http.NewRequest(httpMethod, c.baseUrlNewApi+endpoint, b)
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", bearerToken))
resp, err := c.HttpClient.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
return json.NewDecoder(resp.Body).Decode(data)
}
func (c *WirayaClient) getBearerToken() (string, error) {
body := AuthRequestKey{
Key: c.xApiKey,
}
b := new(bytes.Buffer)
json.NewEncoder(b).Encode(body)
req, err := http.NewRequest(http.MethodPost, c.baseUrlNewApi+"/auth/token/apikey", b)
if err != nil {
return "", err
}
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Accept", "application/json")
resp, err := c.HttpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
data := &TokenResponse{}
err = json.NewDecoder(resp.Body).Decode(data)
if err != nil {
return "", err
}
if data.Token == "" {
return "", errors.New("token returned was empty")
}
return data.Token, nil
}