// Copyright (c) 2020 Gitpod GmbH. All rights reserved.1// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34package util56import (7"encoding/json"8"errors"9"time"10)1112// Duration is an alias for time.Duration to facilitate JSON unmarshaling13// see https://stackoverflow.com/questions/48050945/how-to-unmarshal-json-into-durations14type Duration time.Duration1516// UnmarshalJSON parses the duration to a time.Duration17func (d *Duration) UnmarshalJSON(b []byte) error {18var v interface{}19if err := json.Unmarshal(b, &v); err != nil {20return err21}22switch value := v.(type) {23case float64:24*d = Duration(time.Duration(value))25return nil26case string:27tmp, err := time.ParseDuration(value)28if err != nil {29return err30}31*d = Duration(tmp)32return nil33default:34return errors.New("invalid duration")35}36}3738// MarshalJSON turns a duration into a string39func (d Duration) MarshalJSON() ([]byte, error) {40return json.Marshal(time.Duration(d).String())41}4243// String produces a string representation of this duration44func (d Duration) String() string {45return time.Duration(d).String()46}474849