Instantiating os.FileMode for File Creation/Updating
Instantiating os.FileMode correctly ensures proper permission settings for files during creation or update. Many tutorials resort to setting permission bits directly, but a more precise approach involves utilizing the os.FileMode type.
Custom Constants for Permission Setting
In the absence of predefined constants in os or syscall, you can declare your own:
const ( OS_READ = 04 OS_WRITE = 02 OS_EX = 01 ... OS_ALL_RWX = OS_ALL_RW | OS_ALL_X )
Example of Precision Permission Setting
Here's an example demonstrating the usage of custom constants:
func FileWrite(path string, r io.Reader, uid, gid int, perms string) (int64, error) { fileMode := os.FileMode(0) if perms[0] == '6' { fileMode |= OS_USER_RW } else if perms[0] == '7' { fileMode |= OS_USER_RWX } ... // Continue setting file mode based on the remaining characters of `perms` ... w, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, fileMode) ... }
Benefits of Custom Constant Approach
Custom constants provide:
The above is the detailed content of How to Precisely Set File Permissions in Go using `os.FileMode`?. For more information, please follow other related articles on the PHP Chinese website!