go 如何实现反序列提供默认值

219 天前
 yujianwjj
type ServerConfig struct {
	URL string
	Timeout time.Duration
    Size int
    A  int
    B int
    C int
}

ServerConfig 是从配置文件反序列化出来的,里面的变量如果配置文件没有提供的话,很多变量都是零值, 但是我期望里面的很多变量都是我自己定义的一个默认值。

我现在的做法是反序列化后再一个一个的判断,如果是零值,就改成我期望的值,这样感觉比较麻烦,有什么其他更好的方法吗?

1803 次点击
所在节点    Go 编程语言
14 条回复
blackcurrant
219 天前
使用 viper 读取配置。
然后类似这样定义
type RPCConfig struct {
Host string `mapstructure:"host"`
Port int `mapstructure:"port"`
// 使用默认值
Timeout int `mapstructure:"timeout,default=30"`
}
mornlight
219 天前
做配置管理的第三方库很多都支持 default tag 。
如果觉得不好用可以先用这个库 Set 一遍 github.com/creasty/defaults
scp3041
218 天前
先赋默认值,再反序列化
CyJaySong
218 天前
试试这样写呢
serverConfig := ServerConfig{
URL: "www.baidu.com",
}
_ = json.Unmarshal(bytes, &serverConfig)
yuancoder
218 天前
一般是通过 tag 实现的
ikaros
218 天前
我的看法是为了这么简单的需求引入一个新的库不值(你甚至只用了他的很少功能),如果是基于 tag 的反射还影响性能, 个人解决方法偏向于给这个 struct 写个 SetDefaultValue 的方法,unmarshal 完之后调用一下
ding2dong
218 天前
func GetDefaultServerConfig() ServerConfig {
return ServerConfig{
// 你的一些默认值...
}
}

//读取配置
serverConfig := GetDefaultServerConfig()
json.Unmarshal([]byte(jsonStr), &serverConfig)
Shijamlin
218 天前
@ikaros 同意
dw2693734d
218 天前
@CyJaySong 这种比较简单,我也这样用
hzjseasea
218 天前
https://blog.51cto.com/hongchen99/4520434 tag 实现,重写方法?
CzaOrz
218 天前
看着有点眼熟,可以参考我自己写的一个工具库,原理就是基于反射解析 Tag 然后赋值即可:

- https://github.com/czasg/go-fill

```go
// 依赖
import "github.com/czasg/go-fill"
// 准备结构体
type Config struct {
Host string `fill:"HOST,default=localhost"`
Port int `fill:"PORT,default=5432"`
User string `fill:"USER,default=root"`
Password string `fill:"PASSWORD,default=root"`
}
// 初始化
cfg := Config{}
// 填充环境变量
_ = fill.FillEnv(&cfg)
```
yujianwjj
218 天前
```
type Config struct {
ServerConfigs []ServerConfig
}
```

如果 先赋默认值,再反序列化的话。针对这个情况咋搞?
fantastM
218 天前
@yujianwjj #12 如果解析的是 yaml 配置的话,可以试试这种方式

https://github.com/go-yaml/yaml/issues/165#issuecomment-255223956
yujianwjj
218 天前
嗯,确实是 yaml ,感谢 @fantastM

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/993997

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX