【问题标题】:Static files don't update while serving them from Go从 Go 提供静态文件时不会更新它们
【发布时间】:2018-05-02 21:29:23
【问题描述】:

我开始学习 Go,遇到了静态文件句柄的问题。 有这个:

func main() {
    fs := http.FileServer(http.Dir("public"))
    http.Handle("/", fs)
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}

文件夹结构:

main.go

public
    - index.html

当我运行go run main.go 之后,更改index.html 中的某些内容,然后再次运行go run main.go,浏览器中的视图没有改变。所以我用谷歌搜索了一下,认为它们在 go 编译的二进制文件中,并且由于 main.go 没有更改,go 不会重新编译它。所以我运行go run -a main.go 强制重新编译,但它没有帮助。

我清除了 chrome 中的历史记录和缓存,甚至尝试了另一个浏览器和curl,但仍然看到旧的静态文件,而在文件系统中只有新版本。所以这与浏览器无关。实际上,当我在浏览器中看到新版本的静态文件时,将public 重命名为public2(例如)并在main.go 中进行相同的更改。

这不是 Go 的问题,因为这个示例在其他用户中运行正常。所以这与我的系统有关。我在 Vagrant 的默认 Ubuntu 16.04 上运行该代码。

流浪文件:

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  config.vm.network "forwarded_port", guest: 8080, host: 8080
  config.vm.network "forwarded_port", guest: 5432, host: 5432
end

请求头:

2017/11/19 18:25:45 request.RequestURI: /
2017/11/19 18:25:45 request.RemoteAddr: 10.0.2.2:50584
2017/11/19 18:25:45 request.TLS: <nil>
2017/11/19 18:25:45 Request Headers:
2017/11/19 18:25:45 Accept : [text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8]
2017/11/19 18:25:45 Accept-Encoding : [gzip, deflate, br]
2017/11/19 18:25:45 Accept-Language : [en-US,en;q=0.9,ru;q=0.8]
2017/11/19 18:25:45 Cache-Control : [max-age=0]
2017/11/19 18:25:45 Connection : [keep-alive]
2017/11/19 18:25:45 If-Modified-Since : [Sun, 19 Nov 2017 16:24:53 GMT]
2017/11/19 18:25:45 Upgrade-Insecure-Requests : [1]
2017/11/19 18:25:45 User-Agent : [Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.94 Safari/537.36]

响应头:

HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Length: 2010
Content-Type: text/html; charset=utf-8
Last-Modified: Sun, 19 Nov 2017 16:24:53 GMT
Date: Sun, 19 Nov 2017 18:25:27 GMT

结论:我在另一个虚拟机上运行它,一切正常,所以虚拟机有问题,但现在我不知道是什么问题。

【问题讨论】:

  • 您不需要重新运行或重新编译 go 应用程序,除非浏览器中正在进行一些缓存,否则您应该会在刷新页面后看到对 index.html 的更改。
  • 尝试 curl 看看 index.html 是否有变化。我刚刚在我的机器上重新创建了你的简单示例,它可以在 firefox 上正常工作。
  • 你做错了什么,但 Go 的 http.FileServer 的工作方式没有问题。 imgur.com/a/HnuD7
  • 也可以试试 play.golang.org/p/Z1AZ_EthiY 这样的东西,看看 Go 是每次都收到请求,还是第一次收到。
  • 确保文件在虚拟机中正在被更改,这可能存在同步/缓存问题。听起来像是在缓存它……(绝对与 golang 或您的代码无关)

标签: linux ubuntu go vagrant ubuntu-16.04


【解决方案1】:

go run 本质上是builds a binary, copies it to a tmp folder and then executes it(不仅如此,但对于我们的目的来说已经足够了)。

我通过复制您提供的 main.go 来测试您的示例,然后执行以下操作:

go run main.go
# in a new tab
curl localhost:8080
#  ==> "Hello world"
echo "2" >> public/index.html
curl localhost:8080
#  ==> "Hello world\n2"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-06-27
    • 2014-11-24
    • 2015-06-09
    • 2023-03-13
    • 2017-08-04
    • 1970-01-01
    • 2012-06-15
    • 2013-05-28
    相关资源
    最近更新 更多