New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
空值检查和非 string 值 的 toString() #6
Conversation
@morlay
|
@gaort 现在 Request 参数类型均声明为 string, 当用户需要用如下的方式使用。 type XXXRequest struct {
PageNumber string `position:"Query" name:"PageNumber"`
}
func main() {
req := XXXRequest{
PageNumber: fmt.Sprintf("%v", 2),
}
} 而用户方更希望是这样的方式 type XXXRequest struct {
PageNumber int32 `position:"Query" name:"PageNumber"`
}
func main() {
req := XXXRequest{
PageNumber: 2,
}
} 但当定义为后者时,当前 Query 的拼接处理逻辑是有问题。这里需要更新逻辑,去做 toString 的转换。 第一,reflect.Value.String(), 除了 string 外,如此使用是无法得到对应 type 的 string 化的值的,详见 https://play.golang.org/p/nIeeiaWQ_sg package main
import (
"fmt"
"reflect"
)
func main() {
fmt.Println(reflect.ValueOf("").String())
fmt.Println(reflect.ValueOf(1).String()) // <int Value>
fmt.Println(reflect.ValueOf(int64(1)).String()) // <int64 Value>
fmt.Println(reflect.ValueOf(1.1).String()) // <float64 Value>
fmt.Println(reflect.ValueOf(true).String()) // <bool Value>
} 那意味着,当前逻辑中,Query 拼接得不到预期结果,哪怕是该值未赋值(这里参看问题二), 问题二, 0 值问题 https://tour.golang.org/basics/12 这就是为了让 Request Type 使用更方便需要背后做的处理。也是该 PR 做的事。 也可以参考社区已有实现,https://github.com/denverdino/aliyungo/blob/master/util/encoding.go#L46 |
@morlay 感谢您的贡献
|
1、如果生成为带类型的,刚才提到的转换逻辑不修改,就会出现我刚才提到的问题。 |
比如这样, func Int64(i int64) MyInt64 {
return MyInt64{
Int64: i,
Valid: true,
}
}
type MyInt64 struct {
Int64 int64
Valid bool
}
func (v MyInt64) String() string {
if v.Valid {
return fmt.Sprintf("%d", v.Int64)
}
return ""
}
|
或者,https://github.com/google/go-github/issues/19,指针化以区分 unset 和 zero value 还有一种是给 baseRequest 加个白名单, 当 0 值的时候也可拼接到 Query 上 比如 type baseRequest struct {
zeroFields []string
}
func (br *baseRequest) WithZeroFields(fieldNames ...string) {
br.zeroFields = append(br.zeroFields, zeroFields...)
} |
@morlay 感谢您的贡献,因为这几种方式都会对用户接口产生影响,请容许我们内部一起讨论下,谢谢 |
Request 的参数还是应该保留对应的类型,以方便用户赋值,全 string 太过暴力