forked from whyrusleeping/zmsg
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrpc.go
More file actions
67 lines (54 loc) · 1.3 KB
/
rpc.go
File metadata and controls
67 lines (54 loc) · 1.3 KB
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
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"strings"
)
type Error struct {
Code int `json:"code"`
Message string `json:"message"`
}
func (e Error) Error() string {
return fmt.Sprintf("error %d: %s", e.Code, e.Message)
}
type Response struct {
Result interface{} `json:"result"`
Error Error `json:"error"`
}
type Request struct {
Method string `json:"method"`
Params interface{} `json:"params"`
}
func request(obj *Request, out interface{}) error {
data, err := json.Marshal(obj)
if err != nil {
return err
}
body := bytes.NewReader(data)
req, err := http.NewRequest("POST", "http://localhost:8232/", body)
if err != nil {
return err
}
// auth auth baby
req.Header.Add("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":"+password)))
resp, err := http.DefaultClient.Do(req)
if err != nil {
if strings.Contains(err.Error(), "connection refused") {
return fmt.Errorf("failed to connect to zcash daemon, is it running?")
}
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
var res Response
err := json.NewDecoder(resp.Body).Decode(&res)
if err != nil {
fmt.Println("error reading http body: ", err)
}
return res.Error
}
return json.NewDecoder(resp.Body).Decode(out)
}