登录
首页 >  Golang >  Go问答

Golang编码器:字段类型不匹配的解析错误

来源:stackoverflow

时间:2024-03-05 11:12:28 232浏览 收藏

偷偷努力,悄无声息地变强,然后惊艳所有人!哈哈,小伙伴们又来学习啦~今天我将给大家介绍《Golang编码器:字段类型不匹配的解析错误》,这篇文章主要会讲到等等知识点,不知道大家对其都有多少了解,下面我们就一起来看一吧!当然,非常希望大家能多多评论,给出合理的建议,我们一起学习,一起进步!

问题内容

我在两个不同的流上使用 pubsub,我们从一个流接收消息,运行一些逻辑,如果它符合特定条件,我们将其发布到第二个流。第二个流也是从 goroutine 中接收的。

现在,我有两个主要函数 handlemessagehandleretry,其中前者来自第一个流,第二个用于第二个流。

handlemessage相关代码如下:

    if c.handler.shouldprocess(tx) {
        err := c.handler.process(tx)
        if err != nil {
            c.log.
                witherror(err).
                withfield("tx_hash", tx.txhash.string()).
                error("failed to process")

            retrymsg := retrymessage{
                transaction:                 tx,
                remainingprocessingattempts: c.config.maxprocessingattempts,
                lastattempt:                 time.now(),
            }

            data, err := pubsub.encodemessage(retrymsg)
            if err != nil {
                c.log.witherror(err).error("failed to convert retry msg to byte slice")
            }

            id, err := c.retryqueue.publish(context.background(), &pubsub.message{data: data})
            if err != nil {
                c.log.witherror(err).
                    withfield("id", id).
                    error("failed to publish message to retry queue")
            }
        }
    }

handleretry 中,函数以

打开
    retrytx := new(retrymessage)
    err := pubsub.decodemessage(msg.data, retrytx)
    if err != nil {
        c.log.witherror(err).
            error("failed to decode message: not a retry tx")
        msg.ack()
        return
    }

对于由 handleretry 处理的 retryqueue ——除了从 handlemessage 发布的消息之外没有其他输入

但是,我一直收到 gob 解码错误,提示

level=error msg="无法解码消息:不是重试 tx" env=local error="gob: 类型不匹配:没有匹配 retrymessage 编译解码器的字段"

retrymessage 看起来像这样

type retrymessage struct {
    transaction                 *firehose.transaction
    remainingprocessingattempts int
    lastattempt                 time.time
}

编码和解码函数如下

// EncodeMessage convert an arbitrary interface into a byte slice.
func EncodeMessage(data interface{}) ([]byte, error) {
    var buf bytes.Buffer

    enc := gob.NewEncoder(&buf)

    err := enc.Encode(data)
    if err != nil {
        return nil, err
    }

    return buf.Bytes(), nil
}

// DecodeMessage decodes message data into the provided interface.
func DecodeMessage(data []byte, dest interface{}) error {
    buf := bytes.NewBuffer(data)
    dec := gob.NewDecoder(buf)
    return dec.Decode(dest)
}

解决方案


handlemessage 中的这段代码中:

data, err := pubsub.EncodeMessage(retryMsg)
        if err != nil {
            c.log.WithError(err).Error("failed to convert retry msg to byte slice")
        }

该错误将被忽略,并且已发布消息的 data 字段将填充有可能错误的值。检查日志中是否看到“无法将重试消息转换为字节片”。

今天带大家了解了的相关知识,希望对你有所帮助;关于Golang的技术知识我们会一点点深入介绍,欢迎大家关注golang学习网公众号,一起学习编程~

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>