How to Set File Permissions Using os.FileMode in Golang?

Mary-Kate Olsen
Release: 2024-11-11 22:26:03
Original
365 people have browsed it

How to Set File Permissions Using os.FileMode in Golang?

Using os.FileMode to Set File Permissions

Creating files in Golang often involves specifying file permissions using bitwise flags. However, many examples simply use numeric permissions, such as 0664, which can be inconvenient.

Properly Instantiating os.FileMode

To properly instantiate os.FileMode, you need to define the following:

  • Permission bits: These determine who can read, write, or execute the file.
  • User ID (UID): The user who owns the file.
  • Group ID (GID): The group that owns the file.

Example Implementation

Since there are no constants for permission bits in os or syscall, you can define your own:

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

This allows you to specify permissions directly:

dir_file_mode = os.ModeDir | (OS_USER_RWX | OS_ALL_R)
os.MkdirAll(dir_str, dir_file_mode)
Copy after login

The above is the detailed content of How to Set File Permissions Using os.FileMode in Golang?. 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