-
Notifications
You must be signed in to change notification settings - Fork 8
/
pony.go
65 lines (55 loc) · 1.29 KB
/
pony.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 main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
const (
ponyURL = "https://theponyapi.com/api/v1/pony/random"
)
// Only the properties we actually use.
type ponyResult struct {
Pony ponyResultPony `json:"pony"`
}
type ponyResultPony struct {
Representations ponyRepresentations `json:"representations"`
}
type ponyRepresentations struct {
Small string `json:"small"`
}
func getPony() (ponyImage []byte) {
for i := 0; i < 5; i++ {
image, err := readPony()
if err != nil {
continue
}
return image
}
return nil
}
func readPony() (ponyImage []byte, err error) {
client := http.Client{}
resp, err := client.Get(ponyURL)
if err != nil {
return nil, fmt.Errorf("failed to make request: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("no pony found")
}
var a ponyResult
if err = json.NewDecoder(resp.Body).Decode(&a); err != nil {
return nil, fmt.Errorf("failed to decode response: %v", err)
}
smallMeow, err := client.Get(a.Pony.Representations.Small)
if err != nil {
return nil, fmt.Errorf("failed to make request: %v", err)
}
defer smallMeow.Body.Close()
if smallMeow.StatusCode != http.StatusOK {
return nil, fmt.Errorf("no Meow found")
}
f, err := ioutil.ReadAll(smallMeow.Body)
return f, err
}