I've got a situation where I'd like to check whether a particular path lands inside of a particular directory. My first instinct was to do something like
filepath.HasPrefix(filepath.Clean(path), dir)
but the procedure filepath.HasPrefix
is documented as existing for historic reasons only. Am I going to get the same effect by using strings.HasPrefix
, or is there something I'm missing?
You're not missing anything, look at the source:
// HasPrefix exists for historical compatibility and should not be used.
func HasPrefix(p, prefix string) bool {
return strings.HasPrefix(p, prefix)
}
Just use strings.HasPrefix(p, prefix)
directly.
In Go 1.4 method filepath.HasPrefix
actually calls strings.HasPrefix
so the answer is yes.
While you will get the same functionality with strings.HasPrefix
, it doesn't work in general. filepath.HasPrefix
is deprecated for a reason and it's approach should be considered deprecated too.
Consider filename=/foo/bar
and prefix=/fo
. This passes the strings.HasPrefix
test but clearly bar
is not in /fo
.
The proper approach would compare each directory name holistically.