How to Work with Avro in Go

Use the goavro library to define schemas and encode/decode data in Go for efficient binary serialization.

Use the goavro library to define schemas, encode data into binary Avro, and decode it back into Go structs. Install the library and use avro.NewEncoder and avro.NewDecoder with a schema string to handle serialization.

package main

import (
	"bytes"
	"fmt"
	"github.com/hamba/avro/v2"
)

type Record struct {
	Name  string `avro:"name"`
	Age   int    `avro:"age"`
}

func main() {
	schema := `{"type":"record","name":"User","fields":[{"name":"name","type":"string"},{"name":"age","type":"int"}]}`
	buf := new(bytes.Buffer)
	enc, _ := avro.NewEncoder(schema, buf)
	dec, _ := avro.NewDecoder(schema, buf)

	data := Record{Name: "Alice", Age: 30}
	enc.Encode(data)

	var result Record
	dec.Decode(&result)
	fmt.Println(result)
}