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
Release: 2024-11-22 10:28:10
Original
981 people have browsed it

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
)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template