"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Integrate GORM Field Annotations into Protobuf Definitions?

How to Integrate GORM Field Annotations into Protobuf Definitions?

Published on 2024-11-08
Browse:866

How to Integrate GORM Field Annotations into Protobuf Definitions?

Integrating Field Annotations into Protobuf Definitions

Developers seeking to utilize field annotations provided by GORM within their protobuf definitions may encounter challenges due to the absence of a native datetime type in Protobuf 3 syntax.

To address this, a post-processing script can be employed to augment the generated proto files with the desired GORM annotations. For example, given the following protobuf profile definition:

message Profile {
  uint64 id = 1;
  string name = 2;
  bool active = 3;
}

The following script ("gorm.sh") can be used for post-processing:

#!/bin/bash

g () {
  sed "s/json:\"$1,omitempty\"/json:\"$1,omitempty\" gorm:\"$2\"/"
}

cat $1 \
| g "id" "primary_key" \
| g "name" "varchar(100)" \
> $1.tmp && mv $1{.tmp,}

By invoking the script on the generated protobuf file (e.g., ./gorm.sh profile/profile.pb.go), the resulting output will be:

//...
type Profile struct {
    state         protoimpl.MessageState
    sizeCache     protoimpl.SizeCache
    unknownFields protoimpl.UnknownFields

    Id     uint64 `protobuf:"varint,1,opt,name=id,proto3" json:"id,omitempty" gorm:"type:primary_key"`
    Name   string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty" gorm:"type:varchar(100)"`
    Active bool   `protobuf:"varint,3,opt,name=active,proto3" json:"active,omitempty"`
}
//...

This approach enables the integration of GORM field annotations into protobuf definitions without the need for custom implementations or third-party libraries.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3