/
web.go
278 lines (214 loc) · 5.56 KB
/
web.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
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
package web
import (
"bytes"
"compress/gzip"
"context"
"errors"
"fmt"
"io"
"mime"
"net"
"net/http"
"net/netip"
"net/url"
"os"
"path/filepath"
"strings"
"time"
"github.com/jonhadfield/ip-fetcher/internal/pflog"
"github.com/hashicorp/go-retryablehttp"
"github.com/sirupsen/logrus"
)
func Resolve(name string) (ip netip.Addr, err error) {
i, err := net.ResolveIPAddr("ip", name)
if err != nil {
return
}
return netip.ParseAddr(i.String())
}
func NewHTTPClient() *retryablehttp.Client {
rc := &http.Client{Transport: &http.Transport{}}
c := retryablehttp.NewClient()
c.HTTPClient = rc
c.RetryMax = 2
c.RetryWaitMin = 2 * time.Second
c.RetryWaitMax = 5 * time.Second
return c
}
func MaskSecrets(content string, secret []string) string {
for _, s := range secret {
content = strings.ReplaceAll(content, s, strings.Repeat("*", len(s)))
}
return content
}
func Request(c *retryablehttp.Client, url string, method string, inHeaders http.Header, secrets []string, timeout time.Duration) (body []byte, headers http.Header, status int, err error) {
if method == "" {
err = fmt.Errorf("HTTP method not specified")
return
}
request, err := retryablehttp.NewRequest(method, url, nil)
if err != nil {
err = fmt.Errorf("failed to request %s: %w", MaskSecrets(url, secrets), err)
return
}
request.Header = inHeaders
ctx := context.Background()
var cancel context.CancelFunc
if timeout != 0 {
ctx, cancel = context.WithTimeout(context.Background(), timeout)
defer cancel()
}
request = request.WithContext(ctx)
var resp *http.Response
resp, err = c.Do(request)
if err != nil {
return
}
headers = resp.Header
body, err = GetResponseBody(resp)
if err != nil {
err = fmt.Errorf("%w", err)
return
}
defer resp.Body.Close()
return body, resp.Header, resp.StatusCode, err
}
// GetResourceHeaderValue will make an HTTP request and return the value of the specified header
func GetResourceHeaderValue(client *retryablehttp.Client, url, method, header string, secrets []string) (result string, err error) {
if header == "" {
return "", fmt.Errorf("header must not be empty")
}
_, response, _, err := Request(client, url, method, nil, secrets, 30*time.Second)
return response.Get(header), err
}
type pathDetailsOutput struct {
found, parentFound, isDir bool
parent string
mode os.FileMode
}
func pathDetails(path string) (output pathDetailsOutput, err error) {
f, err := os.Stat(path)
if err != nil {
// if we have an error other than it not existing, then fail
if !os.IsNotExist(err) {
return
}
} else {
parentPath := path
if !f.IsDir() {
parentPath = filepath.Dir(path)
}
return pathDetailsOutput{
found: true,
parentFound: true,
isDir: f.IsDir(),
parent: parentPath,
mode: f.Mode(),
}, nil
}
// path isn't found, so check if it's would-be parent exists
parent := filepath.Dir(path)
f, err = os.Stat(parent)
if err != nil {
if os.IsNotExist(err) {
return pathDetailsOutput{
found: false,
parentFound: false,
isDir: false,
parent: "",
mode: 0,
}, nil
}
// return unexpected error
return
}
// return would-be file's parent
return pathDetailsOutput{
found: false,
parentFound: true,
isDir: false,
parent: parent,
mode: f.Mode(),
}, nil
}
func DownloadFile(client *retryablehttp.Client, u, path string) (downloadedFilePath string, err error) {
if u == "" {
return "", fmt.Errorf("path must not be empty")
}
logrus.Debugf("%s | downloading: %s to %s", pflog.GetFunctionName(), u, path)
details, err := pathDetails(path)
if err != nil {
return
}
// default download path to that provided
if details.found {
downloadedFilePath = path
if details.isDir {
var pU *url.URL
pU, err = url.Parse(u)
if err != nil {
return
}
downloadedFilePath = filepath.Join(path, filepath.Base(pU.Path))
}
}
if !details.found && details.parentFound {
downloadedFilePath = path
}
logrus.Infof("downloading %s to %s", u, downloadedFilePath)
resp, err := client.Get(u)
if err != nil {
return downloadedFilePath, err
}
defer resp.Body.Close()
if resp.StatusCode > 299 {
return downloadedFilePath, fmt.Errorf("server responded with status %d", resp.StatusCode)
}
logrus.Infof("writing to path: %s", downloadedFilePath)
out, err := os.Create(downloadedFilePath)
if err != nil {
return downloadedFilePath, err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
return downloadedFilePath, err
}
func RequestContentDispositionFileName(httpClient *retryablehttp.Client, url string, secrets []string) (filename string, err error) {
logrus.Debugf("requesting filename %s", MaskSecrets(url, secrets))
contentDispHeader, err := GetResourceHeaderValue(
httpClient, url, http.MethodHead, "Content-Disposition", secrets,
)
if err != nil {
return
}
_, params, err := mime.ParseMediaType(contentDispHeader)
if err != nil {
return "", fmt.Errorf("failed to get Content-Disposition header - %w", err)
}
if len(params) == 0 {
return "", errors.New("failed to get Content-Disposition header")
}
return params["filename"], err
}
func GetResponseBody(resp *http.Response) (body []byte, err error) {
var output io.ReadCloser
switch resp.Header.Get("Content-Encoding") {
case "gzip":
output, err = gzip.NewReader(resp.Body)
if err != nil {
return
}
default:
output = resp.Body
if err != nil {
return
}
}
buf := new(bytes.Buffer)
_, err = buf.ReadFrom(output)
if err != nil {
return
}
body = buf.Bytes()
return
}