-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mailinabox.go
117 lines (89 loc) · 2.27 KB
/
mailinabox.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
package mailinabox
import (
"encoding/json"
"io"
"net/http"
"net/url"
"time"
"github.com/nrdcg/mailinabox/errutils"
)
type service struct {
client *Client
}
// Client the Mail-in-a-Box client.
type Client struct {
httpClient *http.Client
baseURL *url.URL
email string
password string
common service // Reuse a single struct instead of allocating one for each service on the heap.
DNS *DNSService
User *UserService
Mail *MailService
System *SystemService
}
// New creates a new Client.
func New(apiURL, email, password string) (*Client, error) {
baseURL, err := url.Parse(apiURL)
if err != nil {
return nil, err
}
client := &Client{
httpClient: &http.Client{Timeout: 10 * time.Second},
baseURL: baseURL,
email: email,
password: password,
}
client.common.client = client
client.DNS = (*DNSService)(&client.common)
client.User = (*UserService)(&client.common)
client.Mail = (*MailService)(&client.common)
client.System = (*SystemService)(&client.common)
return client, nil
}
func (c *Client) doJSON(req *http.Request, result any) error {
req.SetBasicAuth(c.email, c.password)
req.Header.Set("Accept", "application/json")
resp, err := c.httpClient.Do(req)
if err != nil {
return errutils.NewHTTPDoError(req, err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return errutils.NewUnexpectedResponseStatusCodeError(req, resp)
}
if result == nil {
return nil
}
raw, err := io.ReadAll(resp.Body)
if err != nil {
return errutils.NewReadResponseError(req, resp.StatusCode, err)
}
err = json.Unmarshal(raw, result)
if err != nil {
return errutils.NewUnmarshalError(req, resp.StatusCode, raw, err)
}
return nil
}
func (c *Client) doPlain(req *http.Request) ([]byte, error) {
req.SetBasicAuth(c.email, c.password)
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, errutils.NewHTTPDoError(req, err)
}
defer func() { _ = resp.Body.Close() }()
if resp.StatusCode != http.StatusOK {
return nil, errutils.NewUnexpectedResponseStatusCodeError(req, resp)
}
raw, err := io.ReadAll(resp.Body)
if err != nil {
return nil, errutils.NewReadResponseError(req, resp.StatusCode, err)
}
return raw, nil
}
func boolToIntStr(v bool) string {
if v {
return "1"
}
return "0"
}