diff --git a/value.go b/value.go index 509af79..bb7d32c 100644 --- a/value.go +++ b/value.go @@ -4,6 +4,7 @@ import ( "encoding/json" "fmt" "strconv" + "time" ) // Infer parses a value from a string into a suitable type. @@ -11,6 +12,7 @@ import ( // If s is parsed as float, float64 is returned. // If s has unquoted values of true or false, bool is returned. // If s is equal to unquoted null, nil is returned. +// If s can be parsed as time.RFC3339, time.RFC3339Nano, "2006-01-02" or "2006-01-02 15:04:05", time.Time is returned. // If s starts with double quote ", string decoded from JSON is returned (mind JSON escaping rules). // If s starts with [ or {, any decoded from JSON is returned. // Otherwise, s is returned as is. @@ -52,5 +54,12 @@ func Infer(s string) interface{} { return f } + for _, layout := range []string{time.RFC3339, time.RFC3339Nano, "2006-01-02", "2006-01-02 15:04:05"} { + t, err := time.Parse(layout, s) + if err == nil { + return t + } + } + return s } diff --git a/value_test.go b/value_test.go index f52b0a7..0515925 100644 --- a/value_test.go +++ b/value_test.go @@ -2,12 +2,15 @@ package vars_test import ( "testing" + "time" "github.com/godogx/vars" "github.com/stretchr/testify/assert" ) func TestInfer(t *testing.T) { + tm := time.Now().Truncate(time.Millisecond).UTC() + for _, tc := range []struct { s string v interface{} @@ -23,6 +26,10 @@ func TestInfer(t *testing.T) { {`{"foo":"bar"}`, map[string]interface{}{"foo": "bar"}}, {`["abc", 1, false, null]`, []interface{}{"abc", 1.0, false, nil}}, {`{"foo":"ba....`, "infer JSON value {\"foo\":\"ba....: unexpected end of JSON input"}, + {tm.Format(time.RFC3339), tm.Truncate(time.Second)}, + {tm.Format(time.RFC3339Nano), tm}, + {tm.Format("2006-01-02"), tm.Truncate(24 * time.Hour)}, + {tm.Format("2006-01-02 15:04:05"), tm.Truncate(time.Second)}, } { t.Run(tc.s, func(t *testing.T) { v := vars.Infer(tc.s)