Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/common-go/util/duration.go
2498 views
1
// Copyright (c) 2020 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package util
6
7
import (
8
"encoding/json"
9
"errors"
10
"time"
11
)
12
13
// Duration is an alias for time.Duration to facilitate JSON unmarshaling
14
// see https://stackoverflow.com/questions/48050945/how-to-unmarshal-json-into-durations
15
type Duration time.Duration
16
17
// UnmarshalJSON parses the duration to a time.Duration
18
func (d *Duration) UnmarshalJSON(b []byte) error {
19
var v interface{}
20
if err := json.Unmarshal(b, &v); err != nil {
21
return err
22
}
23
switch value := v.(type) {
24
case float64:
25
*d = Duration(time.Duration(value))
26
return nil
27
case string:
28
tmp, err := time.ParseDuration(value)
29
if err != nil {
30
return err
31
}
32
*d = Duration(tmp)
33
return nil
34
default:
35
return errors.New("invalid duration")
36
}
37
}
38
39
// MarshalJSON turns a duration into a string
40
func (d Duration) MarshalJSON() ([]byte, error) {
41
return json.Marshal(time.Duration(d).String())
42
}
43
44
// String produces a string representation of this duration
45
func (d Duration) String() string {
46
return time.Duration(d).String()
47
}
48
49