Skip to content

Instantly share code, notes, and snippets.

@jblachly
Created July 24, 2016 20:25
Show Gist options
  • Save jblachly/bd106cbc3e0cf9a1fa0b91e418da3568 to your computer and use it in GitHub Desktop.
Save jblachly/bd106cbc3e0cf9a1fa0b91e418da3568 to your computer and use it in GitHub Desktop.
package main
import (
"encoding/json"
"fmt"
"time"
)
type Duration time.Duration
func (d *Duration) UnmarshalJSON(b []byte) (err error) {
if b[0] == '"' {
sd := string(b[1 : len(b)-1])
d.Duration, err = time.ParseDuration(sd)
return
}
var id int64
id, err = json.Number(string(b)).Int64()
d.Duration = time.Duration(id)
return
}
func (d Duration) MarshalJSON() (b []byte, err error) {
return []byte(fmt.Sprintf(`"%s"`, d.String())), nil
}
type Astruct struct {
Foo string `json:"baz"`
Date time.Time `json:"date"`
Dur Duration `json:duration`
}
func main() {
fiveSec, _ := time.ParseDuration("5s")
fmt.Println(fiveSec)
a := Astruct{Foo: "bar", Date: time.Now(), Dur: fiveSec}
fmt.Println(a)
b, err := json.Marshal(a)
if err != nil {
fmt.Println("error: ", err)
}
fmt.Println(string(b))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment