How to Precisely Set File Permissions in Go using `os.FileMode`?

Barbara Streisand
Release: 2024-11-12 17:57:01
Original
479 people have browsed it

How to Precisely Set File Permissions in Go using `os.FileMode`?

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

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

Benefits of Custom Constant Approach

Custom constants provide:

  • Clear and portable permission-setting mechanism
  • Elimination of magic numbers and potential confusion
  • Flexibility to manipulate permissions based on desired scenarios

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!

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