Add marshallable duration
MODIFY
times/times.go
times/times.go
package times
import (
+ "encoding/json"
+ "errors"
"fmt"
"time"
@@ -32,3 +34,30 @@ func TimeToString(time *time.Time) string {
func AreDatesTheSameDay(t1, t2 time.Time) bool {
return t1.Year() == t2.Year() && t1.YearDay() == t2.YearDay()
}
+
+type Duration time.Duration
+
+func (d Duration) MarshalJSON() ([]byte, error) {
+ return json.Marshal(time.Duration(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:
+ tmp, err := time.ParseDuration(value)
+ if err != nil {
+ return err
+ }
+ *d = Duration(tmp)
+ return nil
+ default:
+ return errors.New("invalid duration")
+ }
+}

Add marshallable duration