-
Notifications
You must be signed in to change notification settings - Fork 0
/
incoming.go
78 lines (58 loc) · 1.21 KB
/
incoming.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
package bearychat
import (
"bytes"
"encoding/json"
"errors"
"net/http"
"time"
)
type IncomingClient struct {
client *http.Client
}
type ClientOption func(*IncomingClient)
func NewIncomingClient(opts ...ClientOption) *IncomingClient {
cli := &IncomingClient{
client: &http.Client{},
}
cli.Options(opts...)
return cli
}
func (p *IncomingClient) Send(url string, msg *Message) (resp *IncomingResponse, err error) {
if len(url) == 0 {
err = errors.New("url is empty")
return
}
body, err := json.Marshal(msg)
if err != nil {
return
}
httpResp, err := p.client.Post(url, "application/json", bytes.NewBuffer(body))
if err != nil {
return
}
defer httpResp.Body.Close()
r := IncomingResponse{}
decoder := json.NewDecoder(httpResp.Body)
decoder.UseNumber()
err = decoder.Decode(&r)
if err != nil {
return
}
resp = &r
return
}
func (p *IncomingClient) Options(opts ...ClientOption) {
for i := 0; i < len(opts); i++ {
opts[i](p)
}
}
func TransportOption(transport *http.Transport) ClientOption {
return func(c *IncomingClient) {
c.client.Transport = transport
}
}
func TimeoutOption(timeout time.Duration) ClientOption {
return func(c *IncomingClient) {
c.client.Timeout = timeout
}
}