-
Notifications
You must be signed in to change notification settings - Fork 5
/
encoder.go
71 lines (58 loc) · 1.82 KB
/
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
63
64
65
66
67
68
69
70
71
package avroutil
import (
"context"
"github.com/arquivei/foundationkit/errors"
"github.com/arquivei/foundationkit/schemaregistry"
"github.com/hamba/avro/v2"
)
// Encoder is able to transform golang's concrete types into avro's wire format
type Encoder interface {
// Encode encodes @input in the wire format
Encode(input interface{}) ([]byte, error)
}
type implEncoder struct {
wireFormatEncoder WireFormatEncoder
writerSchema avro.Schema
avroAPI avro.API
}
// NewEncoder returns a concrete implementation of Decoder, that
// fetches schemas in schema registry
// Parameters:
// - @schemaRepository: repository for avro schemas.
// - @writerSchemaStr: avro schema, in the AVSC format, used to marshall the
// objects. This schema must be previously registered in the schema registry
// exactly as provided.
func NewEncoder(
ctx context.Context,
schemaRepository schemaregistry.Repository,
subject schemaregistry.Subject,
writerSchemaStr string,
options ...option,
) (Encoder, error) {
const op = errors.Op("avroutil.NewEncoder")
encoder, err := NewWireFormatEncoder(ctx, schemaRepository, subject, writerSchemaStr)
if err != nil {
return nil, errors.E(op, err)
}
parsedAvroSchema, err := avro.Parse(writerSchemaStr)
if err != nil {
return nil, errors.E(op, err)
}
return &implEncoder{
wireFormatEncoder: encoder,
writerSchema: parsedAvroSchema,
avroAPI: newConfig(options...).Freeze(),
}, nil
}
func (e *implEncoder) Encode(input interface{}) ([]byte, error) {
const op = errors.Op("avroutil.implEncoder.Encode")
avroData, err := e.avroAPI.Marshal(e.writerSchema, input)
if err != nil {
return nil, errors.E(op, err)
}
wireFormat, err := e.wireFormatEncoder.BinaryToWireFormat(avroData)
if err != nil {
return nil, errors.E(op, err)
}
return wireFormat, nil
}