Skip to content

Instantly share code, notes, and snippets.

@David-Lor
Created June 27, 2023 08:30
Show Gist options
  • Save David-Lor/5fe4915297b1066e7d337e909912ab58 to your computer and use it in GitHub Desktop.
Save David-Lor/5fe4915297b1066e7d337e909912ab58 to your computer and use it in GitHub Desktop.
GoLang custom time.Duration to parse from JSON/YAML
package main
import (
"encoding/json"
"fmt"
"time"
)
type MyDuration time.Duration
func (d *MyDuration) UnmarshalJSON(data []byte) error {
var durationStr string
if err := json.Unmarshal(data, &durationStr); err != nil {
return err
}
parsedDuration, err := time.ParseDuration(durationStr)
if err != nil {
return err
}
*d = MyDuration(parsedDuration)
return nil
}
func (d *MyDuration) ToTimeDuration() time.Duration {
return time.Duration(*d)
}
type MyStruct struct {
Duration MyDuration `json:"duration"`
}
func main() {
jsonData := `{"duration": "2m30s"}`
var jsonParsed MyStruct
err := json.Unmarshal([]byte(jsonData), &jsonParsed)
if err != nil {
fmt.Println("json.Unmarshal Error:", err)
return
}
fmt.Println("Parsed Duration (as MyDuration) nanoseconds:", jsonParsed.Duration)
fmt.Println("Parsed Duration (as time.Duration) nanoseconds:", jsonParsed.Duration)
fmt.Println("Parsed Duration (as time.Duration) string:", jsonParsed.Duration.ToTimeDuration().String())
time.Sleep(jsonParsed.Duration.ToTimeDuration())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment