Handle quoted strings in UnmarshalJSON

This commit is contained in:
SALLEYRON Julien 2018-03-12 22:00:04 +01:00 committed by Traefiker Bot
parent 7860534f0c
commit e2b42ca57b
2 changed files with 15 additions and 3 deletions

4
Gopkg.lock generated
View file

@ -214,8 +214,8 @@
".",
"parse"
]
revision = "963366c29a7acc2d6e02f4f9bcf260d5a1cf4968"
version = "v1.1.1"
revision = "b4c2f060875361c070ed2bc300c5929b82f5fa2e"
version = "v1.1.2"
[[projects]]
branch = "master"

View file

@ -1,6 +1,7 @@
package parse
import (
"encoding/json"
"flag"
"fmt"
"reflect"
@ -203,6 +204,11 @@ func (d *Duration) UnmarshalText(text []byte) error {
return d.Set(string(text))
}
// MarshalJSON serializes the given duration value.
func (d *Duration) MarshalJSON() ([]byte, error) {
return json.Marshal(time.Duration(*d))
}
// UnmarshalJSON deserializes the given text into a duration value.
func (d *Duration) UnmarshalJSON(text []byte) error {
if v, err := strconv.Atoi(string(text)); err == nil {
@ -210,7 +216,13 @@ func (d *Duration) UnmarshalJSON(text []byte) error {
return nil
}
v, err := time.ParseDuration(string(text))
// We use json unmarshal on value because we have the quoted version
var value string
err := json.Unmarshal(text, &value)
if err != nil {
return err
}
v, err := time.ParseDuration(value)
*d = Duration(v)
return err
}