mirror of
https://github.com/XTLS/Xray-core.git
synced 2024-11-14 19:13:02 +00:00
34 lines
557 B
Go
34 lines
557 B
Go
|
package duration
|
||
|
|
||
|
import (
|
||
|
"encoding/json"
|
||
|
"fmt"
|
||
|
"time"
|
||
|
)
|
||
|
|
||
|
type Duration int64
|
||
|
|
||
|
func (d *Duration) MarshalJSON() ([]byte, error) {
|
||
|
dr := time.Duration(*d)
|
||
|
return json.Marshal(dr.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 string:
|
||
|
var err error
|
||
|
dr, err := time.ParseDuration(value)
|
||
|
if err != nil {
|
||
|
return err
|
||
|
}
|
||
|
*d = Duration(dr)
|
||
|
return nil
|
||
|
default:
|
||
|
return fmt.Errorf("invalid duration: %v", v)
|
||
|
}
|
||
|
}
|