【问题标题】:How to row.Scan() int32 into Golang gRPC protobuf Enum field?如何将 row.Scan() int32 放入 Golang gRPC protobuf Enum 字段?
【发布时间】:2019-03-18 20:02:47
【问题描述】:
// agent.proto

message Agent {
    Permission permission = 1;
    google.protobuf.Timestamp born_time = 2;

    message Permission {
        Type type = 1;

        enum Type {
            KILLNONE = 0;
            KILLALL = 1;
            DANCE = 2;
        }
   }
}

然后将 SQL 行扫描到代理 protobuf 结构中:

// main.go

var a proto.Agent

.....

... row.Scan(&a.Permission.Type,...)

该权限类型存储为简单的 MariaDB INT() value = 0 作为默认类型。所以,我不能直接扫描它。因此,我在 Type int32 处创建了临时结构,并在尝试将临时结构字段映射到 protobuf 结构之后将行扫描到该临时结构中,但没有运气。 当我想将 MariaDB 字符串值扫描到 []byte 类型字段时,我遇到了类似的问题,但我用我的 temp struct []byte(tmp.UUID) 解决了这个问题。

当使用非标准的protobuf字段类型时,将数据库ROW(单行)扫描成protubuf消息的常见模式是什么?

编辑:是否应该有一些额外的0 值处理?

【问题讨论】:

    标签: go protocol-buffers grpc grpc-go


    【解决方案1】:

    我通常在业务领域中使用 Go 类型,并使用适配器与 protobuf 类型进行转换。

    // Role represents a set of permissions
    type Role struct {
        KILLNONE = iota
        KILLALL
        DANCE
    }
    
    // Permission represents a set of agent permissions
    type Permission struct {
        Role Role
    }
    
    // ToProto converts a Permission Go type to a protobuf Permission
    func (p Permission) ToProto() (proto.Permission) {
        pb := proto.Permission{}
        // assign p's properties to proto's respective properties
        // with necessary type conversions.
        ...
        return pb
    }
    

    protobuf 示例通常显示直接使用 protobuf 类型,但似乎适配器在该领域更常见。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-12-08
      • 2018-06-28
      • 2017-01-19
      • 2011-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      相关资源
      最近更新 更多