forked from nytimes/gizmo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pub.go
99 lines (83 loc) · 2.23 KB
/
pub.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package http
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"time"
"github.com/NYTimes/gizmo/pubsub"
"github.com/golang/protobuf/proto"
"golang.org/x/net/context"
)
type publisher struct {
url string
client *http.Client
}
type gcpPublisher struct {
pubsub.Publisher
}
// NewPublisher will return a pubsub.Publisher that simply posts the payload to
// the given URL. If no http.Client is provided, the default one has a 5 second
// timeout.
func NewPublisher(url string, client *http.Client) pubsub.Publisher {
if client == nil {
client = &http.Client{
Timeout: 5 * time.Second,
}
}
return publisher{url: url, client: client}
}
// NewGCPStylePublisher will return a pubsub.Publisher that wraps the payload
// in a GCP pubsub.Message-like object that will make this publisher emulate
// Google's PubSub posting messages to a server.
// If no http.Client is provided, the default one has a 5 second
// timeout.
func NewGCPStylePublisher(url string, client *http.Client) pubsub.Publisher {
return gcpPublisher{NewPublisher(url, client)}
}
func (p publisher) Publish(ctx context.Context, key string, msg proto.Message) error {
payload, err := proto.Marshal(msg)
if err != nil {
return err
}
return p.PublishRaw(ctx, key, payload)
}
func (p publisher) PublishRaw(_ context.Context, _ string, payload []byte) error {
req, err := http.NewRequest("POST", p.url, bytes.NewReader(payload))
if err != nil {
return err
}
resp, err := p.client.Do(req)
if err != nil {
return err
}
if resp.StatusCode >= 400 {
respBody, _ := ioutil.ReadAll(resp.Body)
return fmt.Errorf("received an error response (%d): %s",
resp.StatusCode,
string(respBody),
)
}
return nil
}
type gcpPayload struct {
Message message `json:"message"`
}
type message struct {
Data []byte `json:"data"`
}
func (p gcpPublisher) Publish(ctx context.Context, key string, msg proto.Message) error {
payload, err := proto.Marshal(msg)
if err != nil {
return err
}
return p.PublishRaw(ctx, key, payload)
}
func (p gcpPublisher) PublishRaw(ctx context.Context, key string, msg []byte) error {
payload, err := json.Marshal(gcpPayload{Message: message{Data: msg}})
if err != nil {
return err
}
return p.Publisher.PublishRaw(ctx, key, payload)
}