Compile regex globally

This commit is contained in:
Conrad Hoffmann 2022-03-16 14:37:21 +01:00
parent 78bd2a9b84
commit b3277148d7

View File

@ -21,7 +21,10 @@ type filesystemBackend struct {
path string path string
} }
var nilBackend carddav.Backend = (*filesystemBackend)(nil) var (
nilBackend carddav.Backend = (*filesystemBackend)(nil)
validFilenameRegex = regexp.MustCompile(`^/[A-Za-z0-9_-]+(.[a-zA-Z]+)?$`)
)
func NewFilesystem(path string) (carddav.Backend, error) { func NewFilesystem(path string) (carddav.Backend, error) {
info, err := os.Stat(path) info, err := os.Stat(path)
@ -65,8 +68,7 @@ func (b *filesystemBackend) safePath(ctx context.Context, path string) (string,
} }
// We are mapping to local filesystem path, so be conservative about what to accept // We are mapping to local filesystem path, so be conservative about what to accept
// TODO this changes once multiple addess books are supported // TODO this changes once multiple addess books are supported
var valid = regexp.MustCompile(`^/[A-Za-z0-9_-]+(.[a-zA-Z]+)?$`) if !validFilenameRegex.MatchString(path) {
if !valid.MatchString(path) {
return "", fmt.Errorf("invalid request path") return "", fmt.Errorf("invalid request path")
} }
return filepath.Join(basePath, path), nil return filepath.Join(basePath, path), nil