-
Notifications
You must be signed in to change notification settings - Fork 0
/
eclair.go
111 lines (92 loc) · 2.59 KB
/
eclair.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package eclair
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"strings"
"github.com/tidwall/gjson"
)
type Client struct {
Host string
Password string
}
func (c Client) baseURL() string {
if strings.HasPrefix(c.Host, "http") {
return c.Host
}
return "http://" + c.Host
}
func (c Client) authorizationHeader() string {
return "Basic " + base64.StdEncoding.EncodeToString([]byte(":"+c.Password))
}
type ErrorResponse struct {
Error string `json:"error"`
}
type Params map[string]interface{}
func (c *Client) Call(method string, data map[string]interface{}) (gjson.Result, error) {
r, err := http.NewRequest("POST", c.baseURL()+"/"+method, nil)
if err != nil {
return gjson.Result{},
fmt.Errorf("error creating http request to %s: %w", c.Host, err)
}
r.Header.Set("Accept", "application/json")
r.Header.Set("Authorization", c.authorizationHeader())
if data != nil {
body := &bytes.Buffer{}
writer := multipart.NewWriter(body)
for k, v := range data {
fw, err := writer.CreateFormField(k)
if err != nil {
return gjson.Result{},
fmt.Errorf("error creating form field %s: %w", k, err)
}
_, err = io.Copy(fw, strings.NewReader(fmt.Sprintf("%v", v)))
if err != nil {
return gjson.Result{},
fmt.Errorf("error adding field value %s=%v: %w", k, v, err)
}
}
if err := writer.Close(); err != nil {
return gjson.Result{}, fmt.Errorf("error closing form-data writer: %w", err)
}
r.Header.Set("Content-Type", writer.FormDataContentType())
r.Body = ioutil.NopCloser(bytes.NewReader(body.Bytes()))
}
w, err := http.DefaultClient.Do(r)
if err != nil {
return gjson.Result{}, fmt.Errorf("call to %s errored: %w", c.Host, err)
}
defer w.Body.Close()
b, err := ioutil.ReadAll(w.Body)
if err != nil {
return gjson.Result{}, fmt.Errorf("failed to read response body: %w", err)
}
if w.StatusCode >= 300 {
var errorResponse ErrorResponse
if err := json.Unmarshal(b, &errorResponse); err != nil {
text := string(b)
if len(text) > 200 {
text = text[:200]
}
return gjson.Result{},
fmt.Errorf("failed to decode json error response '%s': %w", text, err)
}
return gjson.Result{}, fmt.Errorf("eclair said: %s", errorResponse.Error)
}
var response interface{}
if err := json.Unmarshal(b, &response); err != nil {
text := string(b)
if len(text) > 200 {
text = text[:200]
}
return gjson.Result{},
fmt.Errorf("failed to decode json good response '%s': %w", text, err)
}
// now that we know the response is good json, we use gjson
return gjson.ParseBytes(b), nil
}