summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/pkg/web/duration.go
blob: 85d5ef650fdee176695e7b53f3bff175be666418 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// SPDX-License-Identifier: GPL-3.0-or-later

package web

import (
	"encoding/json"
	"fmt"
	"strconv"
	"time"
)

type Duration time.Duration

func (d Duration) Duration() time.Duration {
	return time.Duration(d)
}

func (d Duration) String() string {
	return d.Duration().String()
}

func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
	var s string

	if err := unmarshal(&s); err != nil {
		return err
	}

	if v, err := time.ParseDuration(s); err == nil {
		*d = Duration(v)
		return nil
	}
	if v, err := strconv.ParseInt(s, 10, 64); err == nil {
		*d = Duration(time.Duration(v) * time.Second)
		return nil
	}
	if v, err := strconv.ParseFloat(s, 64); err == nil {
		*d = Duration(v * float64(time.Second))
		return nil
	}

	return fmt.Errorf("unparsable duration format '%s'", s)
}

func (d Duration) MarshalYAML() (any, error) {
	seconds := float64(d) / float64(time.Second)
	return seconds, nil
}

func (d *Duration) UnmarshalJSON(b []byte) error {
	s := string(b)

	if v, err := time.ParseDuration(s); err == nil {
		*d = Duration(v)
		return nil
	}
	if v, err := strconv.ParseInt(s, 10, 64); err == nil {
		*d = Duration(time.Duration(v) * time.Second)
		return nil
	}
	if v, err := strconv.ParseFloat(s, 64); err == nil {
		*d = Duration(v * float64(time.Second))
		return nil
	}

	return fmt.Errorf("unparsable duration format '%s'", s)
}

func (d Duration) MarshalJSON() ([]byte, error) {
	seconds := float64(d) / float64(time.Second)
	return json.Marshal(seconds)
}