-
Notifications
You must be signed in to change notification settings - Fork 0
/
rpc.go
97 lines (84 loc) · 2.12 KB
/
rpc.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
package raftgo
import (
"bytes"
"context"
"encoding/json"
"log"
"net/http"
"time"
)
type Peer interface {
AppendEntries(aea AppendEntriesArgs, timeout time.Duration) (AppendEntriesReply, error)
RequestVote(rv RequestVoteArgs, timeout time.Duration) (RequestVoteReply, error)
}
type HttpPeer struct {
Addr string
}
func NewHttpPeer(addr string) *HttpPeer {
return &HttpPeer{Addr: addr}
}
func (p *HttpPeer) AppendEntries(aea AppendEntriesArgs, timeout time.Duration) (AppendEntriesReply, error) {
res, err := p.post("append_entries", aea, timeout)
if err != nil {
return AppendEntriesReply{}, err
}
ress := MapToJsonStruct2(res)
return ress.(AppendEntriesReply), nil
}
func (p *HttpPeer) RequestVote(rv RequestVoteArgs, timeout time.Duration) (RequestVoteReply, error) {
res, err := p.post("request_vote", rv, timeout)
if err != nil {
return RequestVoteReply{}, err
}
ress := MapToJsonStruct1(res)
return ress.(RequestVoteReply), nil
}
func MapToJsonStruct1(res interface{}) interface{} {
jsonBytes, err := json.Marshal(res)
if err != nil {
log.Fatal(err)
}
var reply RequestVoteReply
err = json.Unmarshal(jsonBytes, &reply)
if err != nil {
log.Fatal(err)
}
return reply
}
func MapToJsonStruct2(res interface{}) interface{} {
jsonBytes, err := json.Marshal(res)
if err != nil {
log.Fatal(err)
}
var reply AppendEntriesReply
err = json.Unmarshal(jsonBytes, &reply)
if err != nil {
log.Fatal(err)
}
return reply
}
func (p *HttpPeer) post(method string, data interface{}, timeout time.Duration) (interface{}, error) {
datas, err := json.Marshal(data)
if err != nil {
return nil, err
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
req, err := http.NewRequestWithContext(ctx, "POST", p.Addr+"/"+method, bytes.NewBuffer(datas))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result interface{}
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
return nil, err
}
return result, nil
}