-
Notifications
You must be signed in to change notification settings - Fork 0
/
pictureGetter.go
63 lines (57 loc) · 1.25 KB
/
pictureGetter.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
package main
import (
"io"
"log"
"net/http"
"os"
"path/filepath"
"strconv"
"github.com/nishanths/go-xkcd"
)
//SaveComicGetName returns Comic Name and path
//and save file as number.png
func SaveComicGetName(root string) (string, string, bool) {
comic := getLatestComic()
numberString := strconv.Itoa(comic.Number)
path := getPath(numberString, root)
alreadyExists := false
absPath, _ := filepath.Abs(path)
_, err := os.Stat(absPath)
if err == nil {
alreadyExists = true
} else if os.IsNotExist(err) {
saveComicToFile(comic.ImageURL, path)
}
return comic.SafeTitle, path, alreadyExists
}
func getLatestComic() xkcd.Comic {
client := xkcd.NewClient()
comic, err := client.Latest()
if err != nil {
log.Fatal(err)
}
log.Println("Comic URL:", comic.ImageURL)
log.Println("Comic Name:", comic.SafeTitle)
return comic
}
func getPath(name, root string) string {
fileName := root + name + ".png"
return fileName
}
func saveComicToFile(url, path string) {
response, err := http.Get(url)
if err != nil {
log.Fatal(err)
}
defer response.Body.Close()
file, er := os.Create(path)
if er != nil {
log.Fatal(er)
}
defer file.Close()
_, err = io.Copy(file, response.Body)
if err != nil {
log.Fatal(err)
}
log.Println("Picture saved at: ", path)
}