dou72260 2019-08-29 12:43
浏览 165
已采纳

异步文件写入Golang中的http.HandleFunc

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.

  • 写回答

1条回答 默认 最新

  • doqp87012 2019-08-29 13:09
    关注

    File writes are blocking and atomic. So, concurrent writes will wait for each other, and will not "interfere" with each other, though output may be interleaved. If you want more control, wrap your writes with a sync.Mutex to ensure that one routine completes all its writes before the next routine starts its writes.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)