-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
56 lines (44 loc) · 1.19 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 wow
import (
"context"
"encoding/gob"
"fmt"
"net"
)
type Client interface {
GetChallenge(ctx context.Context, rq *ChallengeRequest) (*ChallengeResponse, error)
GetQuote(ctx context.Context, rq *QuoteRequest) (*QuoteResponse, error)
}
type ClientConfig struct {
Address string
}
type client struct {
addr string
}
func NewClient(cfg *ClientConfig) Client {
return &client{addr: cfg.Address}
}
func (c *client) GetChallenge(ctx context.Context, rq *ChallengeRequest) (*ChallengeResponse, error) {
return request[ChallengeResponse](ctx, c.addr, rq)
}
func (c *client) GetQuote(ctx context.Context, rq *QuoteRequest) (*QuoteResponse, error) {
return request[QuoteResponse](ctx, c.addr, rq)
}
func request[T any](ctx context.Context, addr string, request any) (*T, error) {
var d net.Dialer
conn, err := d.DialContext(ctx, "tcp", addr)
if err != nil {
return nil, err
}
defer func() {
conn.Close()
}()
if err := gob.NewEncoder(conn).Encode(&request); err != nil {
return nil, fmt.Errorf("sending request: %w", err)
}
response := new(T)
if err := gob.NewDecoder(conn).Decode(response); err != nil {
return nil, fmt.Errorf("reading response: %w", err)
}
return response, nil
}