Home >Backend Development >Golang >How to Instantiate os.FileMode in Go with UID, GID, and Octal Permissions?

How to Instantiate os.FileMode in Go with UID, GID, and Octal Permissions?

Linda Hamilton
Linda HamiltonOriginal
2024-11-22 10:28:101010browse

How to Instantiate os.FileMode in Go with UID, GID, and Octal Permissions?

How to Properly Instantiate os.FileMode

In Go, the os.FileMode type represents the file mode bits that specify the file's permissions. Several examples and tutorials demonstrate file creation, but many bypass the proper instantiation of os.FileMode, instead relying on setting permission bits directly.

Challenge

One seeks a method to instantiate os.FileMode correctly, utilizing provided UID, GID, and permission values represented as octal digits.

Solution

In lieu of relying on predefined constants, the following can be used:

const (
    OS_READ = 04
    OS_WRITE = 02
    OS_EX = 01
    OS_USER_SHIFT = 6
    OS_GROUP_SHIFT = 3
    OS_OTH_SHIFT = 0

    OS_USER_R = OS_READ << OS_USER_SHIFT
    OS_USER_W = OS_WRITE << OS_USER_SHIFT
    OS_USER_X = OS_EX << OS_USER_SHIFT
    OS_USER_RW = OS_USER_R | OS_USER_W
    OS_USER_RWX = OS_USER_RW | OS_USER_X

    OS_GROUP_R = OS_READ << OS_GROUP_SHIFT
    OS_GROUP_W = OS_WRITE << OS_GROUP_SHIFT
    OS_GROUP_X = OS_EX << OS_GROUP_SHIFT
    OS_GROUP_RW = OS_GROUP_R | OS_GROUP_W
    OS_GROUP_RWX = OS_GROUP_RW | OS_GROUP_X

    OS_OTH_R = OS_READ << OS_OTH_SHIFT
    OS_OTH_W = OS_WRITE << OS_OTH_SHIFT
    OS_OTH_X = OS_EX << OS_OTH_SHIFT
    OS_OTH_RW = OS_OTH_R | OS_OTH_W
    OS_OTH_RWX = OS_OTH_RW | OS_OTH_X

    OS_ALL_R = OS_USER_R | OS_GROUP_R | OS_OTH_R
    OS_ALL_W = OS_USER_W | OS_GROUP_W | OS_OTH_W
    OS_ALL_X = OS_USER_X | OS_GROUP_X | OS_OTH_X
    OS_ALL_RW = OS_ALL_R | OS_ALL_W
    OS_ALL_RWX = OS_ALL_RW | OS_GROUP_X
)

With these constants, permissions can be specified explicitly:

dir_file_mode := os.ModeDir | (OS_USER_RWX | OS_ALL_R)
os.MkdirAll(dir_str, dir_file_mode)

This method enables precise control over file permissions while eliminating the need for manually setting permission bits.

The above is the detailed content of How to Instantiate os.FileMode in Go with UID, GID, and Octal Permissions?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn