-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathinit.go
90 lines (79 loc) · 1.89 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
81
82
83
84
85
86
87
88
89
90
package adguard
import (
"crypto/tls"
"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, enableInsecureSkipVerify ...*bool) (*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
}
// default for insecureSkipVerify
insecureSkipVerify := false
if len(enableInsecureSkipVerify) > 0 {
insecureSkipVerify = *enableInsecureSkipVerify[0]
}
// create custom transport based on insecureSkipVerify
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: insecureSkipVerify},
}
// instantiate client
c := ADG{
HTTPClient: &http.Client{Timeout: time.Duration(*timeout) * time.Second, Transport: tr},
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
}