Repository navigation
Expand file tree
/
Copy pathClient.go
More file actions
692 lines (606 loc) · 20.1 KB
/
Copy pathClient.go
File metadata and controls
692 lines (606 loc) · 20.1 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
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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
package client
import (
"crypto/sha256"
"crypto/sha512"
"encoding/base64"
"errors"
"hash"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/NeedleInAJayStack/haystack"
"github.com/NeedleInAJayStack/haystack/auth"
"github.com/NeedleInAJayStack/haystack/io"
)
// Client models a client connection to a server using the Haystack API.
type Client struct {
clientHTTP clientHTTP
uri string
username string
password string
auth string
}
var encoding = base64.RawURLEncoding
var userAgent = "Go-haystack-client"
// NewClient creates a new Client object.
func NewClient(uri string, username string, password string) *Client {
// check URI
if !strings.HasPrefix(uri, "http://") && !strings.HasPrefix(uri, "https://") {
panic("URI isn't http or https: " + uri)
}
if !strings.HasSuffix(uri, "/") {
uri = uri + "/"
}
timeout, _ := time.ParseDuration("1m")
return &Client{
clientHTTP: &clientHTTPImpl{
&http.Client{Timeout: timeout},
},
uri: uri,
username: username,
password: password,
auth: "",
}
}
// Open simply opens and authenticates the connection
func (client *Client) Open() error {
auth, err := client.clientHTTP.getAuthHeader(client.uri, client.username, client.password)
if err != nil {
return err
}
client.auth = auth
return nil
}
// About calls the 'about' op.
func (client *Client) About() (haystack.Dict, error) {
result, err := client.Call("about", haystack.EmptyGrid())
if err != nil {
return haystack.Dict{}, err
}
return result.RowAt(0).ToDict(), nil
}
// Close closes and de-authenticates the client
func (client *Client) Close() error {
_, err := client.Call("close", haystack.EmptyGrid())
return err
}
// Defs calls the 'defs' op.
func (client *Client) Defs() (haystack.Grid, error) {
return client.Call("defs", haystack.EmptyGrid())
}
// DefsWithFilter calls the 'defs' op with a filter grid.
func (client *Client) DefsWithFilter(filter string, limit int) (haystack.Grid, error) {
return client.Call("defs", filterGrid(filter, limit))
}
// Libs calls the 'libs' op.
func (client *Client) Libs() (haystack.Grid, error) {
return client.Call("libs", haystack.EmptyGrid())
}
// LibsWithFilter calls the 'libs' op with a filter grid.
func (client *Client) LibsWithFilter(filter string, limit int) (haystack.Grid, error) {
return client.Call("libs", filterGrid(filter, limit))
}
// Ops calls the 'ops' op.
func (client *Client) Ops() (haystack.Grid, error) {
return client.Call("ops", haystack.EmptyGrid())
}
// OpsWithFilter calls the 'ops' op with a filter grid.
func (client *Client) OpsWithFilter(filter string, limit int) (haystack.Grid, error) {
return client.Call("ops", filterGrid(filter, limit))
}
// Filetypes calls the 'filetypes' op.
func (client *Client) Filetypes() (haystack.Grid, error) {
return client.Call("filetypes", haystack.EmptyGrid())
}
// FiletypesWithFilter calls the 'filetypes' op with a filter grid.
func (client *Client) FiletypesWithFilter(filter string, limit int) (haystack.Grid, error) {
return client.Call("filetypes", filterGrid(filter, limit))
}
// Read calls the 'read' op with a filter and no result limit.
func (client *Client) Read(filter string) (haystack.Grid, error) {
return client.ReadLimit(filter, 0)
}
// ReadLimit calls the 'read' op with a filter and a result limit.
func (client *Client) ReadLimit(filter string, limit int) (haystack.Grid, error) {
return client.Call("read", filterGrid(filter, limit))
}
// ReadByIds calls the 'read' op with the input ids.
func (client *Client) ReadByIds(ids []haystack.Ref) (haystack.Grid, error) {
gb := haystack.NewGridBuilder()
gb.AddColNoMeta("id")
for _, id := range ids {
gb.AddRow([]haystack.Val{id})
}
return client.Call("read", gb.ToGrid())
}
// Nav calls the 'nav' op to navigate a project for learning and discovery
func (client *Client) Nav(navId haystack.Val) (haystack.Grid, error) {
gb := haystack.NewGridBuilder()
gb.AddColNoMeta("navId")
gb.AddRow([]haystack.Val{navId})
return client.Call("nav", gb.ToGrid())
}
// WatchSubCreate calls the 'watchSub' op to create a new subscription. If `lease` is 0 or less, no lease is added
// to the subscription
func (client *Client) WatchSubCreate(
watchDis string,
lease haystack.Number,
ids []haystack.Ref,
) (haystack.Grid, error) {
meta := map[string]haystack.Val{"watchDis": haystack.NewStr(watchDis)}
if lease.Float() > 0 {
meta["lease"] = lease
}
gb := haystack.NewGridBuilder()
gb.AddMeta(meta)
gb.AddColNoMeta("ids")
for _, id := range ids {
gb.AddRow([]haystack.Val{id})
}
return client.Call("watchSub", gb.ToGrid())
}
// WatchSubAdd calls the 'watchSub' op to add to an existing subscription. If `lease` is 0 or less, no lease is added
// to the subscription.
func (client *Client) WatchSubAdd(
watchId string,
lease haystack.Number,
ids []haystack.Ref,
) (haystack.Grid, error) {
meta := map[string]haystack.Val{"watchId": haystack.NewStr(watchId)}
if lease.Float() > 0 {
meta["lease"] = lease
}
gb := haystack.NewGridBuilder()
gb.AddMeta(meta)
gb.AddColNoMeta("ids")
for _, id := range ids {
gb.AddRow([]haystack.Val{id})
}
return client.Call("watchSub", gb.ToGrid())
}
// WatchUnsub calls the 'watchUnsub' op to delete or remove entities from a existing subscription. If `lease` is 0
// or less, no lease is added to the subscription.
func (client *Client) WatchUnsub(
watchId string,
ids []haystack.Ref,
) (haystack.Grid, error) {
meta := map[string]haystack.Val{"watchId": haystack.NewStr(watchId)}
if len(ids) <= 0 {
meta["close"] = haystack.NewMarker()
}
gb := haystack.NewGridBuilder()
gb.AddMeta(meta)
gb.AddColNoMeta("ids")
for _, id := range ids {
gb.AddRow([]haystack.Val{id})
}
return client.Call("watchUnsub", gb.ToGrid())
}
// WatchPoll calls the 'watchPoll' op to poll values of a subscription.
func (client *Client) WatchPoll(
watchId string,
refresh bool,
) (haystack.Grid, error) {
meta := map[string]haystack.Val{"watchId": haystack.NewStr(watchId)}
if refresh {
meta["refresh"] = haystack.NewMarker()
}
gb := haystack.NewGridBuilder()
gb.AddMeta(meta)
return client.Call("watchPoll", gb.ToGrid())
}
// PointWriteStatus calls the 'pointWrite' op to query the point write priority array status for the input id.
func (client *Client) PointWriteStatus(id haystack.Ref) (haystack.Grid, error) {
gb := haystack.NewGridBuilder()
gb.AddColNoMeta("id")
gb.AddRow([]haystack.Val{id})
return client.Call("pointWrite", gb.ToGrid())
}
// PointWrite calls the 'pointWrite' op to write the val to the given point.
func (client *Client) PointWrite(
id haystack.Ref,
level int,
val haystack.Val,
who string,
duration haystack.Number,
) (haystack.Grid, error) {
gb := haystack.NewGridBuilder()
gb.AddColNoMeta("id")
gb.AddColNoMeta("level")
gb.AddColNoMeta("val")
gb.AddColNoMeta("who")
gb.AddColNoMeta("duration")
gb.AddRow([]haystack.Val{
id,
haystack.NewNumber(float64(level), ""),
val,
haystack.NewStr(who),
duration,
})
return client.Call("pointWrite", gb.ToGrid())
}
// HisReadAbsDate calls the 'hisRead' op with an input absolute Date range.
func (client *Client) HisReadAbsDate(id haystack.Ref, from haystack.Date, to haystack.Date) (haystack.Grid, error) {
rangeString := from.ToZinc() + "," + to.ToZinc()
return client.HisRead(id, rangeString)
}
// HisReadAbsDateTime calls the 'hisRead' op with an input absolute DateTime range.
func (client *Client) HisReadAbsDateTime(id haystack.Ref, from haystack.DateTime, to haystack.DateTime) (haystack.Grid, error) {
rangeString := from.ToZinc() + "," + to.ToZinc()
return client.HisRead(id, rangeString)
}
// HisRead calls the 'hisRead' op with the given range string. See Haystack API docs for accepted rangeString values.
func (client *Client) HisRead(id haystack.Ref, rangeString string) (haystack.Grid, error) {
gb := haystack.NewGridBuilder()
gb.AddColNoMeta("id")
gb.AddColNoMeta("range")
gb.AddRow([]haystack.Val{
id,
haystack.NewStr(rangeString),
})
return client.Call("hisRead", gb.ToGrid())
}
// HisWrite calls the 'hisWrite' op with the given id and Dicts of history items. Only the "ts" and "val" fields from
// the history items are included.
func (client *Client) HisWrite(id haystack.Ref, hisItems []haystack.Dict) (haystack.Grid, error) {
gb := haystack.NewGridBuilder()
gb.AddMetaVal("id", id)
gb.AddColNoMeta("ts")
gb.AddColNoMeta("val")
gb.AddRowDicts(hisItems)
return client.Call("hisWrite", gb.ToGrid())
}
// InvokeAction calls the 'invokeAction' op with the given id, action name, and arguments.
func (client *Client) InvokeAction(id haystack.Ref, action string, args map[string]haystack.Val) (haystack.Grid, error) {
gb := haystack.NewGridBuilder()
gb.AddMetaVal("id", id)
gb.AddMetaVal("action", haystack.NewStr(action))
rowVals := []haystack.Val{}
for name, val := range args {
gb.AddColNoMeta(name)
rowVals = append(rowVals, val)
}
gb.AddRow(rowVals)
return client.Call("invokeAction", gb.ToGrid())
}
// Eval calls the 'eval' op to evaluate a vendor specific expression.
func (client *Client) Eval(expr string) (haystack.Grid, error) {
gb := haystack.NewGridBuilder()
gb.AddColNoMeta("expr")
gb.AddRow([]haystack.Val{haystack.NewStr(expr)})
return client.Call("eval", gb.ToGrid())
}
// Call executes the given operation. The request grid is posted to the client URI and the response is parsed as a grid.
func (client *Client) Call(op string, reqGrid haystack.Grid) (haystack.Grid, error) {
req := reqGrid.ToZinc()
resp, err := client.clientHTTP.postString(client.uri, client.auth, op, req)
if err != nil {
return haystack.EmptyGrid(), err
}
var reader io.ZincReader
reader.InitString(resp)
val, err := reader.ReadVal()
if err != nil {
return haystack.EmptyGrid(), err
}
switch val := val.(type) {
case haystack.Grid:
if val.Meta().Get("err") != haystack.NewNull() {
return haystack.EmptyGrid(), NewCallError(val)
}
return val, nil
default:
return haystack.EmptyGrid(), errors.New("result was not a grid")
}
}
// filterGrid creates a Grid consisting of a `filter` Str and `limit` Number columns.
// If a value of 0 or less is passed to limit, no limit is applied.
func filterGrid(filter string, limit int) haystack.Grid {
var limitVal haystack.Val
if limit <= 0 {
limitVal = haystack.NewNull()
} else {
limitVal = haystack.NewNumber(float64(limit), "")
}
gb := haystack.NewGridBuilder()
gb.AddColNoMeta("filter")
gb.AddColNoMeta("limit")
gb.AddRow([]haystack.Val{
haystack.NewStr(filter),
limitVal,
})
return gb.ToGrid()
}
// authMsg models a message in the Haystack authorization header format.
// They follow the form: "[scheme] <name1>=<val1>, <name2>=<val2>, ..."
type authMsg struct {
scheme string
attrs map[string]string
}
func authMsgFromString(str string) authMsg {
attrs := make(map[string]string)
attributeStrs := strings.Split(str, ",")
scheme := ""
// The first one MAY include the scheme but not necessarily. Handle both situations
firstAttr := attributeStrs[0]
if strings.Contains(attributeStrs[0], " ") {
schemeSplit := strings.Split(firstAttr, " ")
scheme = strings.TrimSpace(schemeSplit[0])
attributeStrs[0] = schemeSplit[1]
}
for _, attributeStr := range attributeStrs {
attributeSplit := strings.Split(attributeStr, "=")
name := strings.TrimSpace(attributeSplit[0])
val := strings.TrimSpace(attributeSplit[1])
attrs[name] = val
}
return authMsg{
scheme: scheme,
attrs: attrs,
}
}
func (authMsg *authMsg) get(attrName string) string {
return authMsg.attrs[attrName]
}
func (authMsg *authMsg) toString() string {
builder := new(strings.Builder)
if authMsg.scheme != "" {
builder.WriteString(strings.ToUpper(authMsg.scheme))
builder.WriteRune(' ')
}
firstVal := true
for name, val := range authMsg.attrs {
if firstVal {
firstVal = false
} else {
builder.WriteString(", ")
}
builder.WriteString(name)
if val != "" {
builder.WriteRune('=')
builder.WriteString(val)
}
}
return builder.String()
}
// clientHTTP is defined as an interface to allow dependency-injection testing
type clientHTTP interface {
// getAuthHeader returns the `Authorization` header to use
getAuthHeader(uri string, username string, password string) (string, error)
// postString posts the given request body to the given URI and returns the response body
postString(uri string, auth string, op string, reqBody string) (string, error)
}
// clientHTTPImpl is the default implementation of clientHTTP
type clientHTTPImpl struct {
httpClient *http.Client
}
func (clientHTTP *clientHTTPImpl) getAuthHeader(uri string, username string, password string) (string, error) {
req, _ := http.NewRequest("GET", uri+"about", nil)
reqAuth := authMsg{
scheme: "hello",
attrs: map[string]string{
"username": encoding.EncodeToString([]byte(username)),
},
}
clientHTTP.setStandardHeaders(req, reqAuth.toString())
resp, respErr := clientHTTP.httpClient.Do(req)
if respErr != nil {
return "", respErr
}
// If we get 200, authentication is not required
if resp.StatusCode == 200 {
return "", nil
}
respWwwAuthenticate := resp.Header.Get("WWW-Authenticate")
respServer := resp.Header.Get("Server")
respSetCookie := resp.Header.Get("Set-Cookie")
resp.Body.Close()
if respWwwAuthenticate == "" {
return "", NewAuthError("Missing required header: WWW-Authenticate")
}
if resp.StatusCode != 401 {
return "", NewHTTPError(resp.StatusCode, "`about` endpoint with HELLO scheme returned a non 401 status: "+resp.Status)
}
// First try Haystack standard authentication scheme
haystackAuthHeader, haystackErr := clientHTTP.haystackAuth(uri, username, password, respWwwAuthenticate)
if haystackErr == nil {
return haystackAuthHeader, nil
}
// If we can't authenticate with Haystack, try basic auth
isBasicAuth := strings.Contains(strings.ToLower(respWwwAuthenticate), "basic")
isNiagara := strings.Contains(strings.ToLower(respServer), "niagara") || strings.Contains(strings.ToLower(respSetCookie), "niagara")
if isBasicAuth || isNiagara {
return clientHTTP.basicAuth(uri, username, password)
}
return haystackAuthHeader, haystackErr
}
func (clientHTTP *clientHTTPImpl) haystackAuth(uri string, username string, password string, wwwAuthenticate string) (string, error) {
helloAuth := authMsgFromString(wwwAuthenticate)
var authToken string
var authErr error
switch strings.ToUpper(helloAuth.scheme) {
case "SCRAM":
authToken, authErr = clientHTTP.authTokenFromScram(uri, username, password, helloAuth.get("handshakeToken"), helloAuth.get("hash"))
case "PLAINTEXT":
authToken, authErr = clientHTTP.authTokenFromPlaintext(uri, username, password)
default:
return "", NewAuthError("Auth scheme not supported: " + helloAuth.scheme)
}
if authErr != nil {
return "", authErr
}
finalAuth := authMsg{
scheme: "bearer",
attrs: map[string]string{
"authToken": authToken,
},
}
return finalAuth.toString(), nil
}
func (clientHTTP *clientHTTPImpl) basicAuth(uri string, username string, password string) (string, error) {
basicAuth := authMsg{
scheme: "basic",
attrs: map[string]string{
"username": encoding.EncodeToString([]byte(username)),
"password": encoding.EncodeToString([]byte(password)),
},
}
// Test the basic auth to ensure that it works
req, _ := http.NewRequest("GET", uri+"about", nil)
clientHTTP.setStandardHeaders(req, basicAuth.toString())
resp, _ := clientHTTP.httpClient.Do(req)
if resp.StatusCode != http.StatusOK {
return "", NewAuthError("Basic auth failed with status: " + resp.Status)
}
return basicAuth.toString(), nil
}
func (clientHTTP *clientHTTPImpl) postString(uri string, auth string, op string, reqBody string) (string, error) {
reqReader := strings.NewReader(reqBody)
req, _ := http.NewRequest("POST", uri+op, reqReader)
clientHTTP.setStandardHeaders(req, auth)
req.Header.Add("Connection", "Close")
resp, respErr := clientHTTP.httpClient.Do(req)
if respErr != nil {
return "", respErr
}
if resp.StatusCode != http.StatusOK {
return "", NewHTTPError(resp.StatusCode, resp.Status)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
return string(body), err
}
func (clientHTTP *clientHTTPImpl) authTokenFromScram(
uri string,
username string,
password string,
handshakeToken string,
hashName string,
) (string, error) {
var hash func() hash.Hash
switch strings.ToUpper(hashName) {
case "SHA-256":
hash = sha256.New
case "SHA-512":
hash = sha512.New
default: // Only support SHA-256 and SHA-512
return "", NewAuthError("Auth hash not supported: " + hashName)
}
var in []byte
var scram = auth.NewScram(hash, username, password)
var authToken string
for !scram.Step(in) {
out := scram.Out()
req, _ := http.NewRequest("GET", uri+"about", nil)
reqAuth := authMsg{
scheme: "scram",
attrs: map[string]string{
"handshakeToken": handshakeToken,
"data": encoding.EncodeToString(out),
},
}
clientHTTP.setStandardHeaders(req, reqAuth.toString())
resp, _ := clientHTTP.httpClient.Do(req)
if resp.StatusCode != http.StatusUnauthorized && resp.StatusCode != http.StatusOK { // We expect unauthorized until complete.
return "", NewHTTPError(resp.StatusCode, resp.Status)
}
respAuthString := resp.Header.Get("WWW-Authenticate")
if respAuthString == "" { // This header switches to Authentication-Info on success
respAuthString = resp.Header.Get("Authentication-Info")
}
respAuth := authMsgFromString(respAuthString)
handshakeToken = respAuth.get("handshakeToken") // it grows over time
dataEnc := respAuth.get("data")
authToken = respAuth.get("authToken") // This will only be set on the last message
data, _ := encoding.DecodeString(dataEnc)
in = data
}
if scram.Err() != nil {
return "", scram.Err()
}
return authToken, nil
}
func (clientHTTP *clientHTTPImpl) authTokenFromPlaintext(
uri string,
username string,
password string,
) (string, error) {
reqAuth := authMsg{
scheme: "plaintext",
attrs: map[string]string{
"username": encoding.EncodeToString([]byte(username)),
"password": encoding.EncodeToString([]byte(password)),
},
}
req, _ := http.NewRequest("GET", uri+"about", nil)
clientHTTP.setStandardHeaders(req, reqAuth.toString())
resp, _ := clientHTTP.httpClient.Do(req)
if resp.StatusCode != http.StatusOK {
return "", NewHTTPError(resp.StatusCode, resp.Status)
}
respAuthString := resp.Header.Get("Authentication-Info")
respAuth := authMsgFromString(respAuthString)
return respAuth.get("authToken"), nil
}
func (clientHTTP *clientHTTPImpl) setStandardHeaders(req *http.Request, auth string) {
req.Header.Add("Authorization", auth)
req.Header.Add("User-Agent", userAgent)
req.Header.Add("Content-Type", "text/zinc; charset=utf-8")
req.Header.Add("Accept", "text/zinc")
}
/////////////////////
// Errors
/////////////////////
// AuthError represents an error in the authorization
type AuthError struct {
Message string
}
// NewAuthError creates a new AuthError object.
func NewAuthError(message string) AuthError {
return AuthError{Message: message}
}
func (err AuthError) Error() string {
return "Auth error: " + err.Message
}
// CallError occurs when communication is successful, and a Grid is returned, but the grid has an err
// tag indicating a server side error.
type CallError struct {
Grid haystack.Grid
}
// NewCallError creates a new CallError object.
func NewCallError(grid haystack.Grid) CallError {
return CallError{Grid: grid}
}
func (err CallError) Error() string {
dis := err.Grid.Meta().Get("dis")
switch val := dis.(type) {
case haystack.Str:
return "Call error: " + val.String()
default:
return "Call error: Server side error"
}
}
// HTTPError occurs when communication is successful with a server, but we receive an HTTP error response.
type HTTPError struct {
Code int
Message string
}
// NewHTTPError creates a new HTTPError object.
func NewHTTPError(code int, message string) HTTPError {
return HTTPError{Code: code, Message: message}
}
func (err HTTPError) Error() string {
return "HTTP error: " + err.Message
}
// NetworkError occurs when there is a network I/O or connection problem with communication to the server.
type NetworkError struct {
Message string
}
// NewNetworkError creates a new NetworkError object.
func NewNetworkError(message string) NetworkError {
return NetworkError{Message: message}
}
func (err NetworkError) Error() string {
return "Network error: " + err.Message
}