How can a file be opened such that only one process can write to it at a time in Golang?
I am new to Golang and was trying to learn it by writing something. Was attempting to create a secret storage tool which stores, say, api keys to a file; during which I came across an issue - if two instance of same program runs together (hypothetically) a race condition can occur and damage the file.
So, I was checking for a way to lock the file so that only one process can write to it at a time. Reading simultaneously is ok.
Found this answer : How to get an exclusive lock on a file in go on stackoverflow. but in the comments of the same, it's mentioned
your package uses flock() for locking on Unix so doesn't provide OS level mandatory locking
Tried os.ModeExclusive
.
f, err := os.OpenFile(".secrets", os.O_RDWR|os.O_CREATE, os.ModeExclusive)
But it prevents the file from accessing the next time program runs. Can you please explain what this mode does. Not able to understand it from the docs.
Also tried:
f, err := os.OpenFile(".secrets", os.O_RDWR|os.O_CREATE, 0744)
On using the above, anyone can read/write when the file is opened.