Created
July 6, 2022 05:13
-
-
Save songx23/ee2fcecd4448c0b2a1382eca9db50be9 to your computer and use it in GitHub Desktop.
Example code to convert Go structure to binary using Avro codec
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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