-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathavro.go
58 lines (52 loc) · 1.44 KB
/
avro.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
package zfmt
import (
"bytes"
"fmt"
"github.com/actgardner/gogen-avro/v10/compiler"
"github.com/actgardner/gogen-avro/v10/soe"
"github.com/actgardner/gogen-avro/v10/vm"
"github.com/actgardner/gogen-avro/v10/vm/types"
heetch "github.com/heetch/avro"
heetchtypegen "github.com/heetch/avro/avrotypegen"
)
// GeneratedAvroRecord combines interfaces that make Encoding/Decoding possible
// for gogen-avro struct
type GeneratedAvroRecord interface {
soe.AvroRecord
types.Field
Schema() string
}
type AvroFormatter struct{}
func (p *AvroFormatter) Marshall(v any) ([]byte, error) {
switch m := v.(type) {
case soe.AvroRecord:
buf := &bytes.Buffer{}
err := m.Serialize(buf)
return buf.Bytes(), err
case heetchtypegen.AvroRecord:
b, _, err := heetch.Marshal(v)
return b, err
default:
return nil, fmt.Errorf("%T, avro formatter supports only gogen-avro or heetch avro messages", v)
}
}
func (p *AvroFormatter) Unmarshal(b []byte, v any) error {
switch m := v.(type) {
case GeneratedAvroRecord:
r := bytes.NewReader(b)
deser, err := compiler.CompileSchemaBytes([]byte(m.Schema()), []byte(m.Schema()))
if err != nil {
return err
}
return vm.Eval(r, deser, m)
case heetchtypegen.AvroRecord:
t, err := heetch.ParseType(m.AvroRecord().Schema)
if err != nil {
return err
}
_, err = heetch.Unmarshal(b, v, t)
return err
default:
return fmt.Errorf("%T, avro formatter supports only gogen-avro or heetch avro messages", v)
}
}