/
client.go
56 lines (48 loc) · 1.13 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
package flarehttp
import (
"bytes"
"context"
"github.com/flare-rpc/flarego"
"io"
"net/http"
"google.golang.org/protobuf/proto"
)
type clientConn struct {
target string
}
// Invoke performs a unary RPC and returns after the response is received
// into reply.
func (c *clientConn) Invoke(ctx context.Context, method string, args interface{}, reply interface{}, opts ...flarego.CallOption) error {
argmsg := args.(proto.Message)
replymsg := reply.(proto.Message)
buf, err := proto.Marshal(argmsg)
if err != nil {
return err
}
url := c.target + "/" + method
request, err := http.NewRequest("POST", url, bytes.NewReader(buf))
if err != nil {
return err
}
request.Header.Set("Content-Type", "application/proto")
request = request.WithContext(ctx)
resp, err := http.DefaultClient.Do(request)
if err != nil {
return err
}
defer resp.Body.Close()
buf, err = io.ReadAll(resp.Body)
if err != nil {
return err
}
err = proto.Unmarshal(buf, replymsg)
if err != nil {
return err
}
return nil
}
func dial(target string, options ...flarego.DialOption) (flarego.ClientConn, error) {
return &clientConn{
target: target,
}, nil
}