【问题标题】:GoLang: Update file that is served by FileServerGoLang:更新由 FileServer 提供的文件
【发布时间】: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


【解决方案1】:

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()
    // This assumes that the file ends with </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:最好先检查偏移量,然后将字符串写入该位置。

【讨论】:

  • 感谢您花时间重现 OP 代码。我懒得自己处理浏览器的超时,所以整合了整个东西以获得更简单的测试体验play.golang.org/p/cgzuP2r1Qlx
  • 谢谢!事实证明,问题与此完全无关。 (我对 Go 比较陌生。)非常感谢您的帮助!
  • 不客气。
猜你喜欢
  • 2015-04-11
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 2020-06-30
  • 2018-02-07
  • 2019-02-10
  • 2019-01-09
  • 1970-01-01
相关资源
最近更新 更多