Last active
February 7, 2021 08:30
-
-
Save weaming/1426d5806385672a9510dfefcd615cb8 to your computer and use it in GitHub Desktop.
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
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