-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.go
More file actions
195 lines (169 loc) · 4.76 KB
/
client.go
File metadata and controls
195 lines (169 loc) · 4.76 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
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
// Package kbhttp provides a simple HTTP client for testing with Katabole.
//
// For a canonical usage example see https://github.com/katabole/kbexample/tree/main/actions
//
// Example:
//
// client := kbhttp.NewClient(kbhttp.ClientConfig{BaseURL: "http://localhost:3000/"})
//
// var user models.User
// if err := f.Client.GetJSON("/users/12345", &user); err != nil {
// t.Fatalf("failed to get user: %v", err)
// }
//
// user.Name = "Tom"
// if err := f.Client.PutJSON("/users/12345", user, nil); err != nil {
// t.Fatalf("failed to update user: %v", err)
// }
package kbhttp
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"path"
"strings"
"unicode/utf8"
)
type ClientConfig struct {
BaseURL *url.URL
}
type Client struct {
*http.Client
config ClientConfig
}
func NewClient(config ClientConfig) *Client {
return &Client{
Client: http.DefaultClient,
config: config,
}
}
func (c *Client) Do(req *http.Request) (*http.Response, error) {
if c.config.BaseURL == nil {
return c.Client.Do(req)
}
// Clone so we don't modify the argument, just in case
r := req.Clone(req.Context())
r.URL.Scheme = c.config.BaseURL.Scheme
r.URL.Host = c.config.BaseURL.Host
r.URL.Path = path.Join(c.config.BaseURL.Path, r.URL.Path)
r.URL.RawPath = path.Join(c.config.BaseURL.RawPath, r.URL.RawPath)
return c.Client.Do(r)
}
// JSON
//
func (c *Client) DoJSON(req *http.Request, target any) error {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
resp, err := c.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("got %d code and failed to read response body: %w", resp.StatusCode, err)
}
if !utf8.Valid(body) {
return fmt.Errorf("got %d code and %d bytes of binary data", resp.StatusCode, len(body))
}
return fmt.Errorf("got %d code and response: %s", resp.StatusCode, string(body))
}
if err := json.NewDecoder(resp.Body).Decode(&target); err != nil {
return fmt.Errorf("got %d code and failed to decode response body: %w", resp.StatusCode, err)
}
return nil
}
func (c *Client) GetJSON(urlPath string, target any) error {
req, err := http.NewRequest(http.MethodGet, urlPath, nil)
if err != nil {
return err
}
return c.DoJSON(req, target)
}
func (c *Client) PutJSON(urlPath string, input any, target any) error {
data, err := json.Marshal(input)
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodPut, urlPath, bytes.NewReader(data))
if err != nil {
return err
}
return c.DoJSON(req, target)
}
func (c *Client) PostJSON(urlPath string, input any, target any) error {
data, err := json.Marshal(input)
if err != nil {
return err
}
req, err := http.NewRequest(http.MethodPost, urlPath, bytes.NewReader(data))
if err != nil {
return err
}
return c.DoJSON(req, target)
}
func (c *Client) DeleteJSON(urlPath string, target any) error {
req, err := http.NewRequest(http.MethodDelete, urlPath, nil)
if err != nil {
return err
}
return c.DoJSON(req, target)
}
// HTML Pages / Forms
//
func (c *Client) DoPage(req *http.Request) (string, error) {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "text/html")
resp, err := c.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("got %d code and failed to read response body: %w", resp.StatusCode, err)
}
if !utf8.Valid(body) {
return "", fmt.Errorf("got %d code and %d bytes of binary data", resp.StatusCode, len(body))
}
return "", fmt.Errorf("got %d code and response: %s", resp.StatusCode, string(body))
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("got %d code and failed to read response body: %w", resp.StatusCode, err)
}
return string(body), nil
}
func (c *Client) GetPage(urlPath string) (string, error) {
req, err := http.NewRequest(http.MethodGet, urlPath, nil)
if err != nil {
return "", err
}
return c.DoPage(req)
}
func (c *Client) PostPage(urlPath string, input url.Values) (string, error) {
req, err := http.NewRequest(http.MethodPost, urlPath, strings.NewReader(input.Encode()))
if err != nil {
return "", err
}
return c.DoPage(req)
}
func (c *Client) PutPage(urlPath string, input url.Values) (string, error) {
req, err := http.NewRequest(http.MethodPut, urlPath, strings.NewReader(input.Encode()))
if err != nil {
return "", err
}
return c.DoPage(req)
}
func (c *Client) DeletePage(urlPath string) (string, error) {
req, err := http.NewRequest(http.MethodDelete, urlPath, nil)
if err != nil {
return "", err
}
return c.DoPage(req)
}