I've just started learning Go. I'm writing a small server application, and the function (method) that handles the requests (through http.HandleFunc) writes to a file - always the same file. Since, as I understand, http.HandleFunc starts a new goroutine for each request, I'm worried that the file writes might end up interfering with each other in some way - by blocking each other or just overlapping.
Looking at the actual output this problem has not arisen so far, but could it arise, and if so how do I fix it?
Here's a cleaned up version of my code:
package main
import (
"os"
"net/http"
)
type Service struct{
file *os.File
}
func (ser *Service) handleRequest(w http.ResponseWriter, req *http.Request){
//do lots of stuff that does not affect file
message := ...
n, err := ser.file.Write(message) //This is what I'm worried about
//handle error and wrap up
}
func main(){
m := http.NewServeMux()
fi,err := os.Open("/boolanger/file.txt")
//handle error
ser := &Service{file:fi}
m.HandleFunc("/service/", ser.handleRequest)
server := http.Server{
Addr: ":8080",
Handler: m}
serverError := server.ListenAndServe()
}
Ideally I'd like the file writes to be made in the order the requests came in, but this is not that important. I'm more worried about the different file writes interfering in some way.