Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions value.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import (
"encoding/json"
"fmt"
"strconv"
"time"
)

// Infer parses a value from a string into a suitable type.
// If s only contains digits, int64 is returned.
// 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.
Expand Down Expand Up @@ -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
}
7 changes: 7 additions & 0 deletions value_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}
Expand All @@ -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)
Expand Down
Loading