forked from mostafa/xk6-kafka
-
Notifications
You must be signed in to change notification settings - Fork 0
/
avro.go
42 lines (35 loc) · 1.13 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
package kafka
type AvroSerde struct {
Serdes
}
// Serialize serializes a JSON object into Avro binary.
func (*AvroSerde) Serialize(data interface{}, schema *Schema) ([]byte, *Xk6KafkaError) {
jsonBytes, err := toJSONBytes(data)
if err != nil {
return nil, err
}
encodedData, _, originalErr := schema.Codec().NativeFromTextual(jsonBytes)
if originalErr != nil {
return nil, NewXk6KafkaError(failedToEncode, "Failed to encode data", originalErr)
}
bytesData, originalErr := schema.Codec().BinaryFromNative(nil, encodedData)
if originalErr != nil {
return nil, NewXk6KafkaError(failedToEncodeToBinary,
"Failed to encode data into binary",
originalErr)
}
return bytesData, nil
}
// Deserialize deserializes a Avro binary into a JSON object.
func (*AvroSerde) Deserialize(data []byte, schema *Schema) (interface{}, *Xk6KafkaError) {
decodedData, _, err := schema.Codec().NativeFromBinary(data)
if err != nil {
return nil, NewXk6KafkaError(
failedToDecodeFromBinary, "Failed to decode data", err)
}
if data, ok := decodedData.(map[string]interface{}); ok {
return data, nil
} else {
return nil, ErrInvalidDataType
}
}