]> fbox.kageds.com Git - adventofcode.git/blob - 2023/go/utils/inputFile.go
day02
[adventofcode.git] / 2023 / go / utils / inputFile.go
1 package utils
2
3 import (
4 "fmt"
5 "io"
6 "net/http"
7 "os"
8 )
9
10 func GenInputFile(day int) string {
11 var d string
12 if day < 10 {
13 d = fmt.Sprintf("0%d", day)
14 } else {
15 d = fmt.Sprintf("%d", day)
16 }
17
18 pwd, _ := os.Getwd()
19 path := fmt.Sprintf("%s\\day%s\\input.txt", pwd, d)
20 fi, _ := os.Stat(path)
21 if fi != nil {
22 return path
23 }
24
25 fmt.Println("Creating new input file...")
26 f, _ := os.OpenFile(path, os.O_CREATE, 0700)
27 f.WriteString(readHttp(2022, day))
28 return path
29 }
30
31 func readHttp(year, day int) string {
32 fmt.Println("Fetching data into file...")
33
34 url := fmt.Sprintf("https://adventofcode.com/%d/day/%d/input", year, day)
35 session := os.Getenv("sessionAoC")
36
37 req, err := http.NewRequest("GET", url, nil)
38 if err != nil {
39 panic(err)
40 }
41
42 req.AddCookie(&http.Cookie{Name: "session", Value: session})
43 client := &http.Client{}
44 resp, err := client.Do(req)
45 if err != nil {
46 panic(err)
47 }
48
49 body, err := io.ReadAll(resp.Body)
50 if err != nil {
51 panic(err)
52 }
53
54 return string(body)
55 }
56