Home > Enterprise >  How to use camelCase JSON tags for marshaling structs in gRPC generated files in Go?
How to use camelCase JSON tags for marshaling structs in gRPC generated files in Go?

Time:07-17

take the struct below as an example,

type Foo struct {
    state         protoimpl.MessageState
    sizeCache     protoimpl.SizeCache
    unknownFields protoimpl.UnknownFields

    IsBar         bool            `protobuf:"varint,1,opt,name=is_bar,json=isBar,proto3" json:"is_bar,omitempty"`

IsBar has two JSON tags. When I'm trying to json.Marshal, the second tag is used, which is snake_case, but I prefer to use camelCase one. How is it possible?

CodePudding user response:

using protojson package to marshal your proto.Message

import(
  "google.golang.org/protobuf/encoding/protojson"
  "google.golang.org/protobuf/proto"
)

func Marshal(m proto.Message)([]byte,error){
   return (protojson.MarshalOptions{}).Marshal(m)
}
 

CodePudding user response:

Or try the gofaster. It's a protoc plugin alternative protoc-gen-go. It support the field extension gogoproto.jsontag which let you custome json tag.

syntax = "proto3";

package helloworld.v1;

import "google/api/annotations.proto";

import "gogo/protobuf/gogoproto/gogo.proto";

option go_package = "github.com/pigfall/kratos-test/api/helloworld/v1;v1";

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {
    option (google.api.http) = {
      get: "/helloworld/{name}"
    };
  }
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
  string pre_name =2 [(gogoproto.jsontag)="perName"];
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}


  • Related