Table of Contents
问题内容
解决方法
Home Backend Development Golang How to pass any type of data value into GRPC Protobuf structure in Golang?

How to pass any type of data value into GRPC Protobuf structure in Golang?

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:"^"`
}
Copy after login

txtest的protobuf:

message txtest {
   int32 exitcode = 1;
}
Copy after login

我要解析的数据是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)

    }
Copy after login

一笔交易的数据结构为:

{
  "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="
}
Copy after login

detaildetail2 的输出为:

detail: 
detail2: {ExitCode:0}
Copy after login

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

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

解决方法

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

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

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

The above is the detailed content of How to pass any type of data value into GRPC Protobuf structure in Golang?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the vulnerabilities of Debian OpenSSL What are the vulnerabilities of Debian OpenSSL Apr 02, 2025 am 07:30 AM

OpenSSL, as an open source library widely used in secure communications, provides encryption algorithms, keys and certificate management functions. However, there are some known security vulnerabilities in its historical version, some of which are extremely harmful. This article will focus on common vulnerabilities and response measures for OpenSSL in Debian systems. DebianOpenSSL known vulnerabilities: OpenSSL has experienced several serious vulnerabilities, such as: Heart Bleeding Vulnerability (CVE-2014-0160): This vulnerability affects OpenSSL 1.0.1 to 1.0.1f and 1.0.2 to 1.0.2 beta versions. An attacker can use this vulnerability to unauthorized read sensitive information on the server, including encryption keys, etc.

How do you use the pprof tool to analyze Go performance? How do you use the pprof tool to analyze Go performance? Mar 21, 2025 pm 06:37 PM

The article explains how to use the pprof tool for analyzing Go performance, including enabling profiling, collecting data, and identifying common bottlenecks like CPU and memory issues.Character count: 159

How do you write unit tests in Go? How do you write unit tests in Go? Mar 21, 2025 pm 06:34 PM

The article discusses writing unit tests in Go, covering best practices, mocking techniques, and tools for efficient test management.

How do you use table-driven tests in Go? How do you use table-driven tests in Go? Mar 21, 2025 pm 06:35 PM

The article discusses using table-driven tests in Go, a method that uses a table of test cases to test functions with multiple inputs and outcomes. It highlights benefits like improved readability, reduced duplication, scalability, consistency, and a

Explain the purpose of Go's reflect package. When would you use reflection? What are the performance implications? Explain the purpose of Go's reflect package. When would you use reflection? What are the performance implications? Mar 25, 2025 am 11:17 AM

The article discusses Go's reflect package, used for runtime manipulation of code, beneficial for serialization, generic programming, and more. It warns of performance costs like slower execution and higher memory use, advising judicious use and best

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

How do you specify dependencies in your go.mod file? How do you specify dependencies in your go.mod file? Mar 27, 2025 pm 07:14 PM

The article discusses managing Go module dependencies via go.mod, covering specification, updates, and conflict resolution. It emphasizes best practices like semantic versioning and regular updates.

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

See all articles