-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
66 lines (55 loc) · 1.17 KB
/
client.go
File metadata and controls
66 lines (55 loc) · 1.17 KB
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 hackernews
import (
"context"
"fmt"
"io"
"net/http"
)
const defaultURL = "https://hacker-news.firebaseio.com"
var defaultHTTPClient = http.DefaultClient
type Client struct {
baseURL string
client *http.Client
}
type Option func(*Client)
func WithBaseURL(url string) Option {
return func(c *Client) {
c.baseURL = url
}
}
func WithHTTPClient(client *http.Client) Option {
return func(c *Client) {
c.client = client
}
}
func NewClient(opts ...Option) *Client {
c := &Client{
baseURL: defaultURL,
client: defaultHTTPClient,
}
for _, opt := range opts {
opt(c)
}
return c
}
type HTTPError struct {
Code int
}
func (e HTTPError) Error() string {
return fmt.Sprintf("status %d (%v)", e.Code, http.StatusText(e.Code))
}
func (c *Client) get(ctx context.Context, path string) ([]byte, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, c.baseURL+path, nil)
if err != nil {
return nil, fmt.Errorf("while creating request: %w", err)
}
r, err := c.client.Do(req)
if err != nil {
return nil, err
}
if r.StatusCode != http.StatusOK {
return nil, HTTPError{Code: r.StatusCode}
}
defer r.Body.Close()
return io.ReadAll(r.Body)
}