<p>I have a golang end point that receive uploaded file</p>
<p>I discover that creating a file and calling <code>iotil.ReadFile</code> immediately will lead to empty data returned even after file sync.</p>
<p>The data is only available after the second call to the same function or wait 5 second.</p>
<pre><code> r.ParseMultipartForm(32 << 20)
file, handler, err := r.FormFile("my_input_name")
f, err := os.OpenFile("./img_dump/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return
}
f.Sync()
// data is empty [] when first called
data, err := ioutil.ReadFile("/myAbsolutePath/img_dump/" + handler.Filename)
c1 := make(chan string, 1)
go func() {
time.Sleep(time.Second * 5)
c1 <- "result 1"
}()
go func(name string) {
select {
case _ = <-c1:
data, err = ioutil.ReadFile("/myAbsolutePath/img_dump/" + name)
fmt.Println("after sleep")
// This only works if I don't try f.Close(), data is not empty
fmt.Println(len(data))
}
}(handler.Filename)
</code></pre>
<p>Does anyone know how to avoid race condition between creating and reading a file?</p>
<hr/>**评论:**<br/><br/>felixge: <pre><p>I don't think you're seeing a race condition. It looks like you're simply not copying the data from your <code>file</code> instance to your <code>f</code> file?</p></pre>multishotkey: <pre><p>hmm, but I added wait 5 second and it worked, I added that part of the code to the post. </p>
<p>edit: actually you are right, another file is populating it in some other goroutine, thanks :)</p></pre>chmikes: <pre><p>Comparing with <a href="https://astaxie.gitbooks.io/build-web-application-with-golang/en/04.5.html" rel="nofollow">this</a> example, you don't test the returned error from FormFile. There could have been an error. </p>
<p>You are also missing the io.Copy() which I guess writes the data in the file. You should also close that file. </p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传