60 lines
1.2 KiB
Go
60 lines
1.2 KiB
Go
package xkcd
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
)
|
|
|
|
var baseURL = "https://xkcd.com/"
|
|
|
|
// Comic is an XKCD comic
|
|
type Comic struct {
|
|
Month string `json:"month"`
|
|
Num int `json:"num"`
|
|
Link string `json:"link"`
|
|
Year string `json:"year"`
|
|
News string `json:"news"`
|
|
SafeTitle string `json:"safe_title"`
|
|
Transcript string `json:"transcript"`
|
|
Alt string `json:"alt"`
|
|
Img string `json:"img"`
|
|
Title string `json:"title"`
|
|
Day string `json:"day"`
|
|
}
|
|
|
|
// Comic gets a specific XKCD Comic
|
|
func (c *Client) Comic(ctx context.Context, num int) (*Comic, error) {
|
|
u := baseURL
|
|
if num > 0 {
|
|
u += fmt.Sprintf("%d/", num)
|
|
}
|
|
u += "info.0.json"
|
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodGet, u, nil)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
resp, err := c.http.Do(req)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if resp.StatusCode != http.StatusOK {
|
|
return nil, fmt.Errorf("got non-200 response: %s", resp.Status)
|
|
}
|
|
|
|
var comic Comic
|
|
if err := json.NewDecoder(resp.Body).Decode(&comic); err != nil {
|
|
return nil, err
|
|
}
|
|
return &comic, resp.Body.Close()
|
|
}
|
|
|
|
// Current gets the current XKCD Comic
|
|
func (c *Client) Current(ctx context.Context) (*Comic, error) {
|
|
return c.Comic(ctx, 0)
|
|
}
|