-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
70 lines (62 loc) · 1.53 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
// xkcd is a tool that dowloads each URL of each comic once, creates an offline index,
// then using that index prints the URL and the transcript of each comic that matches
// a search term provided on the command line.
// Made with help from the Golang Community, built based off an exercise in GoPL textbook
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"os"
"strconv"
)
const xkcdURL = "https://xkcd.com/"
type xkcdComic struct {
Transcript string `json:"transcript"`
ComicNum int `json:"num"`
}
func main() {
result, err := populateComics()
if err != nil {
log.Fatal(err)
}
searchXkcd(result, os.Args[1:])
}
func populateComics() ([]xkcdComic, error) {
var comics []xkcdComic
var u string
for i := 1; i <= 1626; i++ {
u = xkcdURL + strconv.Itoa(i) + "/info.0.json"
resp, err := http.Get(u)
if err != nil {
return nil, err
}
var c xkcdComic
switch resp.StatusCode {
case 200:
err := json.NewDecoder(resp.Body).Decode(&c)
resp.Body.Close()
if err != nil {
return nil, err
}
comics = append(comics, c)
default:
resp.Body.Close()
fmt.Println(u)
}
}
return comics, nil
}
func searchXkcd(comics []xkcdComic, terms []string) {
for _, c := range comics {
for _, t := range terms {
if strconv.Itoa(c.ComicNum) == t {
fmt.Printf("URL: https://xkcd.com/ \b%v/info.0.json,\nTranscript: %s\n\n", c.ComicNum, c.Transcript)
}
}
}
}
// STILL TO ADD: make populateComics more simplified with defer, using simplified function
// func populateSingleComic() xkcdComic {
//}