Files
bc-netts-energy/internal/config/types.go
2025-11-03 19:26:48 +08:00

47 lines
1.1 KiB
Go

package config
import (
"fmt"
"time"
"gopkg.in/yaml.v3"
)
// Duration wraps time.Duration to support YAML unmarshalling from strings.
type Duration time.Duration
// UnmarshalYAML parses a duration string such as "5s" or "2m".
func (d *Duration) UnmarshalYAML(value *yaml.Node) error {
if value.Kind != yaml.ScalarNode {
return fmt.Errorf("duration must be a string, got %s", value.ShortTag())
}
parsed, err := time.ParseDuration(value.Value)
if err != nil {
return fmt.Errorf("parse duration %q: %w", value.Value, err)
}
*d = Duration(parsed)
return nil
}
// MarshalYAML converts the duration to a string value.
func (d Duration) MarshalYAML() (any, error) {
return time.Duration(d).String(), nil
}
// Duration returns the underlying time.Duration.
func (d Duration) Duration() time.Duration {
return time.Duration(d)
}
// IsZero reports whether the duration has been set.
func (d Duration) IsZero() bool {
return time.Duration(d) == 0
}
// SetDefault assigns the provided default if the duration is zero.
func (d *Duration) SetDefault(def time.Duration) {
if d.IsZero() {
*d = Duration(def)
}
}