forked from chrishoffman/xkcd-slack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxkcd.go
65 lines (56 loc) · 1.49 KB
/
xkcd.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
package xkcdslack
import (
"encoding/json"
"errors"
"fmt"
"io"
"appengine"
"appengine/urlfetch"
)
// Comic is a struct that contains infomation about an xkcd comic.
type Comic struct {
Num int `json:"num"`
Title string `json:"title"`
SafeTitle string `json:"safe_title"`
Img string `json:"img"`
Alt string `json:"alt"`
Year string `json:"year"`
Month string `json:"month"`
Day string `json:"day"`
News string `json:"news"`
Link string `json:"link"`
Transcript string `json:"transcript"`
}
// New reads from an io.Reader and returns a *Comic struct.
func New(r io.Reader) (*Comic, error) {
d := json.NewDecoder(r)
c := new(Comic)
err := d.Decode(c)
return c, err
}
const (
currentURL = "https://xkcd.com/info.0.json"
templateURL = "https://xkcd.com/%v/info.0.json"
)
// Get fetches information about the xkcd comic number `n'.
func Get(c appengine.Context, n int) (*Comic, error) {
url := fmt.Sprintf(templateURL, n)
return getByURL(c, url)
}
// GetCurrent fetches information for the newest xkcd comic.
func GetCurrent(c appengine.Context) (*Comic, error) {
return getByURL(c, currentURL)
}
// getByURL returns infomation downloaded from `url'.
func getByURL(c appengine.Context, url string) (*Comic, error) {
client := urlfetch.Client(c)
resp, err := client.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
return nil, errors.New(resp.Status)
}
return New(resp.Body)
}