go - Golang check if string is valid path -


the golang filepath module (https://golang.org/pkg/path/filepath/) contains few functions manipulating paths , os.stat can used check if file exists. there way check if string forms valid path @ (regardless of whether there's file @ path or not)?

this problem sounds simple, not. here 2 possible solutions found :

solution 1 - academic

the idea here check given filepath based on rules.

problems

  1. operating system (unix / windows)
  2. filesystem
  3. reserved keywords

operating system

the first 1 easiest. go provides various tools os-specific filenames/separators/...

example in os package:

const (     pathseparator     = '/' // os-specific path separator     pathlistseparator = ':' // os-specific path list separator ) 

another 1 in filepath package:

// volumename returns leading volume name. // given "c:\foo\bar" returns "c:" on windows. // given "\\host\share\foo" returns "\\host\share". // on other platforms returns "". func volumename(path string) string {     return path[:volumenamelen(path)] } 

filesystem

filesystems have different restrictions. maximum length or charset allowed may vary. unfortunately, there no way can tell (not far know @ least) filesystem(s) path traverse.

reserved keywords

have blacklist of reserved keywords given os.

implementation

for solution, build lexer/parser.

the tradeoff not guarantee 100% filepath valid.

solution 2 - empirical

attempt create file , delete right after.

func isvalid(fp string) bool {   // check if file exists   if _, err := os.stat(fp); err == nil {     return true   }    // attempt create   var d []byte   if err := ioutil.writefile(fp, d, 0644); err == nil {     os.remove(fp) // , delete     return true   }    return false } 

the main benefit of solution is straightforward , more accurate. if file exists or can created @ given path, means valid. however, solution can invalidate valid paths because of restricted access.

summary

the first solution less accurate second one, though more correct puristic point of view. solution should pick depends on need. prefer false positives or false negatives? first solution can give false positives, while second 1 false negatives.


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -