mirror of
https://github.com/netbirdio/netbird.git
synced 2024-12-15 03:11:02 +01:00
38 lines
684 B
Go
38 lines
684 B
Go
|
package util
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"errors"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
//Duration is used strictly for JSON requests/responses due to duration marshalling issues
|
||
|
type Duration struct {
|
||
|
time.Duration
|
||
|
}
|
||
|
|
||
|
func (d Duration) MarshalJSON() ([]byte, error) {
|
||
|
return json.Marshal(d.String())
|
||
|
}
|
||
|
|
||
|
func (d *Duration) UnmarshalJSON(b []byte) error {
|
||
|
var v interface{}
|
||
|
if err := json.Unmarshal(b, &v); err != nil {
|
||
|
return err
|
||
|
}
|
||
|
switch value := v.(type) {
|
||
|
case float64:
|
||
|
d.Duration = time.Duration(value)
|
||
|
return nil
|
||
|
case string:
|
||
|
var err error
|
||
|
d.Duration, err = time.ParseDuration(value)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
return nil
|
||
|
default:
|
||
|
return errors.New("invalid duration")
|
||
|
}
|
||
|
}
|