通过自定义结构体tag来覆盖默认结构体tag:json:"xxx,omitempty"

1. 修改proto文件,增加gotags注释

在需要修改结构体tag的字段上增加注释:// @gotags: json:"region_name" , 覆盖默认生成的结构体tag

# modules/resource_manager/idl/region.proto

message Region {
  // @gotags: json:"region_name"
  string region_name = 1;
}

字段末尾注释:

# modules/resource_manager/idl/region.proto

message Region {
  string region_name = 1;  // @gotags: json:"region_name"
}

添加多个自定义tag:

# modules/resource_manager/idl/region.proto

message Region {
  // @gotags: json:"region_name" validate:"required"
  string region_name = 1;
}

2. 生成pb.go文件

make build-region-proto

3. 使用protoc-go-inject-tag

安装protoc-go-inject-tag:

go install github.com/favadi/protoc-go-inject-tag@latest

运行protoc-go-inject-tag命令覆盖默认结构体tag:

protoc-go-inject-tag -remove_tag_comment -input=xxxx_path_to_pb_go_file.pb.go 

4. 通过makefile集成

install-protoc-go-inject-tag:
    @hash protoc-go-inject-tag > /dev/null 2>&1; if [ $$? -ne 0 ]; then \
        go install github.com/favadi/protoc-go-inject-tag@latest; \
    fi



build-user-proto: install-kitex install-protoc-go-inject-tag
    @cd modules/user_server && kitex -module westhpc.net/starryshore -no-fast-api -type protobuf -I ./ idl/service.proto   && protoc-go-inject-tag -remove_tag_comment -input=kitex_gen/user/service.pb.go

英雄之旅
8 声望1 粉丝