-
Notifications
You must be signed in to change notification settings - Fork 0
/
gwhub.go
248 lines (222 loc) · 4.94 KB
/
gwhub.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
package gwhub
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"reflect"
"regexp"
"strconv"
"time"
"github.com/google/go-querystring/query"
)
// Hub holds connection details for a GW Hub
type Hub struct {
BaseURL string
client *http.Client
}
// ErrServerError makes it a little easier for the caller to check the
// underlying HTTP response
var ErrServerError = errors.New("error from server (HTTP Status > 299)")
func New(options ...Options) *Hub {
opts := evalOptions(options...)
return &Hub{
BaseURL: opts.baseURL,
client: opts.client,
}
}
// Get method. On successful return the response body will be closed.
func (hub *Hub) Get(ctx context.Context, endpoint string, request interface{}, response interface{}) (resp *http.Response, err error) {
dest, err := url.JoinPath(hub.BaseURL, endpoint)
if err != nil {
return
}
req, err := http.NewRequestWithContext(ctx, "GET", dest, nil)
if err != nil {
return
}
if request != nil {
v, err := query.Values(request)
if err != nil {
return resp, err
}
req.URL.RawQuery = v.Encode()
}
resp, err = hub.client.Do(req)
if err != nil {
return
}
if resp.StatusCode > 299 {
b, _ := io.ReadAll(resp.Body)
err = fmt.Errorf("%w: %s", ErrServerError, string(b))
return
}
defer resp.Body.Close()
if response == nil {
return
}
err = decodeResponse(resp, response)
return
}
// Post method
func (hub *Hub) Post(ctx context.Context, endpoint string, request interface{}, response interface{}) (resp *http.Response, err error) {
dest, err := url.JoinPath(hub.BaseURL, endpoint)
if err != nil {
return
}
j, err := json.Marshal(request)
if err != nil {
return
}
req, err := http.NewRequestWithContext(ctx, "POST", dest, bytes.NewReader(j))
if err != nil {
return
}
req.Header.Add("content-type", "application/json")
resp, err = hub.client.Do(req)
if resp.StatusCode > 299 {
b, _ := io.ReadAll(resp.Body)
err = fmt.Errorf("%w: %s", ErrServerError, string(b))
return
}
defer resp.Body.Close()
if response == nil {
return
}
err = decodeResponse(resp, response)
return
}
func decodeResponse(resp *http.Response, response interface{}) (err error) {
d := json.NewDecoder(resp.Body)
rt := reflect.TypeOf(response)
switch rt.Kind() {
case reflect.Slice:
rv := reflect.ValueOf(response)
var t json.Token
t, err = d.Token()
if err != nil {
return
}
if t != "[" {
err = errors.New("not an array")
return
}
for d.More() {
var s interface{}
if err = d.Decode(&s); err != nil {
return
}
rv = reflect.Append(rv, reflect.ValueOf(s))
}
t, err = d.Token()
if err != nil {
return
}
if t != "]" {
err = errors.New("array not terminated")
return
}
default:
err = d.Decode(&response)
}
return
}
func (hub *Hub) Ping(ctx context.Context) (resp *http.Response, err error) {
return hub.Get(ctx, PingEndpoint, nil, nil)
}
// ParseDuration parses an ISO 8601 string representing a duration, and
// returns the resultant golang time.Duration instance.
//
// From https://github.com/spatialtime/iso8601 but "fixed" to allow
// durations without 'T'
func ParseDuration(isoDuration string) (time.Duration, error) {
re := regexp.MustCompile(`^P(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)D)?T?(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:.\d+)?)S)?$`)
matches := re.FindStringSubmatch(isoDuration)
if matches == nil {
return 0, errors.New("duration string is of incorrect format")
}
seconds := 0.0
//skipping years and months
//days
if matches[3] != "" {
f, err := strconv.ParseFloat(matches[3], 32)
if err != nil {
return 0, err
}
seconds += (f * 24 * 60 * 60)
}
//hours
if matches[4] != "" {
f, err := strconv.ParseFloat(matches[4], 32)
if err != nil {
return 0, err
}
seconds += (f * 60 * 60)
}
//minutes
if matches[5] != "" {
f, err := strconv.ParseFloat(matches[5], 32)
if err != nil {
return 0, err
}
seconds += (f * 60)
}
//seconds & milliseconds
if matches[6] != "" {
f, err := strconv.ParseFloat(matches[6], 32)
if err != nil {
return 0, err
}
seconds += f
}
goDuration := strconv.FormatFloat(seconds, 'f', -1, 32) + "s"
return time.ParseDuration(goDuration)
}
const (
Day = 24 * time.Hour
Week = 7 * Day
)
// FormatDuration converts a time.Duration to an ISO8601 duration up to
// weeks. Months and years are not supported.
func FormatDuration(d time.Duration) (iso string) {
iso = "P"
weeks := d.Truncate(Week)
if weeks > 0 {
iso += fmt.Sprintf("%dW", weeks/Week)
d -= weeks
if d == 0 {
return
}
}
days := d.Truncate(Day)
if days > 0 {
iso += fmt.Sprintf("%dD", days/Day)
d -= days
if d == 0 {
return
}
}
iso += "T"
hours := d.Truncate(time.Hour)
if hours > 0 {
iso += fmt.Sprintf("%dH", hours/time.Hour)
d -= hours
if d == 0 {
return
}
}
minutes := d.Truncate(time.Minute)
if minutes > 0 {
iso += fmt.Sprintf("%dH", minutes/time.Minute)
d -= minutes
if d == 0 {
return
}
}
iso += fmt.Sprintf("%fS", d.Seconds())
return
}