-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgiphy.go
58 lines (48 loc) · 1.21 KB
/
giphy.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
const giphySearchURL = "http://api.giphy.com/v1/gifs/search"
const giphyAPIKey = "dc6zaTOxFJmzC"
type giphy struct {
Data []giphyData `json:"data"`
}
type giphyData struct {
Images struct {
Original struct {
URL string `json:"url"`
} `json:"original"`
} `json:"images"`
}
func giffyGetGifs(searchTerm string, count int) (giphy, error) {
gifResp := giphy{}
// Create Giphy http request
u, err := url.Parse(giphySearchURL)
if err != nil {
return gifResp, fmt.Errorf("url parse error: %s", err.Error())
}
q := u.Query()
q.Set("api_key", giphyAPIKey)
q.Add("q", searchTerm)
u.RawQuery = q.Encode()
// Send request for gifs
resp, err := http.Get(u.String())
if err != nil {
return gifResp, fmt.Errorf("Giphy http request err: %s", err.Error())
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if resp.StatusCode != 200 {
return gifResp, fmt.Errorf("Giphy http request non 200 response: %s (%s)", resp.Status, body)
}
// Unmarshal response
err = json.Unmarshal(body, &gifResp)
if err != nil {
return gifResp, fmt.Errorf("Error unmarshalling Giphy resposne: %s", body)
}
return gifResp, nil
}