2

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?

1
  • 1
    In addition to Clean consider filepath.EvalSymlinks() and filepath.Abs().
    – Dave C
    Mar 23, 2015 at 19:58

3 Answers 3

3

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.

2

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.

0

In Go 1.4 method filepath.HasPrefix actually calls strings.HasPrefix so the answer is yes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.