2017-05-03 07:30:18 +02:00
|
|
|
// Package with the mostly static content (models) of this microservice
|
2017-04-04 19:28:46 +02:00
|
|
|
package models
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"strconv"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Duration is a TOML datatype
|
2017-05-03 07:30:18 +02:00
|
|
|
// A duration string is a possibly signed sequence of decimal numbers and a unit suffix,
|
|
|
|
// such as "300s", "1.5h" or "5d". Valid time units are "s", "m", "h", "d", "w".
|
2017-04-04 19:28:46 +02:00
|
|
|
type Duration struct {
|
|
|
|
time.Duration
|
|
|
|
}
|
|
|
|
|
2017-05-03 07:30:18 +02:00
|
|
|
// Function UnmarshalTOML parses a duration string
|
2017-04-04 19:28:46 +02:00
|
|
|
func (d *Duration) UnmarshalTOML(dataInterface interface{}) error {
|
|
|
|
var data string
|
|
|
|
switch dataInterface.(type) {
|
|
|
|
case string:
|
|
|
|
data = dataInterface.(string)
|
|
|
|
default:
|
|
|
|
return fmt.Errorf("invalid duration: \"%s\"", dataInterface)
|
|
|
|
}
|
|
|
|
// " + int + unit + "
|
|
|
|
if len(data) < 2 {
|
|
|
|
return fmt.Errorf("invalid duration: \"%s\"", data)
|
|
|
|
}
|
|
|
|
|
|
|
|
unit := data[len(data)-1]
|
|
|
|
value, err := strconv.Atoi(string(data[:len(data)-1]))
|
|
|
|
if err != nil {
|
|
|
|
return fmt.Errorf("unable to parse duration %s: %s", data, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
switch unit {
|
|
|
|
case 's':
|
|
|
|
d.Duration = time.Duration(value) * time.Second
|
|
|
|
case 'm':
|
|
|
|
d.Duration = time.Duration(value) * time.Minute
|
|
|
|
case 'h':
|
|
|
|
d.Duration = time.Duration(value) * time.Hour
|
|
|
|
case 'd':
|
|
|
|
d.Duration = time.Duration(value) * time.Hour * 24
|
|
|
|
case 'w':
|
|
|
|
d.Duration = time.Duration(value) * time.Hour * 24 * 7
|
|
|
|
case 'y':
|
|
|
|
d.Duration = time.Duration(value) * time.Hour * 24 * 365
|
|
|
|
default:
|
|
|
|
return fmt.Errorf("invalid duration unit: %s", string(unit))
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|