-
Notifications
You must be signed in to change notification settings - Fork 0
/
get-memes.go
66 lines (56 loc) · 1.34 KB
/
get-memes.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
package imgflipgo
import (
"encoding/json"
"errors"
"io"
"net/http"
)
const GetMemesEndpoint string = "https://api.imgflip.com/get_memes"
type Meme struct {
ID string `json:"id,omitempty"`
Name string `json:"name,omitempty"`
URL string `json:"url,omitempty"`
Width uint `json:"width,omitempty"`
Height uint `json:"height,omitempty"`
// BoxCount describes the number of text boxes the Meme uses.
BoxCount uint `json:"box_count,omitempty"`
}
type MemesResponse struct {
Success bool `json:"success,omitempty"`
Data struct {
Memes []Meme `json:"memes,omitempty"`
} `json:"data,omitempty"`
}
func GetMemesWithResponse() (*MemesResponse, error) {
resp, err := http.Get(GetMemesEndpoint)
if err != nil {
return nil, err
}
if resp == nil {
return nil, errors.New("nil response received")
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
memesResp := MemesResponse{}
err = json.Unmarshal(body, &memesResp)
if err != nil {
return nil, err
}
return &memesResp, err
}
func GetMemes() ([]Meme, error) {
memesResp, err := GetMemesWithResponse()
if err != nil {
return nil, err
}
if memesResp == nil {
return nil, errors.New("nil response received")
}
if !memesResp.Success {
return nil, errors.New("request was unsuccessful")
}
return memesResp.Data.Memes, nil
}