...

Source file src/github.com/letsencrypt/boulder/config/duration.go

Documentation: github.com/letsencrypt/boulder/config

     1  package config
     2  
     3  import (
     4  	"encoding/json"
     5  	"errors"
     6  	"time"
     7  )
     8  
     9  // Duration is just an alias for time.Duration that allows
    10  // serialization to YAML as well as JSON.
    11  type Duration struct {
    12  	time.Duration `validate:"required"`
    13  }
    14  
    15  // ErrDurationMustBeString is returned when a non-string value is
    16  // presented to be deserialized as a ConfigDuration
    17  var ErrDurationMustBeString = errors.New("cannot JSON unmarshal something other than a string into a ConfigDuration")
    18  
    19  // UnmarshalJSON parses a string into a ConfigDuration using
    20  // time.ParseDuration.  If the input does not unmarshal as a
    21  // string, then UnmarshalJSON returns ErrDurationMustBeString.
    22  func (d *Duration) UnmarshalJSON(b []byte) error {
    23  	s := ""
    24  	err := json.Unmarshal(b, &s)
    25  	if err != nil {
    26  		var jsonUnmarshalTypeErr *json.UnmarshalTypeError
    27  		if errors.As(err, &jsonUnmarshalTypeErr) {
    28  			return ErrDurationMustBeString
    29  		}
    30  		return err
    31  	}
    32  	dd, err := time.ParseDuration(s)
    33  	d.Duration = dd
    34  	return err
    35  }
    36  
    37  // MarshalJSON returns the string form of the duration, as a byte array.
    38  func (d Duration) MarshalJSON() ([]byte, error) {
    39  	return []byte(d.Duration.String()), nil
    40  }
    41  
    42  // UnmarshalYAML uses the same format as JSON, but is called by the YAML
    43  // parser (vs. the JSON parser).
    44  func (d *Duration) UnmarshalYAML(unmarshal func(interface{}) error) error {
    45  	var s string
    46  	err := unmarshal(&s)
    47  	if err != nil {
    48  		return err
    49  	}
    50  	dur, err := time.ParseDuration(s)
    51  	if err != nil {
    52  		return err
    53  	}
    54  
    55  	d.Duration = dur
    56  	return nil
    57  }
    58  

View as plain text