-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttp.go
More file actions
233 lines (189 loc) · 6.03 KB
/
http.go
File metadata and controls
233 lines (189 loc) · 6.03 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
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
package directadmin
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
// debugBodyLimit caps the debug body bytes to 32KB.
const debugBodyLimit = 32768
type httpDebug struct {
Body string
BodyTruncated bool
Code int
Cookies []string
Endpoint string
Method string
Start time.Time
}
func (c *UserContext) getRequestURLNew(endpoint string) string {
return fmt.Sprintf("%s/api/%s", c.api.url, endpoint)
}
func (c *UserContext) getRequestURLOld(endpoint string) string {
return fmt.Sprintf("%s/CMD_%s", c.api.url, endpoint)
}
// makeRequest is the underlying function for HTTP requests. It handles debugging statements, and simple error handling.
func (c *UserContext) makeRequest(req *http.Request) ([]byte, error) {
var debugCookies []string
cookiesToSet := c.cookieJar.Cookies(req.URL)
sessionCookieSet := false
for _, cookie := range cookiesToSet {
req.AddCookie(cookie)
if cookie.Name == "csrftoken" {
req.Header.Set("X-CSRFToken", cookie.Value)
} else if cookie.Name == "session" {
sessionCookieSet = true
}
if c.api.debug {
debugCookies = append(debugCookies, cookie.String())
}
}
debug := httpDebug{
Cookies: debugCookies,
Endpoint: getPathWithQuery(req),
Method: req.Method,
Start: time.Now(),
}
defer c.api.printDebugHTTP(&debug)
if !sessionCookieSet {
req.SetBasicAuth(c.credentials.username, c.credentials.passkey)
}
resp, err := c.api.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if c.api.debug {
debug.Code = resp.StatusCode
}
// Required for plugin usage in particular (session and csrf token cookies).
for _, cookie := range resp.Cookies() {
c.cookieJar.SetCookies(req.URL, []*http.Cookie{cookie})
}
var responseBytes []byte
if resp.Body != nil {
responseBytes, err = io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("error reading response body: %w", err)
}
if c.api.debug {
if len(responseBytes) > debugBodyLimit {
debug.BodyTruncated = true
debug.Body = string(responseBytes[:debugBodyLimit])
} else {
debug.Body = string(responseBytes)
}
}
}
if resp.StatusCode/100 != 2 {
return responseBytes, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
return responseBytes, nil
}
// makeRequestNew supports DirectAdmin's new API.
func (c *UserContext) makeRequestNew(method string, endpoint string, body any, object any) ([]byte, error) {
var bodyBytes []byte
if body != nil {
var err error
bodyBytes, err = json.Marshal(body)
if err != nil {
return nil, fmt.Errorf("error serializing body: %w", err)
}
}
req, err := http.NewRequest(strings.ToUpper(method), c.getRequestURLNew(endpoint), bytes.NewBuffer(bodyBytes))
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
query := req.URL.Query()
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Referer", c.api.url)
req.URL.RawQuery = query.Encode()
resp, err := c.makeRequest(req)
if err != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
if resp != nil && object != nil {
if err = json.Unmarshal(resp, &object); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %w", err)
}
}
return resp, nil
}
// makeRequestOld supports DirectAdmin's old API.
func (c *UserContext) makeRequestOld(method string, endpoint string, body url.Values, object any) ([]byte, error) {
req, err := http.NewRequest(strings.ToUpper(method), c.getRequestURLOld(endpoint), strings.NewReader(body.Encode()))
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
query := req.URL.Query()
query.Add("json", "yes")
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Referer", c.api.url)
req.URL.RawQuery = query.Encode()
var genericResponse apiGenericResponse
resp, err := c.makeRequest(req)
if err != nil {
jsonErr := json.Unmarshal(resp, &genericResponse)
if jsonErr != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
return nil, errors.New(genericResponse.Error + ": " + genericResponse.Result)
}
if resp != nil {
if object != nil {
if err = json.Unmarshal(resp, &object); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %w", err)
}
} else if err = json.Unmarshal(resp, &genericResponse); err == nil && genericResponse.Error != "" {
return nil, errors.New(genericResponse.Error + ": " + genericResponse.Result)
}
}
return resp, nil
}
// uploadFile functions for either the old or new DA API.
func (c *UserContext) uploadFile(method string, endpoint string, data []byte, object any, contentType string) ([]byte, error) {
req, err := http.NewRequest(strings.ToUpper(method), c.api.url+endpoint, bytes.NewBuffer(data))
if err != nil {
return nil, fmt.Errorf("error creating request: %w", err)
}
query := req.URL.Query()
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", contentType)
req.Header.Set("Referer", c.api.url)
req.URL.RawQuery = query.Encode()
resp, err := c.makeRequest(req)
if err != nil {
return nil, fmt.Errorf("error making request: %w", err)
}
if len(resp) > 0 && object != nil {
if err = json.Unmarshal(resp, &object); err != nil {
return nil, fmt.Errorf("error unmarshalling response: %w", err)
}
}
return resp, nil
}
func (a *API) printDebugHTTP(debug *httpDebug) {
if a.debug {
var bodyTruncated string
if debug.BodyTruncated {
bodyTruncated = " (truncated)"
}
fmt.Printf("\nENDPOINT: %v %v\nSTATUS CODE: %v\nTIME STARTED: %v\nTIME ENDED: %v\nTIME TAKEN: %v\nCOOKIES: %s\nRESP BODY%s: %v\n", debug.Method, debug.Endpoint, debug.Code, debug.Start, time.Now(), time.Since(debug.Start), strings.Join(debug.Cookies, ";"), bodyTruncated, debug.Body)
}
}
func getPathWithQuery(req *http.Request) string {
if req == nil {
return ""
}
if req.URL.RawQuery != "" {
return req.URL.Path + "?" + req.URL.RawQuery
}
return req.URL.Path
}