Skip to content

Commit

Permalink
fix: parsing struct with duration like 90s (#151)
Browse files Browse the repository at this point in the history
  • Loading branch information
fiksn authored Jul 1, 2023
1 parent ecb0bbe commit 340d324
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 2 deletions.
1 change: 1 addition & 0 deletions config_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -447,3 +447,4 @@ func TestMapStringStringParseEnv(t *testing.T) {
is.Eq(shellVal, sMap["key3"])
})
}

26 changes: 26 additions & 0 deletions issues_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"os"
"testing"
"time"
"fmt"

"github.com/gookit/config/v2"
"github.com/gookit/config/v2/ini"
Expand Down Expand Up @@ -435,3 +436,28 @@ func TestIssues_146(t *testing.T) {
assert.Eq(t, 10*time.Second, cc.DefaultEnv)
assert.Eq(t, 15*time.Second, cc.NoEnv)
}

type DurationStruct struct {
Duration time.Duration
}

func TestDuration(t *testing.T) {
var (
err error
str string
)

c := config.New("test").WithOptions(config.ParseTime)
is := assert.New(t)
dur := DurationStruct{}

for _, seconds := range []int{10, 90} {
str = fmt.Sprintf(`{ "Duration": "%ds" }`, seconds)

err = c.LoadSources(config.JSON, []byte(str))
is.Nil(err)
err = c.Decode(&dur)
is.Nil(err)
is.Equal(float64(seconds), dur.Duration.Seconds())
}
}
2 changes: 1 addition & 1 deletion testdata/issues59.ini
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
; exported at 2023-06-11 13:58:47
; exported at 2023-07-01 14:46:07

age = 123
baseKey = value
Expand Down
2 changes: 1 addition & 1 deletion util.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func ValDecodeHookFunc(parseEnv, parseTime bool) mapstructure.DecodeHookFunc {
}

// start char is number(1-9)
if str[0] > '0' && str[0] < '9' {
if str[0] > '0' && str[0] <= '9' {
// parse time string. eg: 10s
if parseTime && t.Kind() == reflect.Int64 {
dur, err := time.ParseDuration(str)
Expand Down

0 comments on commit 340d324

Please sign in to comment.