-
Notifications
You must be signed in to change notification settings - Fork 0
/
search.go
57 lines (50 loc) · 1.16 KB
/
search.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
package gifgo
import (
"encoding/json"
"net/http"
"net/url"
)
// Search searches for a GIF with the specified params
func (c *Client) Search(query SearchReq) (*MultipleGIF, error) {
reqURL := c.baseURL.ResolveReference(searchPath)
return search(query, reqURL, c.apiKey, c.client)
}
// SearchReq contains paramaters for a GIF search
type SearchReq struct {
Query string
Limit int
Offset int
Rating string
}
func (s SearchReq) toValues() url.Values {
values := url.Values{}
values.Add("q", s.Query)
if s.Limit != 0 {
values.Add("limit", string(s.Limit))
}
if s.Offset != 0 {
values.Add("offset", string(s.Offset))
}
if s.Rating != "" {
values.Add("rating", s.Rating)
}
return values
}
func search(query SearchReq, reqURL *url.URL, key string, client *http.Client) (*MultipleGIF, error) {
q := query.toValues()
q.Add("api_key", key)
reqURL.RawQuery = q.Encode()
req, err := http.NewRequest("GET", reqURL.String(), nil)
if err != nil {
return nil, err
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
data := new(MultipleGIF)
if err := json.NewDecoder(resp.Body).Decode(data); err != nil {
return nil, err
}
return data, nil
}