-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
209 lines (173 loc) · 4.23 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
package jsonstore
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
// Errors
var (
ErrNoSecret = fmt.Errorf("no secret")
ErrNotFound = fmt.Errorf("not found")
ErrInternalServerError = fmt.Errorf("internal server error")
ErrUnexpectedStatus = fmt.Errorf("unexpected status")
)
const (
defaultScheme = "https"
defaultHost = "www.jsonstore.io"
defaultUserAgent = "jsonstore/client.go (godoc.org/github.com/peterhellberg/jsonstore)"
defaultTimeout = 10 * time.Second
)
// Client for the www.jsonstore.io API
type Client struct {
httpClient *http.Client
baseURL *url.URL
userAgent string
secret string
}
// Option is a type of function used to configure the client
type Option func(*Client)
// New creates a www.jsonstore.io Client
func New(options ...Option) *Client {
c := &Client{
httpClient: &http.Client{
Timeout: defaultTimeout,
},
baseURL: &url.URL{
Scheme: defaultScheme,
Host: defaultHost,
},
userAgent: defaultUserAgent,
}
for _, option := range options {
option(c)
}
if c.secret == "" {
if s, err := NewSecret(); err == nil {
c.secret = s
}
}
return c
}
// HTTPClient changes the HTTP client used by the client to the provided *http.Client
func HTTPClient(hc *http.Client) Option {
return func(c *Client) {
c.httpClient = hc
}
}
// BaseURL changes the base URL used by the client to the URL parsed from rawurl
func BaseURL(rawurl string) Option {
return func(c *Client) {
if u, err := url.Parse(rawurl); err == nil {
c.baseURL = u
}
}
}
// Secret sets the secret used by the client to the provided string
func Secret(s string) Option {
return func(c *Client) {
c.secret = s
}
}
// Secret returns the client secret
func (c *Client) Secret() string {
return c.secret
}
// URL returns the URL used by the client
func (c *Client) URL(segments ...string) *url.URL {
return c.baseURL.ResolveReference(&url.URL{
Path: "/" + c.secret + "/" + strings.TrimPrefix(strings.Join(segments, "/"), "/"),
})
}
// Get response from jsonstore
func (c *Client) Get(ctx context.Context, path string, v interface{}) error {
req, err := c.request(ctx, http.MethodGet, path, nil)
if err != nil {
return err
}
return c.do(req, v)
}
// Post to jsonstore
func (c *Client) Post(ctx context.Context, path string, v interface{}) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
req, err := c.request(ctx, http.MethodPost, path, bytes.NewReader(b))
if err != nil {
return err
}
return c.do(req, nil)
}
// Put update to jsonstore
func (c *Client) Put(ctx context.Context, path string, v interface{}) error {
b, err := json.Marshal(v)
if err != nil {
return err
}
req, err := c.request(ctx, http.MethodPut, path, bytes.NewReader(b))
if err != nil {
return err
}
return c.do(req, nil)
}
// Delete from jsonstore
func (c *Client) Delete(ctx context.Context, path string) error {
req, err := c.request(ctx, http.MethodDelete, path, nil)
if err != nil {
return err
}
return c.do(req, nil)
}
func (c *Client) request(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
if c.secret == "" {
return nil, ErrNoSecret
}
rel, err := url.Parse("/" + c.secret + "/" + strings.TrimPrefix(path, "/"))
if err != nil {
return nil, err
}
rawurl := c.baseURL.ResolveReference(rel).String()
req, err := http.NewRequest(method, rawurl, body)
if err != nil {
return nil, err
}
req = req.WithContext(ctx)
req.Header.Add("Accept", "application/json")
req.Header.Add("Content-Type", "application/json")
req.Header.Add("User-Agent", c.userAgent)
return req, nil
}
func (c *Client) do(req *http.Request, v interface{}) error {
resp, err := c.httpClient.Do(req)
if err != nil {
return err
}
defer func() {
_, _ = io.CopyN(ioutil.Discard, resp.Body, 1024)
_ = resp.Body.Close()
}()
switch resp.StatusCode {
case http.StatusOK:
case http.StatusCreated:
case http.StatusNotFound:
return ErrNotFound
case http.StatusInternalServerError:
return ErrInternalServerError
default:
return ErrUnexpectedStatus
}
if v != nil {
return json.NewDecoder(resp.Body).Decode(&response{v})
}
return nil
}
type response struct {
Result interface{} `json:"result"`
}