登录
首页 >  Golang >  Go问答

覆盖现有的 golang 结构并添加字段

来源:stackoverflow

时间:2024-03-30 18:21:24 171浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《覆盖现有的 golang 结构并添加字段》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

func (c *client) init(conf config.config, topic string) (err error) {
    defer func() {
        p := recover()
        switch v := p.(type) {
        case error:
            err = v
        }
    }()
    c.reader = kafka.newreader(kafka.readerconfig{
        brokers:               conf.brokers,
        groupid:               conf.groupid,
        topic:                 topic,
        maxwait:               1 * time.second,    // maximum time to wait for new messages
        minbytes:              1,                  // minimum message size
        maxbytes:              10e6,               // maximum message size 1 mbyte (= maximum size kafka can handle)
        retentiontime:         time.hour * 24 * 7, // keep consumergroup for 1 week
        watchpartitionchanges: true,               // watch for changes to the partitions (e.g. increase of partitions)
    })
    if conf.tlsenabled {
        d := &kafka.dialer{
            tls: &tls.config{},
        }
    }
    return err
}

长话短说:如果 tlsenabled 为 true,我想要做的是将字段 dialer: d 添加到 c.reader ! c.reader 的类型为 readerconfig,它已经包含 dialer 字段,在我的例子中:

d := &kafka.Dialer{
    TLS: &tls.Config{},
    }

正确答案


如果我正确理解您的问题,当且仅当 conf.tlsenabled 为 true 时,您才需要在 kafka.readerconfig 上设置 dialer 字段。在这种情况下,您应该在调用 kafka.newreader 之前移动 if conf.tlsenabled 检查,并将 kafka.readerconfig 分配给变量,如下所示:

rConf := kafka.ReaderConfig{
    Brokers:               conf.Brokers,
    GroupID:               conf.GroupID,
    Topic:                 topic,
    MaxWait:               1 * time.Second,    // maximum time to wait for new messages
    MinBytes:              1,                  // minimum message size
    MaxBytes:              10e6,               // maximum message size 1 MByte (= maximum size Kafka can handle)
    RetentionTime:         time.Hour * 24 * 7, // keep ConsumerGroup for 1 week
    WatchPartitionChanges: true,               // watch for changes to the partitions (e.g. increase of partitions)
}
if conf.TlsEnabled {
    rConf.Dialer = &kafka.Dialer{
        TLS: &tls.Config{},
    }
}
// now assign c.reader
c.reader = kafka.NewReader(rConf)

有一点小问题:在 golang 中,首字母缩略词和其他缩写词应该全部大写。您的配置类型不应具有名为 tlsenabled 的字段,而应为 tlsenabled

本篇关于《覆盖现有的 golang 结构并添加字段》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

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