You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何利用Go结构体自动生成Avro Schema文件?求解决方案

从Go结构体生成Avro Schema的解决方案

推荐工具库

  • hamba/avro:这是一款成熟的Go Avro库,支持通过反射从Go结构体直接生成Avro Schema,完美适配你的需求,还支持用avro:结构体标签指定字段名及其他属性。
  • gogen-avro:主要用于从Avro Schema生成Go代码,但也提供反向生成Schema的命令行工具,适合需要批量处理的场景。

代码示例(基于hamba/avro)

首先安装依赖:

go get github.com/hamba/avro/v2

然后编写生成代码:

package main

import (
	"encoding/json"
	"fmt"
	"os"

	"github.com/hamba/avro/v2"
)

type User struct {
	ID        int    `avro:"id" json:"id"`
	Name      string `avro:"name" json:"name"`
	Age       int    `avro:"age" json:"age"`
	Email     string `avro:"email" json:"email"`
	Timestamp int64  `avro:"timestamp" json:"timestamp"`
}

func main() {
	// 从结构体生成Avro Schema对象
	schema, err := avro.GenerateSchema(&User{}, nil)
	if err != nil {
		fmt.Printf("生成Schema失败: %v\n", err)
		return
	}

	// 将Schema序列化为格式化的JSON
	jsonSchema, err := json.MarshalIndent(schema, "", "  ")
	if err != nil {
		fmt.Printf("JSON序列化失败: %v\n", err)
		return
	}

	// 写入到.avsc文件
	err = os.WriteFile("user.avsc", jsonSchema, 0644)
	if err != nil {
		fmt.Printf("写入文件失败: %v\n", err)
		return
	}

	fmt.Println("Avro Schema生成成功,已保存到user.avsc")
}

运行后生成的user.avsc内容如下:

{
  "type": "record",
  "name": "User",
  "fields": [
    {
      "name": "id",
      "type": "int"
    },
    {
      "name": "name",
      "type": "string"
    },
    {
      "name": "age",
      "type": "int"
    },
    {
      "name": "email",
      "type": "string"
    },
    {
      "name": "timestamp",
      "type": "long"
    }
  ]
}

关键注意事项

  • 结构体的avro:标签用于指定Avro字段名,若未设置,库会自动将结构体字段名转为小写作为Avro字段名。
  • Go类型与Avro类型自动映射:int→int、int64→long、string→string、指针类型(如*string)会生成可选类型["null", "string"]。
  • 若需要自定义Schema的命名空间、文档等元信息,可以在GenerateSchema的第二个参数中传入avro.SchemaOptions配置。

内容的提问来源于stack exchange,提问作者Yash Chauhan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 15:55:28