Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add a simple JSON serializer #201

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 22 additions & 4 deletions codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,10 +52,11 @@ type Codec struct {
schemaCanonical string
typeName *name

nativeFromTextual func([]byte) (interface{}, []byte, error)
binaryFromNative func([]byte, interface{}) ([]byte, error)
nativeFromBinary func([]byte) (interface{}, []byte, error)
textualFromNative func([]byte, interface{}) ([]byte, error)
nativeFromTextual func([]byte) (interface{}, []byte, error)
binaryFromNative func([]byte, interface{}) ([]byte, error)
nativeFromBinary func([]byte) (interface{}, []byte, error)
textualFromNative func([]byte, interface{}) ([]byte, error)
simpleTextualFromNative func([]byte, interface{}) ([]byte, error)

Rabin uint64
}
Expand Down Expand Up @@ -471,6 +472,23 @@ func (c *Codec) TextualFromNative(buf []byte, datum interface{}) ([]byte, error)
return newBuf, nil
}

// SimpleTextualFromNative converts Go native data types to Avro data in JSON text format
// like TextualFromNative. The key difference is that SimpleTextualFromNative yields JSON text
// without embedding type information.
func (c *Codec) SimpleTextualFromNative(buf []byte, datum interface{}) ([]byte, error) {
var newBuf []byte
var err error
if c.simpleTextualFromNative != nil {
newBuf, err = c.simpleTextualFromNative(buf, datum)
} else {
newBuf, err = c.textualFromNative(buf, datum)
}
if err != nil {
return buf, err // if error, return original byte slice
}
return newBuf, nil
}

// Schema returns the original schema used to create the Codec.
func (c *Codec) Schema() string {
return c.schemaOriginal
Expand Down
88 changes: 88 additions & 0 deletions record.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
package goavro

import (
"encoding/json"
"fmt"
)

Expand Down Expand Up @@ -229,5 +230,92 @@ func makeRecordCodec(st map[string]*Codec, enclosingNamespace string, schemaMap
return genericMapTextEncoder(buf, datum, nil, codecFromFieldName)
}

c.simpleTextualFromNative = func(buf []byte, datum interface{}) ([]byte, error) {
// NOTE: Ensure only schema defined field names are encoded; and if
// missing in datum, either use the provided field default value or
// return an error.
sourceMap, ok := datum.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("cannot encode textual record %q: expected map[string]interface{}; received: %T", c.typeName, datum)
}
destMap := make(map[string]interface{}, len(codecFromIndex))
for fieldName := range codecFromFieldName {
fieldValue, ok := sourceMap[fieldName]
if !ok {
defaultValue, ok := defaultValueFromName[fieldName]
if !ok {
return nil, fmt.Errorf("cannot encode textual record %q field %q: schema does not specify default value and no value provided", c.typeName, fieldName)
}
fieldValue = defaultValue
}
destMap[fieldName] = fieldValue
}
datum = destMap
// NOTE: Setting `defaultCodec == nil` instructs genericMapTextEncoder
// to return an error when a field name is not found in the
// codecFromFieldName map.
return simpleRecordEncoder(buf, datum, codecFromFieldName)
}

return c, nil
}

func simpleRecordEncoder(buf []byte, datum interface{}, codecFromKey map[string]*Codec) ([]byte, error) {
mapValues, err := convertMap(datum)
if err != nil {
return nil, fmt.Errorf("cannot encode textual map: %s", err)
}

var atLeastOne bool

buf = append(buf, '{')

for key, value := range mapValues {
atLeastOne = true

// Find a codec for the key
fieldCodec := codecFromKey[key]
if fieldCodec == nil {
return nil, fmt.Errorf("cannot encode textual map: cannot determine codec: %q", key)
}
// Encode key string
buf, err = stringTextualFromNative(buf, key)
if err != nil {
return nil, err
}
buf = append(buf, ':')

b, err := fieldCodec.textualFromNative(nil, value)
if err != nil {
return nil, fmt.Errorf("cannot encode textual map: value for %q does not match its schema: %s", key, err)
}

var v interface{}
if err := json.Unmarshal(b, &v); err != nil {
return nil, fmt.Errorf("failed to unmarshal")
}

if vm, ok := v.(map[string]interface{}); ok {
v = getFirstElem(vm)
}
elem, err := json.Marshal(v)
if err != nil {
return nil, fmt.Errorf("failed to marshal")
}
buf = append(buf, elem...)

buf = append(buf, ',')
}

if atLeastOne {
return append(buf[:len(buf)-1], '}'), nil
}
return append(buf, '}'), nil
}

func getFirstElem(m map[string]interface{}) interface{} {
for _, v := range m {
return v
}
return nil
}