From d5ec073f75cc97d004e0fb30404834a4630cb6af Mon Sep 17 00:00:00 2001 From: bel Date: Sat, 17 Jul 2021 22:49:10 -0600 Subject: [PATCH] support 1w, 1d for loop --- server/ajax/form/form.go | 31 +++++++++++++++++++++++++++++-- server/ajax/form/form_test.go | 26 ++++++++++++++++++++++++++ 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/server/ajax/form/form.go b/server/ajax/form/form.go index 4539e3b..d9f0db2 100755 --- a/server/ajax/form/form.go +++ b/server/ajax/form/form.go @@ -7,6 +7,7 @@ import ( "io" "io/ioutil" "net/http" + "regexp" "strconv" "strings" "time" @@ -61,8 +62,34 @@ func ToStrArr(k string) []string { } func ToDuration(s string) time.Duration { - d, _ := time.ParseDuration(s) - return d + var d time.Duration + for _, c := range []struct { + key string + d time.Duration + }{ + {"d", time.Hour * 24}, + {"w", time.Hour * 24 * 7}, + } { + daysPattern := regexp.MustCompile(`(^|[a-z])[0-9]+` + c.key + `($|[0-9])`) + idxes := daysPattern.FindAllStringIndex(s, -1) + if len(idxes) > 1 { + return 0 + } + for _, idx := range idxes { + substr := s[idx[0]:idx[1]] + for len(substr) > 0 && (substr[0] < '0' || substr[0] > '9') { + substr = substr[1:] + } + for len(substr) > 0 && (substr[len(substr)-1] >= '0' && substr[len(substr)-1] <= '9') { + substr = substr[:len(substr)-1] + } + substr = strings.TrimSuffix(substr, c.key) + n, _ := strconv.Atoi(substr) + d += c.d * time.Duration(n) + } + } + d2, _ := time.ParseDuration(s) + return d2 + d } func ToTime(s string) time.Time { diff --git a/server/ajax/form/form_test.go b/server/ajax/form/form_test.go index 0bbf482..1ec324d 100755 --- a/server/ajax/form/form_test.go +++ b/server/ajax/form/form_test.go @@ -5,6 +5,7 @@ import ( "net/http/httptest" "strings" "testing" + "time" ) func TestGet(t *testing.T) { @@ -142,3 +143,28 @@ func testReq() *http.Request { "d": "e, f,g" }`)) } + +func TestToDuration(t *testing.T) { + cases := map[string]struct { + input string + want time.Duration + }{ + "invalid": {}, + "simple": {input: "1s", want: time.Second}, + "compound": {input: "1m1s", want: time.Minute + time.Second}, + "compound:unsorted": {input: "1s1m", want: time.Minute + time.Second}, + "extension:day": {input: "1d", want: 24 * time.Hour}, + "extension:week": {input: "1w", want: 24 * 7 * time.Hour}, + "extension:week,day": {input: "1w1d", want: 24 * 8 * time.Hour}, + } + + for name, d := range cases { + c := d + t.Run(name, func(t *testing.T) { + got := ToDuration(c.input) + if got != c.want { + t.Fatal(c.input, c.want, got) + } + }) + } +}