64 lines
1.1 KiB
Go
64 lines
1.1 KiB
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"os"
|
|
)
|
|
|
|
func GenInputFile(day int) string {
|
|
var d string
|
|
if day < 10 {
|
|
d = fmt.Sprintf("0%d", day)
|
|
} else {
|
|
d = fmt.Sprintf("%d", day)
|
|
}
|
|
|
|
pwd, _ := os.Getwd()
|
|
path := fmt.Sprintf("%s/day%s/input.txt", pwd, d)
|
|
fi, _ := os.Stat(path)
|
|
if fi != nil {
|
|
return path
|
|
}
|
|
|
|
fmt.Printf("Creating new input file %v...", path)
|
|
f, err := os.Create(path)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
} else {
|
|
defer f.Close()
|
|
data := readHttp(2024, day)
|
|
_, err := f.WriteString(data)
|
|
if err != nil {
|
|
fmt.Println(err)
|
|
}
|
|
}
|
|
return path
|
|
}
|
|
|
|
func readHttp(year, day int) string {
|
|
fmt.Println("Fetching data into file...")
|
|
|
|
url := fmt.Sprintf("https://adventofcode.com/%d/day/%d/input", year, day)
|
|
session := os.Getenv("sessionAoC")
|
|
req, err := http.NewRequest("GET", url, nil)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
req.AddCookie(&http.Cookie{Name: "session", Value: session})
|
|
client := &http.Client{}
|
|
resp, err := client.Do(req)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
return string(body)
|
|
}
|
|
|