golang / protobuf

Go support for Google's protocol buffers

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Option to tell protoc to remove `omitempty` field from json tags when generating .go files

GooDeeJAY opened this issue · comments

Problem

When I generate .pb.go files using protoc, its generating structs with json tags where there are omitempty option in each of the fields:

Proto3:

message MyMessage{
    string id = 1;
    MyType type = 2;
    bool isFoo = 3;
}

Generated go struct:

type MyMessage struct {
    ...    
    Id       string   `protobuf:"bytes,1,opt,name=id,proto3" json:"id,omitempty"`
    Type     MyType   `protobuf:"varint,2,opt,name=type,proto3,enum=some_service.MyType" json:"type,omitempty"`
    IsFoo    bool     `protobuf:"varint,3,opt,name=onboarded,proto3" json:"onboarded,omitempty"`
}

Solutions

Option to tell protoc compiler to not generate structs with omitempty json tags (For example some arg like protoc --json-emitall)


Protobuf to support json-tag related options:

For example, on the top of the .proto file:

option json-emitall="true";

Or, support for some per message option like:

message Foo {
    string id = 1;
    
    option json-tags = "";
}

Desired Result

So that I can get:

type MyMessage struct {
    ...    
    Id       string   `protobuf:"bytes,1,opt,name=id,proto3" json:"id"`
    Type     MyType   `protobuf:"varint,2,opt,name=type,proto3,enum=some_service.MyType" json:"type"`
    IsFoo    bool     `protobuf:"varint,3,opt,name=onboarded,proto3" json:"onboarded"`
}

The JSON tags are considered a deprecated feature of protobuf generation, as one should be using the protojson package, instead of the standard library’s encoding/json which has several caveats to its usage that mean that the official proto3 JSON mapping could not be implemented properly with it.

The JSON tags are considered a deprecated feature of protobuf generation, as one should be using the protojson package, instead of the standard library’s encoding/json which has several caveats to its usage that mean that the official proto3 JSON mapping could not be implemented properly with it.

What caveats is there? protojson has a lot unexpected behaviour i prefer avoid using it replacing with JSONBuiltin. The only trouble i faced - hardcoded omitempty by the compiler.

What caveats is there?

The caveats that it cannot correctly implement the proto3 JSON mapping standard.