-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder.go
62 lines (51 loc) · 961 Bytes
/
encoder.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
package router
import (
"encoding/json"
"fmt"
)
// LF represents LineFeed \n
var LF = []byte("\n")
type encoder interface {
Encode(*record) error
Buffer() buffer
}
type noneEncoder struct {
body buffer
}
func newNoneEncoder(body buffer) encoder {
return &noneEncoder{
body: body,
}
}
func (e *noneEncoder) Encode(rec *record) error {
if _, err := e.body.Write(rec.raw); err != nil {
return err
}
_, err := e.body.Write(LF)
return err
}
func (e *noneEncoder) Buffer() buffer {
return e.body
}
type jsonEncoder struct {
body buffer
}
func newJSONEncoder(body buffer) encoder {
return &jsonEncoder{
body: body,
}
}
func (e *jsonEncoder) Encode(rec *record) error {
bytes, err := json.Marshal(rec.parsed)
if err != nil {
return fmt.Errorf("json marshal: %w", err)
}
if _, err := e.body.Write(bytes); err != nil {
return err
}
_, err = e.body.Write(LF)
return err
}
func (e *jsonEncoder) Buffer() buffer {
return e.body
}