-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
78 lines (68 loc) · 1.54 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
package lbapi
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"time"
)
// Client is the structure for reseller API access to LogicBoxes systems.
type Client struct {
http.Client
// URL of the API, usually https://httpapi.com.
URL string
// ID of the reseller.
ID string
// Key to authenticate with.
Key string
}
// NewClient creates a client structure with a HTTP client for the specified API.
func NewClient(api string, resellerid int64, apikey string) *Client {
if api == "" {
api = APIURL
}
return &Client{
Client: http.Client{Timeout: time.Second * 30},
URL: api,
ID: fmt.Sprintf("%d", resellerid),
Key: apikey,
}
}
// GetReponse fetches a URL's JSON, decode it into a maplist
// and returns it as a map of strings.
func GetResponse(c http.Client, url string) (*maplist, error) {
res, err := c.Get(url)
if err != nil {
return nil, err
}
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
var list maplist
err = decoder.Decode(&list)
if err != nil {
return nil, err
}
s, ok := list["status"]
if ok {
if s == "ERROR" {
return nil, errors.New(string(list["message"].(string)))
}
}
return &list, nil
}
// PostResponse does pretty much the same as getResponse(),
// but with the POST method.
func PostResponse(c http.Client, url string) (*maplist, error) {
res, err := c.Post(url, "", nil)
if err != nil {
return nil, err
}
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
var list maplist
err = decoder.Decode(&list)
if err != nil {
return nil, err
}
return &list, nil
}