-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprovider.go
86 lines (70 loc) · 1.83 KB
/
provider.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
package gonjalla
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type request struct {
Method string `json:"method"`
Params map[string]interface{} `json:"params"`
}
const endpoint string = "https://njal.la/api/1/"
// HTTPClient interface. Useful for mocked unit tests later on.
type HTTPClient interface {
Do(req *http.Request) (*http.Response, error)
}
var (
// Client used in all requests by Request. Can be overwritten for tests.
Client HTTPClient
)
func init() {
Client = &http.Client{}
}
// Request common function for all of Njalla's API.
// Njalla's API uses JSON-RPC, and contains just one endpoint.
// The endpoint is POST only, and takes in a JSON in the body, with two
// arguments, check the `request` struct for more info.
// The `params` argument is variable. Some methods require no parameters,
// (like `list-domains`), while other methods require parameters (like
// `get-domain` which requires `domain: string`).
func Request(
token string, method string, params map[string]interface{},
) ([]byte, error) {
token = fmt.Sprintf("Njalla %s", token)
body, err := json.Marshal(
request{Method: method, Params: params},
)
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", endpoint, bytes.NewBuffer(body))
if err != nil {
return nil, err
}
req.Header.Add("Authorization", token)
resp, err := Client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
jsonData, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
data := make(map[string]interface{})
err = json.Unmarshal(jsonData, &data)
if err != nil {
return nil, err
}
result, ok := data["result"]
if !ok {
return nil, fmt.Errorf("Missing result %s", data)
}
unwrapped, err := json.Marshal(result)
if err != nil {
return nil, err
}
return unwrapped, nil
}