1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-18 02:17:05 +00:00

new {weekday} path parameter type

This commit is contained in:
kataras
2022-06-23 23:01:52 +03:00
parent 999e83723b
commit 8bfea48cd6
6 changed files with 146 additions and 12 deletions

View File

@@ -514,6 +514,36 @@ func TestDateEvaluatorRaw(t *testing.T) {
}
}
func TestWeekdayEvaluatorRaw(t *testing.T) {
tests := []struct {
pass bool
input string
expected time.Weekday
}{
{true, "Monday", time.Monday}, // 0
{true, "monday", time.Monday}, // 1
{false, "Sundays", time.Weekday(-1)}, // 2
{false, "sundays", time.Weekday(-1)}, // 3
{false, "-1", time.Weekday(-1)}, // 4
{true, "0000002", time.Tuesday}, // 5
{true, "3", time.Wednesday}, // 6
{true, "6", time.Saturday}, // 7
}
for i, tt := range tests {
testEvaluatorRaw(t, Weekday, tt.input, reflect.TypeOf(time.Weekday(0)).Kind(), tt.pass, i)
if v, ok := Weekday.Evaluator(tt.input); ok {
if value, ok := v.(time.Weekday); ok {
if expected, got := tt.expected, value; expected != got {
t.Fatalf("[%d] expected: %s but got: %s", i, expected, got)
}
} else {
t.Fatalf("[%d] expected to be able to cast as time.Weekday directly", i)
}
}
}
}
func TestConvertBuilderFunc(t *testing.T) {
fn := func(min uint64, slice []string) func(string) bool {
return func(paramValue string) bool {

View File

@@ -444,6 +444,48 @@ var (
return tt, true
})
// ErrParamNotWeekday is fired when the parameter value is not a form of a time.Weekday.
ErrParamNotWeekday = errors.New("parameter is not a valid weekday")
longDayNames = map[string]time.Weekday{
"Sunday": time.Sunday,
"Monday": time.Monday,
"Tuesday": time.Tuesday,
"Wednesday": time.Wednesday,
"Thursday": time.Thursday,
"Friday": time.Friday,
"Saturday": time.Saturday,
// lowercase.
"sunday": time.Sunday,
"monday": time.Monday,
"tuesday": time.Tuesday,
"wednesday": time.Wednesday,
"thursday": time.Thursday,
"friday": time.Friday,
"saturday": time.Saturday,
}
// Weekday type, returns a type of time.Weekday.
// Valid values:
// 0 to 7 (leading zeros don't matter) or "Sunday" to "Monday" or "sunday" to "monday".
Weekday = NewMacro("weekday", "", false, false, func(paramValue string) (interface{}, bool) {
d, ok := longDayNames[paramValue]
if !ok {
// try parse from integer.
n, err := strconv.Atoi(paramValue)
if err != nil {
return fmt.Errorf("%s: %w", paramValue, err), false
}
if n < 0 || n > 6 {
return fmt.Errorf("%s: %w", paramValue, ErrParamNotWeekday), false
}
return time.Weekday(n), true
}
return d, true
})
// Defaults contains the defaults macro and parameters types for the router.
//
// Read https://github.com/kataras/iris/tree/master/_examples/routing/macros for more details.
@@ -467,6 +509,7 @@ var (
Mail,
Email,
Date,
Weekday,
}
)