-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi.go
189 lines (143 loc) · 3.69 KB
/
api.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"time"
)
type ApiClient struct {
Client *http.Client
Gateway string
Token string
Timeout time.Duration
UseTls bool
}
const DefaultTimeout = 5
type Credentials struct {
Username string `json:"username"`
Password string `json:"password"`
}
func NewApiClient(gateway string) *ApiClient {
return &ApiClient{
Client: &http.Client{},
Gateway: gateway,
Timeout: DefaultTimeout * time.Second,
}
}
func (ac *ApiClient) Login(username, password string) (err error) {
ac.Token = ""
response, err := ac.DoRequest("signin", Credentials{username, password})
if err != nil {
err = fmt.Errorf("login request failed: %w", err)
return
}
var token AuthTokenAnswer
err = json.Unmarshal(response, &token)
if err != nil {
err = fmt.Errorf("could not parse token from login answer: %w", err)
return
}
ac.Token = token.Token
return
}
func (ac *ApiClient) DoLegacyRequest(mode string,
to string,
text string,
username string,
password string) error {
params := url.Values{}
if mode == "contactgroup" {
params.Add("mode", "group")
} else if mode == "contact" {
params.Add("mode", "user")
} else {
params.Add("mode", "number")
}
params.Add("to", to)
params.Add("text", text)
params.Add("username", username)
params.Add("password", password)
schema := "http://"
if ac.UseTls {
schema = "https://"
}
myUrl := schema + ac.Gateway + "/api.php" + "?" + params.Encode()
// Setup Timeout context
ctx, cancel := context.WithTimeout(context.Background(), ac.Timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "GET", myUrl, nil)
if err != nil {
return err
}
resp, err := ac.Client.Do(req)
if err != nil {
// We want to override the context error message to be more expressive
if errors.Is(err, context.DeadlineExceeded) {
return fmt.Errorf("timeout during HTTP request: %w", err)
}
return fmt.Errorf("executing API request failed: %w", err)
}
respBody, err := io.ReadAll(resp.Body)
if err != nil {
err = fmt.Errorf("reading API response failed: %w\nBody: %s", err, respBody)
return err
}
resp.Body.Close()
if resp.StatusCode != 200 {
err = fmt.Errorf("API request failed with status %d", resp.StatusCode)
return err
}
return nil
}
func (ac *ApiClient) DoRequest(rawUrl string, body interface{}) (respBody []byte, err error) {
// Build request body as JSON
var buf bytes.Buffer
j := json.NewEncoder(&buf)
err = j.Encode(body)
if err != nil {
err = fmt.Errorf("could not build JSON request data: %w", err)
return
}
// Setup Timeout context
ctx, cancel := context.WithTimeout(context.Background(), ac.Timeout)
defer cancel()
schema := "http://"
if ac.UseTls {
schema = "https://"
}
// Build Request
baseUrl := schema + ac.Gateway + "/api/"
req, err := http.NewRequestWithContext(ctx, "POST", baseUrl+rawUrl, &buf)
if err != nil {
return []byte(""), err
}
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
if ac.Token != "" {
req.Header.Add("Authorization", "Bearer "+ac.Token)
}
resp, err := ac.Client.Do(req)
if err != nil {
// We want to override the context error message to be more expressive
if errors.Is(err, context.DeadlineExceeded) {
return []byte(""), fmt.Errorf("timeout during HTTP request: %w", err)
}
return []byte(""), fmt.Errorf("executing API request failed: %w", err)
}
respBody, err = io.ReadAll(resp.Body)
if err != nil {
err = fmt.Errorf("reading API response failed: %w", err)
return
}
resp.Body.Close()
if resp.StatusCode != 200 {
err = fmt.Errorf("API request failed with status %d", resp.StatusCode)
return
}
return
}