0

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).

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
kamkow1
  • 467
  • 2
  • 8
  • also, most tutorials online suggest os.ModePerm but it results in ```d---------``` and I cannot write to the directory – kamkow1 Sep 05 '22 at 18:18
  • 1
    Does this answer your question? [os.Mkdir and os.MkdirAll permissions](https://stackoverflow.com/questions/14249467/os-mkdir-and-os-mkdirall-permissions) – Bartosz Grzybowski Sep 05 '22 at 18:25

1 Answers1

1

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