How to integrate gorm.Model fields into Protobuf definitions?

Mary-Kate Olsen
Release: 2024-10-29 06:11:02
Original
333 people have browsed it

How to integrate gorm.Model fields into Protobuf definitions?

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;
  // ...
}
Copy after login

Generate the initial go file using standard protoc command:

protoc profile/profile.proto --go_out=plugins=grpc:profile
Copy after login

Then, use the gorm.sh script to add the gorm annotations:

<code class="bash">#!/bin/bash

g () {
  sed "s/json:\",omitempty\"/json:\",omitempty\" gorm:\"\"/&quot;"
}

cat profile/profile.pb.go \
| g "id" "primary_key" \
| g "name" "varchar(100)" \
> profile/profile.pb.go.tmp &amp;&amp; mv profile/profile.pb.go{.tmp,}</code>
Copy after login

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>
Copy after login

Considerations

  • This approach requires post-processing and may not be suitable for large projects.
  • Ensure the custom script adheres to the protobuf syntax.
  • Testing is crucial to verify the updated proto3 definitions work as intended.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template