-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
83 lines (74 loc) · 1.44 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
package advent
import (
"bufio"
"fmt"
"io"
"net/http"
"net/http/cookiejar"
"strconv"
)
type client struct {
http.Client
host string
year int
cookie string
}
type Input []string
func (in *Input) ToInt() ([]int, error) {
var intArr []int
for _, s := range *in {
i, err := strconv.Atoi(s)
if err != nil {
return intArr, err
}
intArr = append(intArr, i)
}
return intArr, nil
}
type Client interface {
GetInput(day int) (*Input, error)
}
func NewClient(year int, cookie string) (Client, error) {
jar, err := cookiejar.New(nil)
if err != nil {
return nil, err
}
return &client{
Client: http.Client{
Jar: jar,
},
host: "adventofcode.com",
year: year,
cookie: cookie,
}, nil
}
func (c *client) GetInput(day int) (*Input, error) {
var lines Input
method := "GET"
address := fmt.Sprintf("https://%s/%d/day/%d/input", c.host, c.year, day)
req, err := c.initRequest(method, address, nil)
if err != nil {
return &lines, err
}
resp, err := c.Do(req)
if err != nil {
return &lines, err
}
defer resp.Body.Close()
scanner := bufio.NewScanner(resp.Body)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return &lines, nil
}
func (c *client) initRequest(method, address string, body io.Reader) (*http.Request, error) {
req, err := http.NewRequest(method, address, body)
if err != nil {
return nil, err
}
req.AddCookie(&http.Cookie{
Name: "session",
Value: c.cookie,
})
return req, nil
}