Home > Mobile >  How to create a directory that has specific permissions
How to create a directory that has specific permissions

Time:09-06

I'm trying to create a directory in Go with very specific permissions. I need drwxrwxr-x but I don't know how to do it with os.Mkdir(). I've tried os.ModeDir, os.ModePerm and os.ModeSticky

I'm on linux and I do not care if the solution will work in windows. it can, but it doesn't have to.

My issue is that I'm trying to create a directory that is later used within the program itself (the program creates the directory and it uses it to write files to).

CodePudding user response:

To quote https://stackoverflow.com/a/59963154/1079543:

all programs run with a umask setting...the set of permissions that the system will automatically remove from file and directory creation requests.

Setting the umask to 0 when you start the program produces the result you're looking for:

//go:build unix
package main

import (
    "log"
    "os"

    "golang.org/x/sys/unix"
)

func main() {
    unix.Umask(0)
    if err := os.Mkdir("dirname", 0775); err != nil {
        log.Fatalf("failed to create directory: %v", err)
    }
}

//go:build unix should be true "if GOOS is a Unix or Unix-like system" per: https://pkg.go.dev/cmd/go#hdr-Build_constraints

The old way to do this was with syscall.Umask(0). This package is now deprecated per: https://go.googlesource.com/proposal/ /refs/heads/master/design/freeze-syscall.md

  • Related