Integrating gorm.Model Fields into Protobuf Definitions
Integrating the gorm.Model fields (deleted_at, created_at, id, etc.) into proto3 definitions can be challenging, especially since proto3 does not have a datetime type. However, there are workable solutions.
Custom Script Approach
Since the protoc-gen-gorm project proved unsuitable, one solution is to create a custom post-processing script. After generating the go files from protobuf, this script can manipulate the proto3 definition file to include the necessary gorm fields.
Example:
If we have a proto file profile/profile.proto:
message Profile { uint64 id = 1; string name = 2; bool active = 3; // ... }
Generate the initial go file using standard protoc command:
protoc profile/profile.proto --go_out=plugins=grpc:profile
Then, use the gorm.sh script to add the gorm annotations:
<code class="bash">#!/bin/bash g () { sed "s/json:\",omitempty\"/json:\",omitempty\" gorm:\"\"/"" } cat profile/profile.pb.go \ | g "id" "primary_key" \ | g "name" "varchar(100)" \ > profile/profile.pb.go.tmp && mv profile/profile.pb.go{.tmp,}</code>
This will add the gorm annotations to the generated go file:
<code class="go">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"` }</code>
Considerations
The above is the detailed content of How to integrate gorm.Model fields into Protobuf definitions?. For more information, please follow other related articles on the PHP Chinese website!