-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
90 lines (74 loc) · 1.78 KB
/
client.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 aoc
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"os"
"time"
)
type Client struct {
sessionToken string
httpClient *http.Client
}
const RequestTimout = 10
func NewClient(token string) Client {
return Client{
sessionToken: token,
httpClient: &http.Client{
Transport: nil,
CheckRedirect: nil,
Jar: nil,
Timeout: time.Second * RequestTimout,
},
}
}
// DownloadInput downloads the requested input file.
func (c *Client) DownloadInput(year, day int) (io.ReadCloser, error) {
url := fmt.Sprintf("https://adventofcode.com/%d/day/%d/input", year, day)
req, err := http.NewRequestWithContext(context.Background(), "GET", url, nil)
if err != nil {
return nil, fmt.Errorf("unable to create request from context: %w", err)
}
req.AddCookie(&http.Cookie{
Name: "session",
Value: c.sessionToken,
Path: "",
Domain: "",
Expires: time.Time{},
RawExpires: "",
MaxAge: 0,
Secure: false,
HttpOnly: false,
SameSite: 0,
Raw: "",
Unparsed: []string{},
})
resp, err := c.httpClient.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
return nil, errors.New("unable to download input")
}
return resp.Body, nil
}
// DownloadAndSaveInput downloads and saves the requested input file.
func (c *Client) DownloadAndSaveInput(year, day int, targetFile string) error {
file, err := c.DownloadInput(year, day)
if err != nil {
return err
}
defer file.Close()
outputFile, err := os.Create(targetFile)
if err != nil {
return fmt.Errorf("unable to create output file: %w", err)
}
defer outputFile.Close()
_, err = io.Copy(outputFile, file)
if err != nil {
return fmt.Errorf("unable to copy response into the output file: %w", err)
}
return nil
}