Created
January 19, 2022 08:43
-
-
Save ulexxander/a678baa2ae3454f9516a1cd7450ed6be to your computer and use it in GitHub Desktop.
Make Go time.Duration JSON marshalable and unmarshalable as strings.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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