]> fbox.kageds.com Git - adventofcode.git/blob - 2023/go/utils/inputFile.go
day07
[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.Printf("Creating new input file %v...", path)
26 f, err := os.Create(path)
27 if err != nil {
28 fmt.Println(err)
29 } else {
30 defer f.Close()
31 data := readHttp(2023, day)
32 _, err := f.WriteString(data)
33 if err != nil {
34 fmt.Println(err)
35 }
36 }
37 return path
38 }
39
40 func readHttp(year, day int) string {
41 fmt.Println("Fetching data into file...")
42
43 url := fmt.Sprintf("https://adventofcode.com/%d/day/%d/input", year, day)
44 session := os.Getenv("sessionAoC")
45 req, err := http.NewRequest("GET", url, nil)
46 if err != nil {
47 panic(err)
48 }
49
50 req.AddCookie(&http.Cookie{Name: "session", Value: session})
51 client := &http.Client{}
52 resp, err := client.Do(req)
53 if err != nil {
54 panic(err)
55 }
56
57 body, err := io.ReadAll(resp.Body)
58 if err != nil {
59 panic(err)
60 }
61 return string(body)
62 }
63