types: add simple duration type for parsing [0-9]+[wd]

This commit is contained in:
c9s 2022-12-24 20:37:53 +08:00
parent e0daf9904e
commit 4388bc209b
No known key found for this signature in database
GPG Key ID: 7385E7E464CB0A54
2 changed files with 53 additions and 0 deletions

47
pkg/types/duration.go Normal file
View File

@ -0,0 +1,47 @@
package types
import (
"regexp"
"strconv"
"time"
"github.com/pkg/errors"
)
var simpleDurationRegExp = regexp.MustCompile("^(\\d+)[hdw]$")
var ErrNotSimpleDuration = errors.New("the given input is not simple duration format")
type SimpleDuration struct {
Num int64
Unit string
Duration Duration
}
func ParseSimpleDuration(s string) (*SimpleDuration, error) {
if !simpleDurationRegExp.MatchString(s) {
return nil, errors.Wrapf(ErrNotSimpleDuration, "input %q is not a simple duration", s)
}
matches := simpleDurationRegExp.FindStringSubmatch(s)
numStr := matches[1]
unit := matches[2]
num, err := strconv.ParseInt(numStr, 10, 64)
if err != nil {
return nil, err
}
switch unit {
case "d":
d := Duration(time.Duration(num) * 24 * time.Hour)
return &SimpleDuration{num, unit, d}, nil
case "w":
d := Duration(time.Duration(num) * 7 * 24 * time.Hour)
return &SimpleDuration{num, unit, d}, nil
case "h":
d := Duration(time.Duration(num) * time.Hour)
return &SimpleDuration{num, unit, d}, nil
}
return nil, errors.Wrapf(ErrNotSimpleDuration, "input %q is not a simple duration", s)
}

View File

@ -26,6 +26,12 @@ func (d *Duration) UnmarshalJSON(data []byte) error {
switch t := o.(type) {
case string:
sd, err := ParseSimpleDuration(t)
if err == nil {
*d = sd.Duration
return nil
}
dd, err := time.ParseDuration(t)
if err != nil {
return err