0

0

如何将任何类型的数据值传递到 Golang 中的 GRPC Protobuf 结构中?

WBOY

WBOY

发布时间:2024-02-09 12:12:18

|

862人浏览过

|

来源于stackoverflow

转载

如何将任何类型的数据值传递到 golang 中的 grpc protobuf 结构中?

php小编新一为您介绍如何将任何类型的数据值传递到Golang中的GRPC Protobuf结构中。GRPC Protobuf是一种高效的数据传输协议,但是默认情况下只支持有限的数据类型。然而,通过使用自定义的字段类型和值转换方法,我们可以轻松地将任何类型的数据值传递到Protobuf结构中。在本文中,我们将提供一些实用的技巧和示例代码,帮助您在Golang中处理各种数据类型的传递。无论是字符串、数字、布尔值还是自定义的复杂对象,都可以通过这些方法成功传递到GRPC Protobuf结构中。让我们一起来看看吧!

问题内容

我正在尝试通过 tonutils-go 解析 adnl 库中的数据并通过 grpc 传递数据。

我需要的数据结构为

// struct from tonutils-go
type transaction struct {
    _           magic         `tlb:"$0111"`
    accountaddr []byte        `tlb:"bits 256"`
    lt          uint64        `tlb:"## 64"`
    prevtxhash  []byte        `tlb:"bits 256"`
    prevtxlt    uint64        `tlb:"## 64"`
    now         uint32        `tlb:"## 32"`
    outmsgcount uint16        `tlb:"## 15"`
    origstatus  accountstatus `tlb:"."`
    endstatus   accountstatus `tlb:"."`
    io          struct {
        in  *message      `tlb:"maybe ^"`
        out *messageslist `tlb:"maybe ^"`
    } `tlb:"^"`
    totalfees   currencycollection     `tlb:"."`
    stateupdate hashupdate             `tlb:"^"` // of account
    description transactiondescription `tlb:"^"`

    // not in scheme, but will be filled based on request data for flexibility
    hash []byte `tlb:"-"`
}

type transactiondescription struct {
    description any `tlb:"."`
}


type transactiondescriptionordinary struct {
    _            magic         `tlb:"$0000"`
    creditfirst  bool          `tlb:"bool"`
    storagephase *storagephase `tlb:"maybe ."`
    creditphase  *creditphase  `tlb:"maybe ."`
    computephase computephase  `tlb:"."`
    actionphase  *actionphase  `tlb:"maybe ^"`
    aborted      bool          `tlb:"bool"`
    bouncephase  *bouncephase  `tlb:"maybe ."`
    destroyed    bool          `tlb:"bool"`
}

type computephase struct {
    phase any `tlb:"."`
}


type computephasevm struct {
    _                magic `tlb:"$1"`
    success          bool  `tlb:"bool"`
    msgstateused     bool  `tlb:"bool"`
    accountactivated bool  `tlb:"bool"`
    gasfees          coins `tlb:"."`
    details          struct {
        gasused          *big.int `tlb:"var uint 7"`
        gaslimit         *big.int `tlb:"var uint 7"`
        gascredit        *big.int `tlb:"maybe var uint 3"`
        mode             int8     `tlb:"## 8"`
        exitcode         int32    `tlb:"## 32"`
        exitarg          *int32   `tlb:"maybe ## 32"`
        vmsteps          uint32   `tlb:"## 32"`
        vminitstatehash  []byte   `tlb:"bits 256"`
        vmfinalstatehash []byte   `tlb:"bits 256"`
    } `tlb:"^"`
}

txtest的protobuf:

立即学习go语言免费学习笔记(深入)”;

message txtest {
   int32 exitcode = 1;
}

我要解析的数据是exitcode,代码如下:

    list, err := api.listtransactions(context.background(), addr, 1, uint64(txinfo.txlt), data)
    if err != nil {
        log.printf("send err: %s", err.error())
        return nil, err
    }
    for _, t := range list {
        a := t.description.description

        var result tlb.transactiondescriptionordinary

        b, err := json.marshalindent(a, "", "  ")
        if err != nil {
            fmt.println("error:", err)
        }
        json.unmarshal([]byte(string(b)), &result)

        var computephase tlb.computephasevm

        c, err := json.marshalindent(result.computephase.phase, "", "  ")
        if err != nil {
            fmt.println("error:", err)
        }

        json.unmarshal([]byte(string(c)), &computephase)


        detail := &pb.txtest{
            exitcode: computephase.details.exitcode,
        }
        detail2 := struct {
            exitcode int32 `json:"exit_code"`
        }{
            exitcode: computephase.details.exitcode,
        }

        fmt.printf("detail: %+v\n", detail)
        fmt.printf("detail2: %+v\n", detail2)

    }

一笔交易的数据结构为:

XPaper Ai
XPaper Ai

AI撰写论文、开题报告生成、AI论文生成器尽在XPaper Ai论文写作辅助指导平台

下载
{
  "accountaddr": "hymm1/kk6gb2dlv3zvkiryepkohrtf/jg8k7ttg91sq=",
  "lt": 11898016000001,
  "prevtxhash": "ikgjsxdt0gzijxgnilvxy0+a1ggeqded4f7zaj9dlmc=",
  "prevtxlt": 11897712000001,
  "now": 1685602760,
  "outmsgcount": 1,
  "origstatus": "active",
  "endstatus": "active",
  "io": {
    "in": {
      "msgtype": "external_in",
      "msg": {
        "srcaddr": "none",
        "dstaddr": "eqadiyzx-qroyhymtxfnwqhhiskqgdfmx-mbwru1mb3wxn5d",
        "importfee": "0",
        "stateinit": null,
        "body": {}
      }
    },
    "out": {
      "list": {}
    }
  },
  "totalfees": {
    "coins": "22324812",
    "extracurrencies": {}
  },
  "stateupdate": {
    "oldhash": "wukexyos8hswyqyrlhpmjhpfmusid8odtaq6fy20pyq=",
    "newhash": "e8tn4cp4lakfwvdcgc/vqbz7lzeb4mhjmbrfe8rpsqa="
  },
  "description": {
    "description": {
      "creditfirst": true,
      "storagephase": {
        "storagefeescollected": "484",
        "storagefeesdue": null,
        "statuschange": {
          "type": "unchanged"
        }
      },
      "creditphase": null,
      "computephase": {
        "phase": {
          "success": true,
          "msgstateused": false,
          "accountactivated": false,
          "gasfees": "19862000",
          "details": {
            "gasused": 19862,
            "gaslimit": 0,
            "gascredit": 10000,
            "mode": 0,
            "exitcode": 0,
            "exitarg": null,
            "vmsteps": 404,
            "vminitstatehash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa=",
            "vmfinalstatehash": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa="
          }
        }
      },
      "actionphase": {
        "success": true,
        "valid": true,
        "nofunds": false,
        "statuschange": {
          "type": "unchanged"
        },
        "totalfwdfees": "1000000",
        "totalactionfees": "333328",
        "resultcode": 0,
        "resultarg": null,
        "totalactions": 1,
        "specactions": 0,
        "skippedactions": 0,
        "messagescreated": 1,
        "actionlisthash": "fkoo2xx9ju4yxtgjlrujvayrrwtryhebkuywuyg9av4=",
        "totalmsgsize": {
          "cells": 1,
          "bits": 697
        }
      },
      "aborted": false,
      "bouncephase": null,
      "destroyed": false
    }
  },
  "hash": "vmxfrkfietmaihm3brtvhskaide1ckgrw8rqbvarjtq="
}

detaildetail2 的输出为:

detail: 
detail2: {ExitCode:0}

我的问题是为什么 protoc 生成的结构无法从 transaction 解析 exitcode 但我定义的结构可以正常工作?

如何将数据注入到protoc生成的struct txtest中,让我通过grpc传输数据?

解决方法

使用 0 以外的退出代码值尝试此操作,我猜您会得到不同的结果。

看看您生成的代码。我相信发生的事情是 fmt.Printf 正在为您的原型结构调用生成的 String() 方法,它使用 prototext 包来打印消息的内容,而不是默认的 Go 结构打印机。

这是 proto3预期行为int320 和空字段之间没有区别。

本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热门AI工具

更多
DeepSeek
DeepSeek

幻方量化公司旗下的开源大模型平台

豆包大模型
豆包大模型

字节跳动自主研发的一系列大型语言模型

通义千问
通义千问

阿里巴巴推出的全能AI助手

腾讯元宝
腾讯元宝

腾讯混元平台推出的AI助手

文心一言
文心一言

文心一言是百度开发的AI聊天机器人,通过对话可以生成各种形式的内容。

讯飞写作
讯飞写作

基于讯飞星火大模型的AI写作工具,可以快速生成新闻稿件、品宣文案、工作总结、心得体会等各种文文稿

即梦AI
即梦AI

一站式AI创作平台,免费AI图片和视频生成。

ChatGPT
ChatGPT

最最强大的AI聊天机器人程序,ChatGPT不单是聊天机器人,还能进行撰写邮件、视频脚本、文案、翻译、代码等任务。

相关专题

更多
golang如何定义变量
golang如何定义变量

golang定义变量的方法:1、声明变量并赋予初始值“var age int =值”;2、声明变量但不赋初始值“var age int”;3、使用短变量声明“age :=值”等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

182

2024.02.23

golang有哪些数据转换方法
golang有哪些数据转换方法

golang数据转换方法:1、类型转换操作符;2、类型断言;3、字符串和数字之间的转换;4、JSON序列化和反序列化;5、使用标准库进行数据转换;6、使用第三方库进行数据转换;7、自定义数据转换函数。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

229

2024.02.23

golang常用库有哪些
golang常用库有哪些

golang常用库有:1、标准库;2、字符串处理库;3、网络库;4、加密库;5、压缩库;6、xml和json解析库;7、日期和时间库;8、数据库操作库;9、文件操作库;10、图像处理库。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

343

2024.02.23

golang和python的区别是什么
golang和python的区别是什么

golang和python的区别是:1、golang是一种编译型语言,而python是一种解释型语言;2、golang天生支持并发编程,而python对并发与并行的支持相对较弱等等。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

209

2024.03.05

golang是免费的吗
golang是免费的吗

golang是免费的。golang是google开发的一种静态强类型、编译型、并发型,并具有垃圾回收功能的开源编程语言,采用bsd开源协议。本专题为大家提供相关的文章、下载、课程内容,供大家免费下载体验。

394

2024.05.21

golang结构体相关大全
golang结构体相关大全

本专题整合了golang结构体相关大全,想了解更多内容,请阅读专题下面的文章。

220

2025.06.09

golang相关判断方法
golang相关判断方法

本专题整合了golang相关判断方法,想了解更详细的相关内容,请阅读下面的文章。

193

2025.06.10

golang数组使用方法
golang数组使用方法

本专题整合了golang数组用法,想了解更多的相关内容,请阅读专题下面的文章。

398

2025.06.17

俄罗斯Yandex引擎入口
俄罗斯Yandex引擎入口

2026年俄罗斯Yandex搜索引擎最新入口汇总,涵盖免登录、多语言支持、无广告视频播放及本地化服务等核心功能。阅读专题下面的文章了解更多详细内容。

158

2026.01.28

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号