[英]Overwriting an existing golang structure and adding a field
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 类型,在我的例子中已经包含 Dialer 字段:
d := &kafka.Dialer{
TLS: &tls.Config{},
}
如果我正确理解了您的问题,那么当且仅当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
。
您不能将字段添加到现有类型,但可以将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)
}
问题未解决?试试以下方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.