-
Notifications
You must be signed in to change notification settings - Fork 1
/
init.go
80 lines (69 loc) · 1.52 KB
/
init.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
package adguard
import (
"fmt"
"io"
"net/http"
"time"
)
// ADG Client
type ADG struct {
HostURL string
HTTPClient *http.Client
Auth AuthStruct
}
// AuthStruct
type AuthStruct struct {
Username string `json:"username"`
Password string `json:"password"`
}
// NewClient
func NewClient(host, username, password, scheme *string, timeout *int) (*ADG, error) {
// sanity checks
if *host == "" {
return nil, fmt.Errorf("required parameter `host`")
}
if *username == "" {
return nil, fmt.Errorf("required parameter `username`")
}
if *password == "" {
return nil, fmt.Errorf("required parameter `password`")
}
if *scheme == "" {
*scheme = "https"
}
if *timeout == 0 {
*timeout = 10
}
// instantiate client
c := ADG{
HTTPClient: &http.Client{Timeout: time.Duration(*timeout) * time.Second},
HostURL: fmt.Sprintf("%s://%s/control", *scheme, *host),
}
// instantiate auth
c.Auth = AuthStruct{
Username: *username,
Password: *password,
}
return &c, nil
}
func (c *ADG) doRequest(req *http.Request) ([]byte, error) {
// add auth info to request
req.SetBasicAuth(c.Auth.Username, c.Auth.Password)
req.Header.Set("Content-Type", "application/json")
// perform request
res, err := c.HTTPClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
// parse body
body, err := io.ReadAll(res.Body)
if err != nil {
return nil, err
}
// sanity check
if res.StatusCode != http.StatusOK {
return nil, fmt.Errorf("status: %d, body: %s", res.StatusCode, body)
}
return body, err
}