-
Notifications
You must be signed in to change notification settings - Fork 1
/
http.go
64 lines (51 loc) · 1.14 KB
/
http.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
package wallhaven
import (
"encoding/json"
"io"
"io/ioutil"
"net/http"
"net/url"
"os"
)
func processResponse(resp *http.Response, out interface{}) error {
byt, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
resp.Body.Close()
return json.Unmarshal(byt, out)
}
const baseURL = "https://wallhaven.cc/api/v1"
func getWithBase(p string) string {
return baseURL + p
}
var client = &http.Client{}
func get(p string) (*http.Response, error) {
return getWithValues(p, url.Values{})
}
func getWithValues(p string, v url.Values) (*http.Response, error) {
u, err := url.Parse(getWithBase(p))
if err != nil {
return nil, err
}
u.RawQuery = v.Encode()
return getAuthedResponse(u.String())
}
func getAuthedResponse(url string) (*http.Response, error) {
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
req.Header.Set("X-API-Key", os.Getenv("WH_API_KEY"))
return client.Do(req)
}
func download(filepath string, resp *http.Response) error {
defer resp.Body.Close()
out, err := os.Create(filepath)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, resp.Body)
return err
}