如何以天为单位指定时间持续时间,以便可以无错误加载 Golang Viper 配置?

huangapple go评论89阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年3月27日 15:50:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75853288.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定