-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhttprpc.go
47 lines (38 loc) · 883 Bytes
/
httprpc.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
package httprpc
import (
"bytes"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
)
type RPCEncoder func(method string, args interface{}) ([]byte, error)
type RPCDecoder func(r io.Reader, reply interface{}) error
func CallRaw(address, method string, params, reply interface{}, contentType string, encoder RPCEncoder, decoder RPCDecoder) error {
enc, err := encoder(method, params)
if err != nil {
return err
}
res, err := http.Post(address, contentType, bytes.NewBuffer(enc))
if err != nil {
return err
}
resText, err := ioutil.ReadAll(res.Body)
if err != nil {
return err
}
reader := bytes.NewReader(resText)
res.Body.Close()
if res.StatusCode != 200 {
return errors.New(fmt.Sprintf("%s: %s", res.Status, string(resText)))
} else {
reader.UnreadByte()
err = decoder(reader, &reply)
if err != nil {
return err
}
return nil
}
return nil
}