plugin/timeouts - Allow ability to configure listening server timeouts (#5784)

This commit is contained in:
Rich
2022-12-28 11:14:16 +00:00
committed by GitHub
parent 6c9b49f5c2
commit e7ad486b50
14 changed files with 369 additions and 14 deletions

View File

@@ -0,0 +1,26 @@
package durations
import (
"fmt"
"strconv"
"time"
)
// NewDurationFromArg returns a time.Duration from a configuration argument
// (string) which has come from the Corefile. The argument has some basic
// validation applied before returning a time.Duration. If the argument has no
// time unit specified and is numeric the argument will be treated as seconds
// rather than GO's default of nanoseconds.
func NewDurationFromArg(arg string) (time.Duration, error) {
_, err := strconv.Atoi(arg)
if err == nil {
arg = arg + "s"
}
d, err := time.ParseDuration(arg)
if err != nil {
return 0, fmt.Errorf("failed to parse duration '%s'", arg)
}
return d, nil
}

View File

@@ -0,0 +1,51 @@
package durations
import (
"testing"
"time"
)
func TestNewDurationFromArg(t *testing.T) {
tests := []struct {
name string
arg string
wantErr bool
want time.Duration
}{
{
name: "valid GO duration - seconds",
arg: "30s",
want: 30 * time.Second,
},
{
name: "valid GO duration - minutes",
arg: "2m",
want: 2 * time.Minute,
},
{
name: "number - fallback to seconds",
arg: "30",
want: 30 * time.Second,
},
{
name: "invalid duration",
arg: "twenty seconds",
wantErr: true,
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
actual, err := NewDurationFromArg(test.arg)
if test.wantErr && err == nil {
t.Error("error was expected")
}
if !test.wantErr && err != nil {
t.Error("error was not expected")
}
if test.want != actual {
t.Errorf("expected '%v' got '%v'", test.want, actual)
}
})
}
}