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?

Inaimathi
  • 13,853
  • 9
  • 49
  • 93

3 Answers3

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.

Rick-777
  • 9,714
  • 5
  • 34
  • 50
JimB
  • 104,193
  • 13
  • 262
  • 255
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.

B-Con
  • 454
  • 6
  • 15
0

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

Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105