亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

任何帶有 grpc 的字段總是為零

任何帶有 grpc 的字段總是為零

Go
素胚勾勒不出你 2022-09-12 20:30:00
我正在將gRPC與戈朗一起使用。我有一個非常簡單的原型定義和一個gRPC服務。原始定義在谷歌/原型布夫/任何類型的認可中有一個字段。gRPC 服務無法將此字段映射到輸入值,并且始終初始化為零原型定義:syntax = "proto3";option go_package = "service";option java_multiple_files = true;option java_package = "io.grpc.consensus";import "google/protobuf/any.proto";package service;service MyService {  rpc Verify (Payload) returns (Response) {}}message Response {  string policyId =1;  string txnId =2;}message Endorsement {  string endorserId=1;  // This is being initialise to nil by gRPC  google.protobuf.Any data = 2;  string signature=3;  bool isVerified=4;}message Payload {  string policyId =1;  string txnId =2;  repeated Endorsement endorsements=3;}使用這個,一個簡單的gRPC服務被實現:package serviceimport (    "log"    "golang.org/x/net/context")type ServiceServerImpl struct {}func NewServiceServerImpl() *ServiceServerImpl {    return &ServiceServerImpl{}}func (s *ServiceServerImpl) Verify(ctx context.Context, txnPayload *Payload) (*Response, error) {    log.Printf("Got verification request: %s", txnPayload.TxnId)    for _, endorsement := range txnPayload.Endorsements {        j, err := endorsement.Data.UnmarshalNew()        if err != nil {            log.Print("Error while unmarshaling the endorsement")        }        if j==nil {       //This gets printed as payload's endorsement data is always null for google/protobuf/any type            log.Print("Data is null for endorsement")        }    }    return &Response{TxnId: txnPayload.TxnId,  PolicyId: txnPayload.PolicyId}, nil}輸入數據:{  "policyId": "9dd97b1e-b76f-4c49-b067-22143c954e75",  "txnId": "231-4dc0-8e54-58231df6f0ce",  "endorsements": [    {      "endorserId": "67e1dfbd-1716-4d91-94ec-83dde64e4b80",      "data": {        "type": "issueTx",        "userId": 1,        "transaction": {            "amount": 10123.50        }    },      "signature": "MEUCIBkooxG2uFZeSEeaf5Xh5hWLxcKGMxCZzfnPshOh22y2AiEAwVLAaGhccUv8UhgC291qNWtxrGawX2pPsI7UUA/7QLM=",      "isVerified": false    }  ]}
查看完整描述

2 回答

?
月關寶盒

TA貢獻1772條經驗 獲得超5個贊

如您所知,是消息類型,因此當您沒有為其設置任何值時,它將為零。google.protobuf.Any


您必須使用您的結構取消封送數據,請參閱下面來自 protobuf 示例的代碼


      // marshal any

      foo := &pb.Foo{...}

      any, err := anypb.New(foo)

      if err != nil {

        ...

      }

      // unmarshal any 

      foo := &pb.Foo{}

      if err := any.UnmarshalTo(foo); err != nil {

        ...

      }


或者我認為你可以用它與指針接口(&接口{})一起使用,如下所示:


      d := &interface{}{}

      if err := endorsement.Data.UnmarshalTo(d); err != nil {

        ...

      }


查看完整回答
反對 回復 2022-09-12
?
qq_笑_17

TA貢獻1818條經驗 獲得超7個贊

從軟件包1 文檔取消編組任何

UnmarshalNew使用全局類型注冊表解析消息類型,并構造該消息的新實例以取消編組。為了使消息類型顯示在全局注冊表中,必須將表示該 protobuf 消息類型的 Go 類型鏈接到 Go 二進制文件中。對于由原始生成生成的消息,這是通過導入表示 .proto 文件的生成的 Go 包來實現的

注冊表的類型為 。類型查找是使用字段完成的,該字段在封送原始消息時由 gRPC 客戶端設置為具體類型的 url。protoregistry.GlobalTypesAny.TypeUrl

令人困惑的細節是,它可以是任何原始緩沖區消息,但該原始緩沖區消息必須在某個地方定義Any

您的文件沒有與輸入中的對象匹配的消息定義。可能是此消息在其他地方定義(不在您自己的原型文件中),但無論如何,您都必須導入生成的消息所在的Go包。.protodataData

否則,如果輸入不是來自已定義的原型消息,您可以自己向原型添加消息定義,然后使用 UnmarshalTo

// proto file

message Data {

    string type = 1;

    int user_id = 2;

    Transaction transaction = 3;

}


message Transaction {

    float amount = 1;

}

然后:


    for _, endorsement := range txnPayload.Endorsements {

        data := generated.Data{}

        err := endorsement.Data.UnmarshalTo(&data)

        if err != nil {

            log.Print("Error while unmarshaling the endorsement")

        }

    }

如果您只需要任意的字節序列,即真正未知的類型,請使用原型類型并將其視為 JSON 有效負載。bytes


將其建模為 Go 結構:


type Data struct {

    Type     string `json:"type"`

    UserID   int    `json:"userId"`

    Transaction struct{

        Amount float64 `json:"amount"`

    } `json:"transaction"`


}

或者,如果客戶可以發送任何東西。map[string]interface{}


然后在您的處理程序功能中:


    for _, endorsement := range txnPayload.Endorsements {

        data := Data{} // or `map[string]interface{}`

        err := json.Unmarshal(endorsement.Data, &data)

        if err != nil {

            log.Print("Error while unmarshaling the endorsement")

        }

    }


查看完整回答
反對 回復 2022-09-12
  • 2 回答
  • 0 關注
  • 189 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號