目录
问题内容
解决方法
首页 后端开发 Golang 如何将任何类型的数据值传递到 Golang 中的 GRPC Protobuf 结构中?

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

Feb 09, 2024 pm 12:12 PM

如何将任何类型的数据值传递到 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:

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)

    }
登录后复制

一笔交易的数据结构为:

{
  "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 和空字段之间没有区别。

以上是如何将任何类型的数据值传递到 Golang 中的 GRPC Protobuf 结构中?的详细内容。更多信息请关注PHP中文网其他相关文章!

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

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

AI Hentai Generator

AI Hentai Generator

免费生成ai无尽的。

热门文章

R.E.P.O.能量晶体解释及其做什么(黄色晶体)
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳图形设置
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌
威尔R.E.P.O.有交叉游戏吗?
1 个月前 By 尊渡假赌尊渡假赌尊渡假赌

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

Debian OpenSSL有哪些漏洞 Debian OpenSSL有哪些漏洞 Apr 02, 2025 am 07:30 AM

OpenSSL,作为广泛应用于安全通信的开源库,提供了加密算法、密钥和证书管理等功能。然而,其历史版本中存在一些已知安全漏洞,其中一些危害极大。本文将重点介绍Debian系统中OpenSSL的常见漏洞及应对措施。DebianOpenSSL已知漏洞:OpenSSL曾出现过多个严重漏洞,例如:心脏出血漏洞(CVE-2014-0160):该漏洞影响OpenSSL1.0.1至1.0.1f以及1.0.2至1.0.2beta版本。攻击者可利用此漏洞未经授权读取服务器上的敏感信息,包括加密密钥等。

您如何使用PPROF工具分析GO性能? 您如何使用PPROF工具分析GO性能? Mar 21, 2025 pm 06:37 PM

本文解释了如何使用PPROF工具来分析GO性能,包括启用分析,收集数据并识别CPU和内存问题等常见的瓶颈。

您如何在GO中编写单元测试? 您如何在GO中编写单元测试? Mar 21, 2025 pm 06:34 PM

本文讨论了GO中的编写单元测试,涵盖了最佳实践,模拟技术和有效测试管理的工具。

Go语言中用于浮点数运算的库有哪些? Go语言中用于浮点数运算的库有哪些? Apr 02, 2025 pm 02:06 PM

Go语言中用于浮点数运算的库介绍在Go语言(也称为Golang)中,进行浮点数的加减乘除运算时,如何确保精度是�...

Go的爬虫Colly中Queue线程的问题是什么? Go的爬虫Colly中Queue线程的问题是什么? Apr 02, 2025 pm 02:09 PM

Go爬虫Colly中的Queue线程问题探讨在使用Go语言的Colly爬虫库时,开发者常常会遇到关于线程和请求队列的问题。�...

什么是GO FMT命令,为什么很重要? 什么是GO FMT命令,为什么很重要? Mar 20, 2025 pm 04:21 PM

本文讨论了GO编程中的GO FMT命令,该命令将代码格式化以遵守官方样式准则。它突出了GO FMT在维持代码一致性,可读性和降低样式辩论方面的重要性。 FO的最佳实践

Debian下PostgreSQL监控方法 Debian下PostgreSQL监控方法 Apr 02, 2025 am 07:27 AM

本文介绍在Debian系统下监控PostgreSQL数据库的多种方法和工具,助您全面掌握数据库性能监控。一、利用PostgreSQL内置监控视图PostgreSQL自身提供多个视图用于监控数据库活动:pg_stat_activity:实时展现数据库活动,包括连接、查询和事务等信息。pg_stat_replication:监控复制状态,尤其适用于流复制集群。pg_stat_database:提供数据库统计信息,例如数据库大小、事务提交/回滚次数等关键指标。二、借助日志分析工具pgBadg

从前端转型后端开发,学习Java还是Golang更有前景? 从前端转型后端开发,学习Java还是Golang更有前景? Apr 02, 2025 am 09:12 AM

后端学习路径:从前端转型到后端的探索之旅作为一名从前端开发转型的后端初学者,你已经有了nodejs的基础,...

See all articles