-
Notifications
You must be signed in to change notification settings - Fork 1
/
sink.go
52 lines (44 loc) · 1.01 KB
/
sink.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
package apirouter
import (
"bytes"
"context"
"github.com/KarpelesLab/pjson"
"github.com/coder/websocket"
"github.com/fxamacker/cbor/v2"
)
type EncoderInterface interface {
Encode(obj any) error
}
func EncoderSink(enc EncoderInterface) ResponseSink {
return &encoderSink{enc: enc}
}
type encoderSink struct {
enc EncoderInterface
}
func (e *encoderSink) SendResponse(r *Response) error {
return e.enc.Encode(r.getResponseData())
}
type websocketSink struct {
ctx context.Context
wsc *websocket.Conn
cbor bool
}
func (w *websocketSink) SendResponse(r *Response) error {
if w.cbor {
buf := &bytes.Buffer{}
enc := cbor.NewEncoder(buf)
err := enc.Encode(r.getResponseData())
if err != nil {
return err
}
return w.wsc.Write(w.ctx, websocket.MessageBinary, buf.Bytes())
} else {
buf := &bytes.Buffer{}
enc := pjson.NewEncoderContext(r.getJsonCtx(), buf)
err := enc.Encode(r.getResponseData())
if err != nil {
return err
}
return w.wsc.Write(w.ctx, websocket.MessageText, buf.Bytes())
}
}