generated from RTradeLtd/repo-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathswampi.go
56 lines (50 loc) · 1.22 KB
/
swampi.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
package swampi
import (
"io"
"net/http"
)
// Swampi is the swarm http api client
type Swampi struct {
c *http.Client
// the bare host (http://foobar:8500)
endpoint string
}
// New creates a new instance of swampi
func New(endpoint string) *Swampi {
return &Swampi{
c: &http.Client{},
endpoint: endpoint,
}
}
// Do executes the given http request
func (s *Swampi) Do(call APICall, req *http.Request) (*Response, error) {
resp, err := s.c.Do(req)
if err != nil {
return nil, err
}
return &Response{call, resp}, nil
}
// Send is a wrapper around constructCall + Do
func (s *Swampi) Send(call APICall, body io.Reader, headers map[string][]string, args ...interface{}) (*Response, error) {
req, err := s.constructCall(call, body, headers, s.endpoint+call.ParseArgs(args...))
if err != nil {
return nil, err
}
return s.Do(call, req)
}
func (s *Swampi) constructCall(call APICall, body io.Reader, headers map[string][]string, url string) (*http.Request, error) {
req, err := http.NewRequest(call.Method(), url, body)
if err != nil {
return nil, err
}
for k, v := range headers {
if len(v) == 1 {
req.Header.Set(k, v[0])
} else {
for _, vv := range v {
req.Header.Add(k, vv)
}
}
}
return req, nil
}