mirror of
https://github.com/0rangebananaspy/authelia.git
synced 2024-09-14 22:47:21 +07:00
cc06ab6c18
* [CI] Add gocritic linter * Implement gocritic recommendations The outstanding recommendations are due to be addressed in #959 and #971 respectively. * Fix implementation tests * Fix remaining linting issues. * Fix tests. Co-authored-by: Clément Michaud <clement.michaud34@gmail.com>
52 lines
1.4 KiB
Go
52 lines
1.4 KiB
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
// ParseDurationString parses a string to a duration
|
|
// Duration notations are an integer followed by a unit
|
|
// Units are s = second, m = minute, d = day, w = week, M = month, y = year
|
|
// Example 1y is the same as 1 year.
|
|
func ParseDurationString(input string) (time.Duration, error) {
|
|
var duration time.Duration
|
|
|
|
matches := parseDurationRegexp.FindStringSubmatch(input)
|
|
|
|
switch {
|
|
case len(matches) == 3 && matches[2] != "":
|
|
d, _ := strconv.Atoi(matches[1])
|
|
|
|
switch matches[2] {
|
|
case "y":
|
|
duration = time.Duration(d) * Year
|
|
case "M":
|
|
duration = time.Duration(d) * Month
|
|
case "w":
|
|
duration = time.Duration(d) * Week
|
|
case "d":
|
|
duration = time.Duration(d) * Day
|
|
case "h":
|
|
duration = time.Duration(d) * Hour
|
|
case "m":
|
|
duration = time.Duration(d) * time.Minute
|
|
case "s":
|
|
duration = time.Duration(d) * time.Second
|
|
}
|
|
case input == "0" || len(matches) == 3:
|
|
seconds, err := strconv.Atoi(input)
|
|
if err != nil {
|
|
return 0, fmt.Errorf("Could not convert the input string of %s into a duration: %s", input, err)
|
|
}
|
|
|
|
duration = time.Duration(seconds) * time.Second
|
|
case input != "":
|
|
// Throw this error if input is anything other than a blank string, blank string will default to a duration of nothing
|
|
return 0, fmt.Errorf("Could not convert the input string of %s into a duration", input)
|
|
}
|
|
|
|
return duration, nil
|
|
}
|