对golang protobuf 的扩展字段赋值时候一直提示proto: bad extension value type
clkUrl:="z.cn"
proto.SetExtension(seatbid, rtb.E_Clkurl, clkUrl)
查看源码后发现,对扩展字段赋值的时候会对第二个参数进行反射获取类型,判断第三个参数的类型和第二个是否匹配 ,
func SetExtension(pb Message, extension *ExtensionDesc, value interface{}) error {
epb, ok := extendable(pb)
if !ok {
return errors.New("proto: not an extendable proto")
}
if err := checkExtensionTypes(epb, extension); err != nil {
return err
}
typ := reflect.TypeOf(extension.ExtensionType)
if typ != reflect.TypeOf(value) {
return errors.New("proto: bad extension value type")
}
// nil extension values need to be caught early, because the
// encoder can't distinguish an ErrNil due to a nil extension
// from an ErrNil due to a missing field. Extensions are
// always optional, so the encoder would just swallow the error
// and drop all the extensions from the encoded message.
if reflect.ValueOf(value).IsNil() {
return fmt.Errorf("proto: SetExtension called with nil value of type %T", value)
}
extmap := epb.extensionsWrite()
extmap[extension.Field] = Extension{desc: extension, value: value}
return nil
}
通过打印第二个参数的类型发现 第二个参数类型是*string , 我的第三个参数是sring,问题已经明了。
阅读源码是解决问题的最好途径。
修改后的代码如下:
proto.SetExtension(seatbid, rtb.E_Clkurl, &clkUrl)