5

I'm new to Go, have a bit of a problem with reading default file permissions / system mask. Of course I can specify fixed permissions:

f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY, 0600)

But I would like the program to behave nicely and open a file with user's account set umask. How can I do that?

LetMeSOThat4U
  • 6,470
  • 10
  • 53
  • 93

1 Answers1

10

It already works like you want it.

Just use "0666" and the umask will be applied.

f, err := os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY, 0666)

For me with umask 0022 I get:

$ go run x.go  ; ls -l filename
-rw-r--r--  1 ask  wheel  0 May 24 00:18 filename

Use 0660 (for example) if you always want the file to be unreadable by "other", no matter the umask.

Ask Bjørn Hansen
  • 6,784
  • 2
  • 26
  • 40
  • 1
    I wish the docs said so: http://golang.org/pkg/os/#OpenFile "OpenFile is the generalized open call; most users will use Open or Create instead. It opens the named file with specified flag (O_RDONLY etc.) and perm, (0666 etc.) if applicable". For me that states clearly that it uses the perm, not applies account's umask to compute permission, though on reading the source code I see it is so: http://golang.org/src/pkg/os/file_unix.go?s=2041:2116#L77 – LetMeSOThat4U May 24 '14 at 08:20
  • Note that `os.Create(fpath)` already applies 0666 permissions (also filtered by the umask, of course), and is thus exactly equivalent to and preferred over using `os.OpenFile(fpath, os.O_CREATE|os.O_WRONLY, 0666)` – krait May 25 '14 at 18:07
  • 1
    The Go documentation does not cover aspects of the system that the kernel forces upon all programs. If you don't see your question answered in the documentation, you can reasonably expect that the answer is language-agnostic. – krait May 25 '14 at 18:07
  • @JohnDoe Yeah, I can see it'd be nice if it was explained more -- but as the other commenters said this is standard system stuff so a reader familiar with unix would find it superfluous. The "os" package is mostly a thin veneer on the underlying system calls so it (reasonably I think) assumes you'll either know how those work or read up on it in your system documentation. – Ask Bjørn Hansen Jun 14 '14 at 21:13