Duration for JSON/YAML marshalling
parent
7a88fc6f5e
commit
11f1c9cefd
2
go.mod
2
go.mod
|
|
@ -1,3 +1,5 @@
|
|||
module replicator
|
||||
|
||||
go 1.21.1
|
||||
|
||||
require gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
|
|
|
|||
|
|
@ -0,0 +1,3 @@
|
|||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
|
@ -1,20 +1,53 @@
|
|||
package replicator
|
||||
|
||||
import "net/url"
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/url"
|
||||
"time"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
type (
|
||||
Config struct {
|
||||
Local Storage
|
||||
Remote Storage
|
||||
Src Storage
|
||||
Dest Storage
|
||||
Interval Duration
|
||||
}
|
||||
|
||||
Storage struct {
|
||||
Driver url.URL
|
||||
Full Stream
|
||||
Incremental Stream
|
||||
Driver url.URL
|
||||
}
|
||||
|
||||
Stream struct {
|
||||
Disabled bool
|
||||
}
|
||||
Duration time.Duration
|
||||
)
|
||||
|
||||
func (d *Duration) UnmarshalJSON(b []byte) error {
|
||||
var s string
|
||||
if err := json.Unmarshal(b, &s); err != nil {
|
||||
return err
|
||||
}
|
||||
d2, err := time.ParseDuration(s)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*d = Duration(d2)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (d Duration) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(time.Duration(d).String())
|
||||
}
|
||||
|
||||
func (d *Duration) UnmarshalYAML(value *yaml.Node) error {
|
||||
var s string
|
||||
if err := value.Decode(&s); err != nil {
|
||||
return err
|
||||
}
|
||||
b, _ := json.Marshal(s)
|
||||
return d.UnmarshalJSON(b)
|
||||
}
|
||||
|
||||
func (d Duration) MarshalYAML() (interface{}, error) {
|
||||
return time.Duration(d).String(), nil
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,30 @@
|
|||
package replicator
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"gopkg.in/yaml.v3"
|
||||
)
|
||||
|
||||
func TestDuration(t *testing.T) {
|
||||
d := Duration(3*time.Second + time.Minute)
|
||||
var d2 Duration
|
||||
if b, err := json.Marshal(d); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if err := json.Unmarshal(b, &d2); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if d != d2 {
|
||||
t.Fatal(d, d2)
|
||||
}
|
||||
|
||||
var d3 Duration
|
||||
if b, err := yaml.Marshal(d); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if err := yaml.Unmarshal(b, &d3); err != nil {
|
||||
t.Fatal(err)
|
||||
} else if d != d3 {
|
||||
t.Fatal(d, d3)
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue