Skip to content

Instantly share code, notes, and snippets.

@ulexxander
Created January 19, 2022 08:43
Show Gist options
  • Save ulexxander/a678baa2ae3454f9516a1cd7450ed6be to your computer and use it in GitHub Desktop.
Save ulexxander/a678baa2ae3454f9516a1cd7450ed6be to your computer and use it in GitHub Desktop.
Make Go time.Duration JSON marshalable and unmarshalable as strings.
// Duration embeds time.Duration and makes it more JSON-friendly.
// Instead of marshaling and unmarshaling as int64 it uses strings, like "5m" or "0.5s".
type Duration time.Duration
func (d Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(d.String())
}
func (d *Duration) UnmarshalJSON(data []byte) error {
var str string
if err := json.Unmarshal(data, &str); err != nil {
return err
}
val, err := time.ParseDuration(str)
*d = Duration(val)
return err
}
func (d Duration) String() string {
return time.Duration(d).String()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment