-
Notifications
You must be signed in to change notification settings - Fork 5
/
writer.go
64 lines (50 loc) · 1.71 KB
/
writer.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
package commander
import (
"github.com/jeroenrinzema/commander/internal/metadata"
"github.com/jeroenrinzema/commander/internal/types"
)
// NewWriter initializes a new response writer for the given value
func NewWriter(group *Group, parent *Message) Writer {
writer := &writer{
group: group,
parent: parent,
}
return writer
}
// Writer handle implementation for a given group and message
type Writer = types.Writer
// Writer is a struct representing the ResponseWriter interface
type writer struct {
group *Group
parent *Message
}
// NewMessage constructs a new message or a child of the parent.
func (writer *writer) NewMessage(action string, version int8, key []byte, data []byte) *Message {
if writer.parent != nil {
return writer.parent.NewMessage(action, types.Version(version), metadata.Key(key), data)
}
return types.NewMessage(action, version, key, data)
}
func (writer *writer) Error(action string, status types.StatusCode, err error) (*Message, error) {
if status == types.NullStatusCode {
status = types.StatusInternalServerError
}
var payload []byte
if err != nil {
payload = []byte(err.Error())
}
message := writer.NewMessage(action, 0, nil, payload)
message.Status = status
err = writer.group.ProduceEvent(message)
return message, err
}
func (writer *writer) Event(action string, version int8, key []byte, data []byte) (*Message, error) {
message := writer.NewMessage(action, version, key, data)
err := writer.group.ProduceEvent(message)
return message, err
}
func (writer *writer) Command(action string, version int8, key []byte, data []byte) (*Message, error) {
message := writer.NewMessage(action, version, key, data)
err := writer.group.ProduceCommand(message)
return message, err
}