Skip to content

Instantly share code, notes, and snippets.

@weaming
Last active February 7, 2021 08:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save weaming/1426d5806385672a9510dfefcd615cb8 to your computer and use it in GitHub Desktop.
Save weaming/1426d5806385672a9510dfefcd615cb8 to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"encoding/json"
"fmt"
"time"
)
type Duration struct {
Duration time.Duration
}
func (d Duration) MarshalJSON() (b []byte, err error) {
return []byte(d.Duration.String()), nil
}
func (d Duration) String() string {
return d.Duration.String()
}
func (d *Duration) UnmarshalJSON(b []byte) (err error) {
b = bytes.TrimSpace(b)
if b[0] == '"' {
sd := string(b[1 : len(b)-1])
d0, err := time.ParseDuration(sd)
d.Duration = d0
return err
}
var id int64
id, err = json.Number(string(b)).Int64()
d.Duration = time.Duration(id)
return nil
}
func main() {
bs := []byte(`"3h23m13s"`)
fmt.Println(string(bs))
d := Duration{time.Duration(0)}
d.UnmarshalJSON(bs)
fmt.Println(d.String())
}
// output:
// > go run main.go
// "3h23m13s"
// 3h23m13s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment