Home >Backend Development >Golang >How do you integrate gorm.Model fields into Protobuf definitions while handling datetime types, and what are the pros and cons of different methods?
Integrating gorm.Model fields into protobuf definitions becomes necessary when structuring data for database use. Despite protobuf's lack of a datetime type, a solution can be devised by customizing the generated protobuf code.
Failed Solution Using protoc-gen-gorm
Attempts to implement the protoc-gen-gorm project proved futile due to potential clashes between proto2 and proto3 during the blending process.
Custom Script for Post-Processing
An alternative approach is to create a custom script for post-processing after generating go files from protobuf. Here's a breakdown of the solution:
Original Protobuf File
<code class="proto">message Profile { uint64 id = 1; string name = 2; bool active = 3; }</code>
Generated Protobuf 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"` Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` Active bool `protobuf:"varint,3,opt,name=active,proto3" json:"active,omitempty"` }</code>
Custom GORM Script
<code class="bash">g () { sed "s/json:\",omitempty\"/json:\",omitempty\" gorm:\"type:\"/" } cat \ | g "id" "primary_key" \ | g "name" "varchar(100)" \ > .tmp && mv {.tmp,}</code>
Post-Processed Protobuf 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>
This script adds gorm field tags to the generated protobuf Go file, allowing the integration of protobuf definitions with gorm.Model fields for seamless database interactions.
The above is the detailed content of How do you integrate gorm.Model fields into Protobuf definitions while handling datetime types, and what are the pros and cons of different methods?. For more information, please follow other related articles on the PHP Chinese website!