英文:
How to mention time duration in days so that golang viper config can be loaded without errors?
问题
我在.env
文件中有两个配置,如下所示:
MAX_TOKEN_EXPIRY_DAYS=30d
ACCESS_TOKEN_DURATION=30m
在Golang中,用于加载配置的结构如下:
type AppConfig struct {
MaxTokenExpiry time.Duration `mapstructure:"MAX_TOKEN_EXPIRY_DAYS"`
AccessTokenDuration time.Duration `mapstructure:"ACCESS_TOKEN_DURATION"`
}
现在,当我尝试加载配置时,我遇到了以下错误:
* error decoding 'MAX_TOKEN_EXPIRY_DAYS': time: unknown unit "d" in duration "30d"
这可能意味着问题出在MAX_TOKEN_EXPIRY_DAYS=30d
这一行,因为它无法识别d
标记。但是,在ACCESS_TOKEN_DURATION=30m
中的m
标记可以正常工作,因为Golang中的time.Duration
能够正确解析它。
在时间包的源代码中,我看到了以下构造:
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
是否有任何方法可以表示天数?
英文:
I have two configurations in the .env
file as following
MAX_TOKEN_EXPIRY_DAYS=30d
ACCESS_TOKEN_DURATION=30m
The struct in golang to load the config looks like following
type AppConfig struct {
MaxTokenExpiry time.Duration `mapstructure:"MAX_TOKEN_EXPIRY_DAYS"`
AccessTokenDuration time.Duration `mapstructure:"ACCESS_TOKEN_DURATION"`
}
Now the when I am trying to load the config, I am getting the following error
> * error decoding 'MAX_TOKEN_EXPIRY_DAYS': time: unknown unit "d" in duration "30d"
This may mean that I the issue was with MAX_TOKEN_EXPIRY_DAYS=30d
line as it is not able to recognise the d
tag. But the m
tag in ACCESS_TOKEN_DURATION=30m
runs well as time.Duration
in golang is able to parse it well.
In the time package source code, I see the following constructs
Nanosecond Duration = 1
Microsecond = 1000 * Nanosecond
Millisecond = 1000 * Microsecond
Second = 1000 * Millisecond
Minute = 60 * Second
Hour = 60 * Minute
Is there any way to denote days in the config?
答案1
得分: 2
这是因为在你的时间字符串上调用的ParseDuration不支持d
作为单位后缀。
有效的时间单位有"ns"、"us"(或"μs")、"ms"、"s"、"m"、"h"。
你最好使用30d
的小时等价值,即720h
来消除歧义。
此外,还可以在golang/go中查看问题/解释,了解语言设计者为什么选择这种方式。为什么time.ParseDuration()不支持天数?#17767
英文:
It is because the ParseDuration called on your time string does not support d
as a unit suffix
> Valid time units are "ns", "us" (or "µs"), "ms", "s", "m", "h".
You are better off using the hours equivalent of 30d
i.e. 720h
to resolve the ambiguity.
Also see issue/explanation in golang/go for why the language designers decided to go with the choice. Why doesn't time.ParseDuration() support days? #17767
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论