Skip to content

Instantly share code, notes, and snippets.

@songx23
Created July 6, 2022 05:13
Show Gist options
  • Save songx23/ee2fcecd4448c0b2a1382eca9db50be9 to your computer and use it in GitHub Desktop.
Save songx23/ee2fcecd4448c0b2a1382eca9db50be9 to your computer and use it in GitHub Desktop.
Example code to convert Go structure to binary using Avro codec
type Book struct {
Name string `json:"Name" avro:"Name" mapstructure:"Name"`
Author string `json:"Author" avro:"Author" mapstructure:"Author"`
Genre string `json:"Genre" avro:"Genre" mapstructure:"Genre"`
Rating int `json:"Rating" avro:"Rating" mapstructure:"Rating"`
}
func (b *Book) ToBinary(schema string) ([]byte, error) {
j, err := json.Marshal(b)
if err != nil {
return nil, err
}
codec, err := goavro.NewCodec(schema)
if err != nil {
return nil, err
}
nat, _, err := codec.NativeFromTextual(j)
if err != nil {
return nil, err
}
bin, err := codec.BinaryFromNative(nil, nat)
if err != nil {
return nil, err
}
return bin, nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment