首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >GoLang: FileServer提供的更新文件

GoLang: FileServer提供的更新文件
EN

Stack Overflow用户
提问于 2021-09-21 18:56:28
回答 1查看 360关注 0票数 0

我使用FileServer提供目录,如下所示:

代码语言:javascript
复制
go func() {
  fs := http.FileServer(http.Dir("./view"))
  err := http.ListenAndServe(":8000", fs)
  if err != nil {
    log.Fatal("ListenAndServe: ", err)
  }
}()

view目录中,我有一个index.html文件,在为view目录提供服务时,我试图更新该文件。我观察到附加命令阻塞并只在停止服务目录后才更新文件。

下面是修改文件的代码:

代码语言:javascript
复制
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)
  }
}

这是预期的行为吗?

谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-09-21 20:24:11

http.FileServer函数只返回一个处理程序。因此,它没有阻塞文件系统。这里的问题可能与文件的偏移量有关。我试过在我的机器上工作,没有任何问题。

我已经修改了你的代码

代码语言:javascript
复制
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中,我最初放置空白文档,

代码语言:javascript
复制
<!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:最好先检查偏移量,然后把字符串写到那个位置。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69274214

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档