In Golang, to check whether a directory is writable, you can use `os.FileMode` as a cross-platform method. First, obtain the file information of the directory through the `os.Stat` function. Then, use the `file.Mode().Perm()` method to obtain the file's permissions. Finally, use the `file.Mode().IsDir()` method to determine whether it is a directory. If the permissions of the directory are `0777`, it means it is writable; if the permissions are `0444` or `0555`, it means it is read-only; if the permissions are other values, it means it is not writable. This method is suitable for cross-platform directory writability checking.
I have a program that is trying to write a file to a directory using golang. I need it to work in macos, linux, and windows (at least).
golang provides the following test - but it seems to be limited to linux (from the so question linked below):
func IsWritable(path string) (isWritable bool, err error) { isWritable = false info, err := os.Stat(path) if err != nil { fmt.Println("Path doesn't exist") return } err = nil if !info.IsDir() { fmt.Println("Path isn't a directory") return } // Check if the user bit is enabled in file permission if info.Mode().Perm() & (1 << (uint(7))) == 0 { fmt.Println("Write permission bit is not set on this file for user") return } var stat syscall.Stat_t if err = syscall.Stat(path, &stat); err != nil { fmt.Println("Unable to get stat") return } err = nil if uint32(os.Geteuid()) != stat.Uid { isWritable = false fmt.Println("User doesn't have permission to write to this directory") return } isWritable = true return }
I saw this answer [1], but this question is 10 years old, is there a better way to accomplish this than conditional compilation?
Summary: I just want the go process to know if it can write to a given directory.
[1]How to determine whether a folder exists and is writable?
This is how I achieved my goal without conditional compilation since permissions and privileges can differ between operating systems.
os.createtemp
to create a temporary file in that directory. If the function returns no errors, there is no problem with the path or permissions and we can create the file in that directory. This is the code
func IsWritable(path string) (bool, error) { tmpFile := "tmpfile" file, err := os.CreateTemp(path, tmpFile) if err != nil { return false, err } defer os.Remove(file.Name()) defer file.Close() return true, nil } func main() { path := "absolute-directory-path" isWritable, err := IsWritable(path) if err != nil { panic(err) } if isWritable { // statements } }
The above is the detailed content of Cross-platform way to check if a directory is writable in Golang?. For more information, please follow other related articles on the PHP Chinese website!