Test & refactor basepath validation into dedicated fn
parent
9710854b25
commit
fe35f189ed
|
@ -344,8 +344,7 @@ func (s *Server) Serve(ctx context.Context) error {
|
|||
return err
|
||||
}
|
||||
|
||||
re := regexp.MustCompile(`(\/{1}\w+)+`)
|
||||
if re.ReplaceAllLiteralString(s.Basepath, "") != "" {
|
||||
if !validBasepath(s.Basepath) {
|
||||
err := fmt.Errorf("Invalid basepath, must follow format \"/mybasepath\"")
|
||||
logger.
|
||||
WithField("component", "server").
|
||||
|
@ -539,3 +538,8 @@ func clientUsage(values client.Values) *client.Usage {
|
|||
},
|
||||
}
|
||||
}
|
||||
|
||||
func validBasepath(basepath string) bool {
|
||||
re := regexp.MustCompile(`(\/{1}\w+)+`)
|
||||
return re.ReplaceAllLiteralString(basepath, "") == ""
|
||||
}
|
||||
|
|
|
@ -3,6 +3,7 @@ package server
|
|||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/bouk/httprouter"
|
||||
)
|
||||
|
@ -18,3 +19,50 @@ func WithContext(ctx context.Context, r *http.Request, kv map[string]string) *ht
|
|||
}
|
||||
return r.WithContext(httprouter.WithParams(ctx, params))
|
||||
}
|
||||
|
||||
func Test_validBasepath(t *testing.T) {
|
||||
type args struct {
|
||||
basepath string
|
||||
}
|
||||
tests := []struct {
|
||||
name string
|
||||
args args
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "Basepath can be empty",
|
||||
args: args{
|
||||
basepath: "",
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "Basepath is not empty and valid",
|
||||
args: args{
|
||||
basepath: "/russ",
|
||||
},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "Basepath is not empty and invalid - no slashes",
|
||||
args: args{
|
||||
basepath: "russ",
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
{
|
||||
name: "Basepath is not empty and invalid - extra slashes",
|
||||
args: args{
|
||||
basepath: "//russ//",
|
||||
},
|
||||
want: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := validBasepath(tt.args.basepath); got != tt.want {
|
||||
t.Errorf("validBasepath() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue