-
Notifications
You must be signed in to change notification settings - Fork 214
/
write_structured_message.go
51 lines (42 loc) · 1.14 KB
/
write_structured_message.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
/*
Copyright 2021 The CloudEvents Authors
SPDX-License-Identifier: Apache-2.0
*/
package utils
import (
"context"
"io"
"github.com/cloudevents/sdk-go/v2/binding"
"github.com/cloudevents/sdk-go/v2/binding/format"
)
// WriteStructured fills the provided io.Writer with the binding.Message m in structured mode.
// Using context you can tweak the encoding processing (more details on binding.Write documentation).
func WriteStructured(ctx context.Context, m binding.Message, writer io.Writer, transformers ...binding.Transformer) error {
_, err := binding.Write(
ctx,
m,
wsMessageWriter{writer},
nil,
transformers...,
)
return err
}
type wsMessageWriter struct {
io.Writer
}
func (w wsMessageWriter) SetStructuredEvent(_ context.Context, _ format.Format, event io.Reader) error {
_, err := io.Copy(w.Writer, event)
if err != nil {
// Try to close anyway
_ = w.tryToClose()
return err
}
return w.tryToClose()
}
func (w wsMessageWriter) tryToClose() error {
if closer, ok := w.Writer.(io.WriteCloser); ok {
return closer.Close()
}
return nil
}
var _ binding.StructuredWriter = wsMessageWriter{} // Test it conforms to the interface