Cross-platform way to check if a directory is writable in Golang?
Feb 10, 2024 pm 12:51 PMIn 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.
Question content
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):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
|
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?
Workaround
This is how I achieved my goal without conditional compilation since permissions and privileges can differ between operating systems.
- I tried using
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
|
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!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Go language pack import: What is the difference between underscore and without underscore?

How to implement short-term information transfer between pages in the Beego framework?

How do I write mock objects and stubs for testing in Go?

How to convert MySQL query result List into a custom structure slice in Go language?

How can I define custom type constraints for generics in Go?

How can I use tracing tools to understand the execution flow of my Go applications?

How to write files in Go language conveniently?
