如何在GO中实现跨平台文件锁定

I need to implement the following behavior in GO:

  1. A process should be able to read a file irrespective if any other process has locked the file for writing
  2. A process should obtain a write lock, before it can write to the file. This is to ensure that multiple processes cannot write to the same file
  3. A process should not wait to obtain the write lock, if it cannot obtain a lock it should move on

For UNIX based systems, syscall package in GO defines flock function, which could be used to implement the above behaviour in the following manner:

  1. Use syscall.flock function with LOCK_EX | LOCK_NB to try and obtain a lock before writing to the file
  2. Do not check for any locks before reading from the file

syscall package for Windows in GO, does not include flock. Given this, how best can I write code that can execute cross-platform and has the behavior described above?

I want to try and achieve this without making OS specific calls or using unsafe.

PS: I do not want mandatory file locking, the processes will check for file lock before performing file operations

Use compiler flags.

Flags for windows:

// +build windows,!linux
...

Flags for linux:

// +build linux,!windows
...

If you want to use platform native locking functions.

A workaround might be to allocate resources which are (supposedly) singletons across platforms like binding to a port and relying on that being possible only once. The error condition of the bind operation will be the deciding factor.

Personally I'd go with the option to use platform native options and just make an interface so that one can add tests easily and thereby make sure that things won't break.