-
Notifications
You must be signed in to change notification settings - Fork 8
/
image.go
63 lines (52 loc) · 1.3 KB
/
image.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 (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
const (
imageURL = "https://api.unsplash.com/photos/random?query=%s&client_id=%s"
)
func getImage(animalType string) []byte {
for i := 0; i < 5; i++ {
image, err := readImage(animalType)
if err != nil {
continue
}
return image
}
return nil
}
type imageResult struct {
ImageURLS imagesSize `json:"urls"`
}
type imagesSize struct {
Small string `json:"small"`
}
func readImage(animalType string) (image []byte, err error) {
client := http.Client{}
uri := fmt.Sprintf(imageURL, animalType, Config.UnsplashClientID)
randomImage, err := client.Get(uri)
if err != nil {
return nil, fmt.Errorf("failed to make request: %v", err)
}
defer randomImage.Body.Close()
if randomImage.StatusCode != http.StatusOK {
return nil, fmt.Errorf("no goose found")
}
var a imageResult
if err = json.NewDecoder(randomImage.Body).Decode(&a); err != nil {
return nil, fmt.Errorf("failed to decode response: %v", err)
}
smallImage, err := client.Get(a.ImageURLS.Small)
if err != nil {
return nil, fmt.Errorf("failed to make request: %v", err)
}
defer smallImage.Body.Close()
if smallImage.StatusCode != http.StatusOK {
return nil, fmt.Errorf("no %s found", animalType)
}
f, err := ioutil.ReadAll(smallImage.Body)
return f, nil
}