Home > Net >  os.Stat: permission denied => error(syscall.Errno) EACCES (13)
os.Stat: permission denied => error(syscall.Errno) EACCES (13)

Time:12-24

I'm creating a directory inside a unit test like this:

// The directory which is going to be created next to unit test executable.
const DirName string = "test-files"

Creating directory:

    // Create the directory if doesn't already exist.
    err := os.MkdirAll(DirName, os.ModeDir)
    if err != nil {
        return err
    }

    // Compose a sample file path to double-check its existence.
    pth := DirName   string(os.PathSeparator)   "samplefile.txt"


    exists, err := doesExist(pth)
    if err != nil {
        return err
    }

And checking file existence:


// Does file exist?
func doesExist(pth string) (bool, error) {

    // Check file existence
    // https://stackoverflow.com/a/10510718/3405291
    if _, err := os.Stat(pth); err != nil {
        if os.IsNotExist(err) {
            return false, nil
        } else {
            return true, err
        }
    }

    // Above conditions are skipped,
    // therefore file exists.
    return true, nil
}

The above code returns this error:

os.Stat: permission denied

error(syscall.Errno) EACCES (13)

I can double-check that the directory is actually created. But the permissions are d---------:

> ls -lh
d--------- 2 m3 users    6 Dec 23 20:30 test-files

How can I create the directory with the appropriate permissions?

CodePudding user response:

You're abusing the os.ModeDir constant. It's invented to serve as the bit mask to check whether the file's mode permissions bits (returned by, say, os.(*File).Stat indicate it's a directory.

The default permission mode bits to create a directory are 0777 but they are subject to umask.

  •  Tags:  
  • go
  • Related