-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
88 lines (72 loc) · 1.99 KB
/
main.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
package main
import (
"flag"
"fmt"
"github.com/ludikrous/xkcdOffline/comic"
_ "github.com/ludikrous/xkcdOffline/comic"
"io"
"log"
"net/http"
"os"
"strings"
)
const URL string = "https://xkcd.com/"
const JSON_PATH string = "/info.0.json"
func main() {
// define flags
pictureFolder := flag.String("loc", ".", "Full path for the folder in which comics will be stored")
// TODO flags to add:
// log into csv, high res, add title and captions to image, compile into pdf, start end date, start end number
// parse flags
flag.Parse()
err := os.MkdirAll(fmt.Sprintf("%s/xkcdOffline", *pictureFolder), os.ModePerm)
if err != nil {
log.Fatal(err)
os.Exit(-1)
}
// populate picture folder with all the xkcd comics
allComics := getAllComics()
// download all comics into the given directory
for _, comic := range allComics {
download(comic, pictureFolder)
}
}
func download(c comic.Comic, pictureFolder *string) {
// get the image from xkcd servers
response, e := http.Get(c.Address)
if e != nil {
log.Fatal(e)
}
defer response.Body.Close()
//open a file for writing
splitURL := strings.Split(c.Address, "/")
fileEnding := splitURL[len(splitURL)-1]
filename := fmt.Sprintf("%s/xkcdOffline/xkcd%d_%s", *pictureFolder, c.Number, fileEnding)
file, err := os.Create(filename)
if err != nil {
log.Fatal(err)
}
defer file.Close()
// Use io.Copy to just dump the response body to the file. This supports huge files
_, err = io.Copy(file, response.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println("Saved comic #%d to disk.", c.Number)
}
func getAllComics() []comic.Comic {
// get latest comic number
currNumber := getHighestComicNum()
// make a slice of comics and populate them
allComics := make([]comic.Comic, currNumber)
// iterate through all comics
for num := currNumber; num > 0; num-- {
c := comic.NewComic(num)
allComics[num-1] = c
fmt.Println(c)
}
return allComics
}
func getHighestComicNum() int {
return 10 // TODO this method should be implemented later on
}