覆盖现有Golang结构并添加字段

zc0qhyus  于 2022-10-07  发布在  Go
关注(0)|答案(2)|浏览(176)
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为真,我想要做的是将字段Dialer: d添加到c.reader中!C.Reader的ReaderConfig类型已经包含拨号程序字段,在本例中为:

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

pqwbnv8z1#

如果我正确理解了您的问题,当且仅当conf.TlsEnabled为真时,您才希望在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

yh2wf1be

yh2wf1be2#

您不能向现有类型添加字段,但可以将client嵌入自定义类型。然后可以通过自定义类型直接访问这些字段

type myType struct {
    something string
    foo       int
    bar       int
}

type myExtendedType struct {
    myType
    dialer *kafka.Dialer
}

func main() {
    ext := myExtendedType{
        myType: myType{
            something: "some",
            foo:       24,
            bar:       42,
        },
        dialer: &kafka.Dialer{
            TLS: &tls.Config{},
        },
    }
    println(ext.something, ext.foo, ext.bar, ext.dialer)
}

相关问题