Skip to content

pubgo/protoc-gen-retag

Repository files navigation

protoc-gen-retag

Go Reference CI Go Report Card

中文文档

A protoc plugin that allows you to add custom Go struct tags to generated protobuf files.

Features

  • Add custom struct tags (e.g., graphql, xml, validate) to protobuf-generated Go structs
  • Modify existing tags (e.g., override default json tag)
  • Support for oneof fields
  • Preserves original protobuf/json tags while adding new ones

Installation

go install github.com/pubgo/protoc-gen-retag@latest

Usage

1. Import the retag proto file

import "proto/retag/retag.proto";

2. Add custom tags to your fields

syntax = "proto3";

package example;

import "proto/retag/retag.proto";

message User {
    // Add a new graphql tag
    string name = 1 [
        (retag.tags) = {name: "graphql", value: "userName,optional"}
    ];

    // Add multiple custom tags
    string email = 2 [
        (retag.tags) = {name: "graphql", value: "userEmail"},
        (retag.tags) = {name: "validate", value: "required,email"}
    ];

    // Override the default json tag
    string user_id = 3 [
        (retag.tags) = {name: "json", value: "id,omitempty"}
    ];

    // Support for oneof fields
    oneof contact {
        option (retag.oneof_tags) = {name: "graphql", value: "contact,optional"};
        string phone = 4;
        string address = 5;
    }
}

3. Generate Go code

protoc --go_out=. --retag_out=. your.proto

Or with buf:

# buf.gen.yaml
version: v1
plugins:
  - plugin: go
    out: gen
    opt: paths=source_relative
  - plugin: retag
    out: gen
    opt: paths=source_relative

Generated Output

The generated Go struct will include your custom tags:

type User struct {
    Name   string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty" graphql:"userName,optional"`
    Email  string `protobuf:"bytes,2,opt,name=email,proto3" json:"email,omitempty" graphql:"userEmail" validate:"required,email"`
    UserId string `protobuf:"bytes,3,opt,name=user_id,json=userId,proto3" json:"id,omitempty"`
    // ...
}

Tag Options

Extension Scope Description
retag.tags Field Add/modify tags on message fields
retag.oneof_tags Oneof Add tags on oneof fields

Credits

This project is inspired by and based on protoc-gen-go-tag.

License

MIT License

About

一个 protoc 插件,用于在生成的 protobuf Go 文件中添加自定义 struct tags

Resources

License

Stars

Watchers

Forks

Packages

 
 
 

Contributors

Languages