This repository has been archived by the owner on Apr 16, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
client.go
96 lines (83 loc) · 2.28 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
package skynet
import (
"fmt"
"io"
"net/http"
"net/url"
"gitlab.com/NebulousLabs/errors"
)
type (
// SkynetClient is the Skynet Client which can be used to access Skynet.
SkynetClient struct {
PortalURL string
Options Options
}
// requestOptions contains the options for a request.
requestOptions struct {
Options
method string
reqBody io.Reader
extraPath string
query url.Values
}
)
// New creates a new Skynet Client which can be used to access Skynet.
func New() SkynetClient {
return NewCustom("", Options{})
}
// NewCustom creates a new Skynet Client with a custom portal URL and options.
// Pass in "" for the portal to let the function select one for you.
func NewCustom(portalURL string, customOptions Options) SkynetClient {
if portalURL == "" {
portalURL = DefaultPortalURL()
}
return SkynetClient{
PortalURL: portalURL,
Options: customOptions,
}
}
// executeRequest makes and executes a request.
func (sc *SkynetClient) executeRequest(config requestOptions) (*http.Response, error) {
url := sc.PortalURL
method := config.method
reqBody := config.reqBody
// Set options, prioritizing options passed to the API calls.
opts := sc.Options
if config.EndpointPath != "" {
opts.EndpointPath = config.EndpointPath
}
if config.APIKey != "" {
opts.APIKey = config.APIKey
}
if config.CustomUserAgent != "" {
opts.CustomUserAgent = config.CustomUserAgent
}
if config.customContentType != "" {
opts.customContentType = config.customContentType
}
// Make the URL.
url = makeURL(url, opts.EndpointPath, config.extraPath, config.query)
// Create the request.
req, err := http.NewRequest(method, url, reqBody)
if err != nil {
return nil, errors.AddContext(err, fmt.Sprintf("could not create %v request", method))
}
if opts.APIKey != "" {
req.SetBasicAuth("", opts.APIKey)
}
if opts.CustomUserAgent != "" {
req.Header.Set("User-Agent", opts.CustomUserAgent)
}
if opts.customContentType != "" {
req.Header.Set("Content-Type", opts.customContentType)
}
// Execute the request.
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, errors.AddContext(err, "could not execute request")
}
if resp.StatusCode >= 400 {
return nil, errors.AddContext(makeResponseError(resp), "error code received")
}
return resp, nil
}