英文:
GoLang: Update file that is served by FileServer
问题
我正在使用FileServer来提供一个目录,代码如下所示:
go func() {
fs := http.FileServer(http.Dir("./view"))
err := http.ListenAndServe(":8000", fs)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}()
在view
目录中,我有一个index.html
文件,我正在尝试在提供view
目录的同时更新该文件。我观察到追加命令会阻塞,并且只有在停止提供目录后才会更新文件。
以下是修改文件的代码:
func AppendToFile() {
f, err := os.OpenFile("./view/index.html", os.O_RDWR, 0644)
if err != nil {
panic(err)
}
defer f.Close()
// 这假设文件以</body></html>结尾
f.Seek(-15, 2)
if _, err = f.WriteString("test test test\n"); err != nil {
panic(err)
}
if _, err = f.WriteString("</body></html>\n"); err != nil {
panic(err)
}
}
这是预期的行为吗?
谢谢!
英文:
I am serving a directory using FileServer as follows:
go func() {
fs := http.FileServer(http.Dir("./view"))
err := http.ListenAndServe(":8000", fs)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}()
Inside the view
directory I have an index.html
file, which I am trying to update while the view
directory is being served. I observe that the append commands block and update the file only after I stop serving the directory.
Below is the code to modify the file:
func AppendToFile() {
f, err := os.OpenFile("./view/index.html", os.O_RDWR, 0644)
if err != nil {
panic(err)
}
defer f.Close()
// This assumes that the file ends with </body></html>
f.Seek(-15, 2)
if _, err = f.WriteString("test test test\n"); err != nil {
panic(err)
}
if _, err = f.WriteString("</body></html>\n"); err != nil {
panic(err)
}
}
Is this the expected behavior?
Thank you!
答案1
得分: 3
http.FileServer函数只返回一个处理程序,所以它不会阻塞文件系统。
这里的问题可能与文件的偏移量有关。我在我的机器上尝试过,没有任何问题。
我已经修改了你的代码如下:
package main
import (
"net/http"
"os"
"time"
)
func main() {
t := time.NewTicker(time.Second)
defer t.Stop()
go func() {
srv := http.FileServer(http.Dir("./test"))
http.ListenAndServe(":8080", srv)
}()
for {
select {
case <-t.C:
appendToFile()
}
}
}
func appendToFile() {
f, err := os.OpenFile("./test/index.html", os.O_RDWR, 0644)
if err != nil {
panic(err)
}
defer f.Close()
// 这里假设文件以</body></html>结尾
f.Seek(-16, 2)
if _, err = f.WriteString("test test test\n"); err != nil {
panic(err)
}
if _, err = f.WriteString("</body></html>\n"); err != nil {
panic(err)
}
}
在index.html中,我最初放了一个空白文档:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body></html>
PS:最好先检查
评论