Home > Backend Development > Golang > How to mention duration in days so that golang viper configuration can be loaded without error?

How to mention duration in days so that golang viper configuration can be loaded without error?

PHPz
Release: 2024-02-12 16:30:07
forward
833 people have browsed it

如何提及以天为单位的持续时间,以便可以毫无错误地加载 golang viper 配置?

Question content

I have two configurations in the .env file, as follows

max_token_expiry_days=30d
access_token_duration=30m
Copy after login

The structure used to load configuration in golang is as follows

type appconfig struct {
    maxtokenexpiry      time.duration `mapstructure:"max_token_expiry_days"`
    accesstokenduration time.duration `mapstructure:"access_token_duration"`
}
Copy after login

Now when I try to load the configuration I get the following error

* error decoding 'max_token_expiry_days': time: unknown unit "d" in duration "30d"
Copy after login

This probably means the problem is with the max_token_expiry_days=30d line, as it doesn't recognize the d tag. But the m tag in access_token_duration=30m works fine with time. duration in golang can parse it well.

In the time package source code, I see the following structure

Nanosecond  Duration = 1
Microsecond          = 1000 * Nanosecond
Millisecond          = 1000 * Microsecond
Second               = 1000 * Millisecond
Minute               = 60 * Second
Hour                 = 60 * Minute
Copy after login

Is there any way to express the number of days in the configuration?

Workaround

This is because the ParseDuration called on your time string does not support d as a unit suffix

The valid time units are "ns", "us" (or "μs"), "ms", "s", "m", and "h".

You are better off using the number of hours 30d, which is 720h to resolve ambiguities.

Also see the question/explanation in golang/go to understand why the language designers decided to use select. Why time.ParseDuration() does not support days? #17767

The above is the detailed content of How to mention duration in days so that golang viper configuration can be loaded without error?. For more information, please follow other related articles on the PHP Chinese website!

source:stackoverflow.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template