-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
90 lines (73 loc) · 2 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
79
80
81
82
83
84
85
86
87
88
89
90
package quorum
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
type HTTPClient struct {
client *http.Client
}
func NewHTTPClient() *HTTPClient {
return &HTTPClient{
client: &http.Client{},
}
}
func (d *HTTPClient) Join(ctx context.Context, target string, jreq *JoinRequest) (*JoinResponse, error) {
encodedArgs, err := json.Marshal(jreq)
if err != nil {
return nil, fmt.Errorf("Json error: %v", err)
}
bodyReader := bytes.NewReader(encodedArgs)
req, err := http.NewRequest("POST", "http://"+target+"/v1/join", bodyReader)
if err != nil {
return nil, fmt.Errorf("Error creating request: %v", err)
}
req = req.WithContext(ctx)
resp, err := d.client.Do(req)
if err != nil {
return nil, fmt.Errorf("Error from http requests: %v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Error parsing http response: %v", err)
}
var response *JoinResponse
err = json.Unmarshal(body, &response)
if err != nil {
return nil, fmt.Errorf("Error umarshaling json response: %v", err)
} else {
return response, nil
}
}
func (d *HTTPClient) Leave(ctx context.Context, target string, lreq *LeaveRequest) (*LeaveResponse, error) {
encodedArgs, err := json.Marshal(lreq)
if err != nil {
return nil, fmt.Errorf("Json error: %v", err)
}
bodyReader := bytes.NewReader(encodedArgs)
req, err := http.NewRequest("POST", "http://"+target+"/v1/leave", bodyReader)
if err != nil {
return nil, fmt.Errorf("Error creating request: %v", err)
}
req = req.WithContext(ctx)
resp, err := d.client.Do(req)
if err != nil {
return nil, fmt.Errorf("Error from http requests: %v", err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Error parsing http response: %v", err)
}
var response *LeaveResponse
err = json.Unmarshal(body, &response)
if err != nil {
return nil, fmt.Errorf("Error umarshaling json response: %v", err)
} else {
return response, nil
}
}