/
transports.go
67 lines (56 loc) · 1.92 KB
/
transports.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
package qp
import (
"errors"
"fmt"
"github.com/stretchr/pat/start"
)
// ErrNotRunning is returned when an method is
// called on a transport that is not running.
var ErrNotRunning = errors.New("transport is not running")
// ErrRunning is returned when an method is
// called on a transport that is running.
var ErrRunning = errors.New("transport is running")
// Message represents a single message of data and its source.
type Message struct {
// The channel the Message came from.
Source string
// The data of the message.
Data []byte
}
func (m *Message) String() string {
return fmt.Sprintf("[%s %v]", m.Source, string(m.Data))
}
// Handler represents types capable of handling messages
// from the transports.
type Handler interface {
Handle(msg *Message)
}
// HandlerFunc represents functions capable of handling
// messages.
type HandlerFunc func(msg *Message)
// Handle calls the HandlerFunc.
func (f HandlerFunc) Handle(msg *Message) {
f(msg)
}
// PubSubTransport represents a transport capable of
// providing publish/subscribe capabilities.
type PubSubTransport interface {
start.StartStopper
// Publish publishes data on the specified channel.
Publish(channel string, data []byte) error
// Subscribe binds the handler to the specified channel.
// Only one handler can be associated with a given channel.
// Multiple calls to Subscribe with the same channel will replace the previous handler.
Subscribe(channel string, handler Handler) error
}
// DirectTransport represents a transport capable of
// providing request/response capabilities.
type DirectTransport interface {
start.StartStopper
// Send sends data on the channel.
Send(channel string, data []byte) error
// OnMessage binds the handler to the specified channel.
// Only one handler can be associated with a given channel.
// Multiple calls to OnMessage wiht the same channel will replace the previous handler.
OnMessage(channel string, handler Handler) error
}