support 1w, 1d for loop
parent
b8f0efc01c
commit
d5ec073f75
|
|
@ -7,6 +7,7 @@ import (
|
||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"regexp"
|
||||||
"strconv"
|
"strconv"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
@ -61,8 +62,34 @@ func ToStrArr(k string) []string {
|
||||||
}
|
}
|
||||||
|
|
||||||
func ToDuration(s string) time.Duration {
|
func ToDuration(s string) time.Duration {
|
||||||
d, _ := time.ParseDuration(s)
|
var d time.Duration
|
||||||
return d
|
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 {
|
func ToTime(s string) time.Time {
|
||||||
|
|
|
||||||
|
|
@ -5,6 +5,7 @@ import (
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestGet(t *testing.T) {
|
func TestGet(t *testing.T) {
|
||||||
|
|
@ -142,3 +143,28 @@ func testReq() *http.Request {
|
||||||
"d": "e, f,g"
|
"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)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue