if _, err := os.Stat("./conf/app.ini"); err != nil {
if os.IsNotExist(err) {
..... //Shows error if file not exists
} else {
..... // Shows success message like file is there
}
}
// validateDirectory expands a directory and checks that it exists
// it returns the full path to the directory on success
// validateDirectory("~/foo") -> ("/home/bbkane/foo", nil)
func validateDirectory(dir string) (string, error) {
dirPath, err := homedir.Expand(dir)
if err != nil {
return "", errors.WithStack(err)
}
info, err := os.Stat(dirPath)
if os.IsNotExist(err) {
return "", errors.Wrapf(err, "Directory does not exist: %v\n", dirPath)
}
if err != nil {
return "", errors.Wrapf(err, "Directory error: %v\n", dirPath)
}
if !info.IsDir() {
return "", errors.Errorf("Directory is a file, not a directory: %#v\n", dirPath)
}
return dirPath, nil
}
另外,重复@Dave C 的评论,如果你检查一个目录的存在是为了将一个文件写入其中,通常最好的方法就是在事后尝试打开它并处理一些错误:
// O_EXCL - used with O_CREATE, file must not exist
file, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0666)
if err != nil {
return errors.WithStack(err)
}
defer file.Close()