forked from sethp-nr/icanhazdadjoke
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
63 lines (46 loc) · 1021 Bytes
/
client.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 icanhazdadjoke
import (
"io/ioutil"
"net/http"
)
const UserAgent = "ICanHazDadJoke go client (https://github.com/sethp-nr/icanhazdadjoke)"
const DefaultUrl = "https://icanhazdadjoke.com/"
var DefaultClient = &Client{
Client: http.DefaultClient,
url: DefaultUrl,
}
type Client struct {
*http.Client
url string
}
type FuncOpt func(*Client)
func NewClient(opts ...FuncOpt) *Client {
client := &Client{
Client: http.DefaultClient,
url: DefaultUrl,
}
for _, opt := range opts {
opt(client)
}
return client
}
func GetRandomJokeText() (string, error) {
return DefaultClient.GetRandomJokeText()
}
func (c *Client) GetRandomJokeText() (string, error) {
req, err := http.NewRequest("GET", c.url, nil)
if err != nil {
return "", err
}
req.Header.Add("User-Agent", UserAgent)
req.Header.Add("Accept", "text/plain")
resp, err := c.Do(req)
if err != nil {
return "", err
}
bytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(bytes), nil
}