I'm trying to create a directory using os.Mkdir() and then create files in it, similar to this script:
package main
import (
"log"
"os"
"path"
)
func main() {
dir := "test_dir"
os.Mkdir(dir, os.ModeDir)
fileName := path.Join(dir, "file.txt")
_, err := os.Create(fileName)
if err != nil {
log.Fatalf("create file: %v", err)
}
}
However, if I run this, I get
> go run fileperms.go
2019/10/15 14:44:02 create file: open test_dir/file.txt: permission denied
exit status 1
It is not immediately clear to me from https://golang.org/pkg/os/#FileMode how to specify the FileMode in order to allow the same script to create files in the newly-created directory. How can I achieve this?
os.Mkdirshould pass0777as the second argument. You don't needos.ModeDiras it's implied by the make-directory function. The low 3 bits are Unix-style permissions; it's up to the OS to translate them to whatever the OS uses. On Unix-like systems, the current umask will take away any unwanted permissions, so you should usually grant all permissions to everyone to start.0700: rwx for user, nothing for group or other. A typical umask is002or022, to take away other, and maybe group, write permission.