File: duration.go

package info (click to toggle)
golang-github-traefik-paerser 0.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 612 kB
  • sloc: makefile: 14
file content (62 lines) | stat: -rw-r--r-- 1,703 bytes parent folder | download
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
package types

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

// Duration is a custom type suitable for parsing duration values.
// It supports `time.ParseDuration`-compatible values and suffix-less digits; in
// the latter case, seconds are assumed.
type Duration time.Duration

// Set sets the duration from the given string value.
func (d *Duration) Set(s string) error {
	if v, err := strconv.ParseInt(s, 10, 64); err == nil {
		*d = Duration(time.Duration(v) * time.Second)
		return nil
	}

	v, err := time.ParseDuration(s)
	*d = Duration(v)
	return err
}

// String returns a string representation of the duration value.
func (d Duration) String() string { return (time.Duration)(d).String() }

// MarshalText serialize the given duration value into a text.
func (d Duration) MarshalText() ([]byte, error) {
	return []byte(d.String()), nil
}

// UnmarshalText deserializes the given text into a duration value.
// It is meant to support TOML decoding of durations.
func (d *Duration) UnmarshalText(text []byte) error {
	return d.Set(string(text))
}

// MarshalJSON serializes the given duration value.
func (d Duration) MarshalJSON() ([]byte, error) {
	return []byte(`"` + time.Duration(d).String() + `"`), nil
}

// UnmarshalJSON deserializes the given text into a duration value.
func (d *Duration) UnmarshalJSON(text []byte) error {
	if v, err := strconv.ParseInt(string(text), 10, 64); err == nil {
		*d = Duration(time.Duration(v) * time.Second)
		return nil
	}

	// We use json unmarshal on value because we have the quoted version
	var value string
	err := json.Unmarshal(text, &value)
	if err != nil {
		return err
	}

	v, err := time.ParseDuration(value)
	*d = Duration(v)
	return err
}