You can't write to a closed file, so if you close it after each write operation, you also have to (re)open it before each write.
This would be quite inefficient. So instead leave it open, and only close it once your app is about to terminate (this is required because File.Write()
does not guarantee that when it returns the data is written to disk). Since you're writing the file from HTTP handlers, you should implement graceful server termination, and close the file after that. See Server.Shutdown()
for details.
Also, if the purpose of your shared file writing is to create some kind of logger, you could take advantage of the log
package, so you would not have to use a mutex. For details, see net/http set custom logger.