-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathpublisher.go
78 lines (63 loc) · 1.58 KB
/
publisher.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 gotfy
import (
"bytes"
"context"
"errors"
"fmt"
"net/http"
"net/url"
"github.com/goccy/go-json"
)
var (
ErrNoServer = errors.New("server is nil")
ErrNoTopic = errors.New("topic is nil")
)
// Publisher creates messages for topics
type Publisher struct {
server *url.URL
httpClient *http.Client
Headers http.Header
}
// NewPublisher creates a topic publisher for the specified server URL,
// and uses the supplied HTTP client to resolve the request
func NewPublisher(server *url.URL, httpClient *http.Client) (*Publisher, error) {
if server == nil {
return nil, ErrNoServer
}
if httpClient == nil {
httpClient = http.DefaultClient
}
return &Publisher{
server: server,
httpClient: httpClient,
Headers: http.Header{"Content-Type": []string{"application/json"}},
}, nil
}
func (t *Publisher) SendMessage(ctx context.Context, m *Message) (*PublishResp, error) {
buf, err := json.MarshalContext(ctx, m)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, t.server.String(), bytes.NewReader(buf))
if err != nil {
return nil, err
}
for name, headers := range t.Headers {
for _, h := range headers {
req.Header.Set(name, h)
}
}
resp, err := t.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if s := resp.StatusCode; s < 200 || s >= 300 {
return nil, fmt.Errorf("non-200 http response code from server: %d", s)
}
var pubResp PublishResp
if err = json.NewDecoder(resp.Body).DecodeContext(ctx, &pubResp); err != nil {
return nil, err
}
return &pubResp, nil
}