咕噜咕噜:更新文件服务器提供的文件

我正在使用文件服务器为目录提供服务,如下所示:


go func() {

  fs := http.FileServer(http.Dir("./view"))

  err := http.ListenAndServe(":8000", fs)

  if err != nil {

    log.Fatal("ListenAndServe: ", err)

  }

}()

在目录中,我有一个文件,我正在尝试在提供目录时更新该文件。我观察到追加命令仅在我停止提供目录后阻止并更新文件。viewindex.htmlview


以下是修改该文件的代码:


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)

  }

}

这是预期的行为吗?


谢谢!


回首忆惘然
浏览 74回答 1
1回答

慕姐8265434

网易娱乐.文件服务器函数只返回一个处理程序。因此,它不会阻塞文件系统。此处的问题可能与文件的偏移量有关。我已经在我的机器中尝试过,它工作没有任何问题。我已经修改了你的代码;package mainimport (&nbsp; &nbsp; "net/http"&nbsp; &nbsp; "os"&nbsp; &nbsp; "time")func main() {&nbsp; &nbsp; t := time.NewTicker(time.Second)&nbsp; &nbsp; defer t.Stop()&nbsp; &nbsp; go func() {&nbsp; &nbsp; &nbsp; &nbsp; srv := http.FileServer(http.Dir("./test"))&nbsp; &nbsp; &nbsp; &nbsp; http.ListenAndServe(":8080", srv)&nbsp; &nbsp; }()&nbsp; &nbsp; for {&nbsp; &nbsp; &nbsp; &nbsp; select {&nbsp; &nbsp; &nbsp; &nbsp; case <-t.C:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; appendToFile()&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}func appendToFile() {&nbsp; &nbsp; f, err := os.OpenFile("./test/index.html", os.O_RDWR, 0644)&nbsp; &nbsp; if err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; defer f.Close()&nbsp; &nbsp; // This assumes that the file ends with </body></html>&nbsp; &nbsp; f.Seek(-16, 2)&nbsp; &nbsp; if _, err = f.WriteString("test test test\n"); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }&nbsp; &nbsp; if _, err = f.WriteString("</body></html>\n"); err != nil {&nbsp; &nbsp; &nbsp; &nbsp; panic(err)&nbsp; &nbsp; }}在索引中.html我最初放置空白文档,<!DOCTYPE html><html><head>&nbsp; &nbsp; <meta charset="UTF-8">&nbsp; &nbsp; <meta http-equiv="X-UA-Compatible" content="IE=edge">&nbsp; &nbsp; <meta name="viewport" content="width=device-width, initial-scale=1.0">&nbsp; &nbsp; <title>Document</title></head><body></body></html>PS:最好先检查偏移量,然后将字符串写入该位置。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go