-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
73 lines (60 loc) · 1.31 KB
/
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
64
65
66
67
68
69
70
71
72
73
package openbd
import (
"context"
"fmt"
"io"
"net/http"
"strings"
"github.com/kironono/go-openbd/api"
)
type Client struct {
Client *http.Client
Host string
}
func NewClient(client *http.Client, host string) *Client {
return &Client{
client,
host,
}
}
func DefaultClient() *Client {
return &Client{
Client: http.DefaultClient,
Host: "https://api.openbd.jp/v1",
}
}
func (c *Client) Books(ctx context.Context, ids []string) ([]Book, error) {
endpoint := api.BooksEndpoint.Complement(c.Host)
req, err := http.NewRequest(http.MethodGet, endpoint, nil)
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
req.WithContext(ctx)
q := req.URL.Query()
q.Add("isbn", strings.Join(ids, ","))
req.URL.RawQuery = q.Encode()
body, err := get(c, req)
if err != nil {
return nil, err
}
books, err := DecodeBooks(body)
if err != nil {
return nil, err
}
return books, nil
}
func get(c *Client, req *http.Request) ([]byte, error) {
resp, err := c.Client.Do(req)
if err != nil {
return nil, fmt.Errorf("response error: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("status error: %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("read response: %w", err)
}
return body, nil
}