【发布时间】:2021-11-15 07:54:59
【问题描述】:
我正在使用 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()
// 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)
}
}
这是预期的行为吗?
谢谢!
【问题讨论】:
-
您没有显示修改文件的代码。
-
@Marc 文件末尾只是一个简单的
WriteString。 -
你没有显示你是如何打电话给
AppendToFile()的。请参阅@sigkilled 的答案 - 因为该函数应该能够毫无问题地更新文件。
标签: go fileserver