Go web服务器 – 不要使用时间戳缓存文件

huangapple go评论91阅读模式
英文:

Go webserver - don't cache files using timestamp

问题

我正在一个嵌入式系统上运行一个用Go语言编写的Web服务器。如果有人降级了固件版本,index.html的时间戳可能会倒退。如果index.html比之前的版本旧,服务器会发送一个HTTP 304响应(未修改),并提供缓存版本的文件。

Web服务器的代码使用了http.FileServer()和http.ListenAndServe()。

可以通过使用Posix命令touch修改index.html的时间戳来轻松重现这个问题:

touch -d"23:59" index.html

重新加载页面,然后

touch -d"23:58" index.html

这次重新加载将在index.html上返回一个304响应。

有没有办法防止基于时间戳的缓存?

英文:

I'm running a webserver written in go on an embedded system. The timestamp of index.html may go backwards if someone has downgraded the firmware version. If index.html is older than the previous version, the server sends a http 304 response (not modified), and serves a cached version of the file.

The webserver code is using http.FileServer() and http.ListenAndServe().

The problem can easily reproduced by modifying the timestamp of index.html using the Posix command touch

touch -d"23:59" index.html

reloading the page, then

touch -d"23:58" index.html

reloading this time will give a 304 response on index.html.

Is there a way to prevent timestamp based caching?

答案1

得分: 19

假设你的文件服务器代码类似于文档中的示例:

http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("/static")))))

你可以编写一个处理程序,设置适当的缓存头,以防止这种行为,通过删除 ETag 头并设置 Cache-Control: no-cache, private, max-age=0 来防止缓存(在本地和上游代理中):

var epoch = time.Unix(0, 0).Format(time.RFC1123)

var noCacheHeaders = map[string]string{
    "Expires":         epoch,
    "Cache-Control":   "no-cache, private, max-age=0",
    "Pragma":          "no-cache",
    "X-Accel-Expires": "0",
}

var etagHeaders = []string{
    "ETag",
    "If-Modified-Since",
    "If-Match",
    "If-None-Match",
    "If-Range",
    "If-Unmodified-Since",
}

func NoCache(h http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        // 删除可能已设置的任何 ETag 头
        for _, v := range etagHeaders {
            if r.Header.Get(v) != "" {
                r.Header.Del(v)
            }
        }

        // 设置我们的 NoCache 头
        for k, v := range noCacheHeaders {
            w.Header().Set(k, v)
        }

        h.ServeHTTP(w, r)
    }

    return http.HandlerFunc(fn)
}

使用方法如下:

http.Handle("/static/", NoCache(http.StripPrefix("/static/", http.FileServer(http.Dir("/static")))))

注意:我最初在 github.com/zenazn/goji/middleware 上编写了这个代码,所以你也可以直接导入那个包,但这只是一个简单的代码片段,我想展示一个完整的示例供后人参考!

英文:

Assuming your file server code is like the example in the docs:

http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("/static"))))

You can write a handler that sets the appropriate cache headers to prevent this behaviour by stripping ETag headers and setting Cache-Control: no-cache, private, max-age=0 to prevent caching (both locally and in upstream proxies):

var epoch = time.Unix(0, 0).Format(time.RFC1123)

var noCacheHeaders = map[string]string{
	"Expires":         epoch,
	"Cache-Control":   "no-cache, private, max-age=0",
	"Pragma":          "no-cache",
	"X-Accel-Expires": "0",
}

var etagHeaders = []string{
	"ETag",
	"If-Modified-Since",
	"If-Match",
	"If-None-Match",
	"If-Range",
	"If-Unmodified-Since",
}

func NoCache(h http.Handler) http.Handler {
    fn := func(w http.ResponseWriter, r *http.Request) {
        // Delete any ETag headers that may have been set
		for _, v := range etagHeaders {
			if r.Header.Get(v) != "" {
				r.Header.Del(v)
			}
		}

		// Set our NoCache headers
		for k, v := range noCacheHeaders {
			w.Header().Set(k, v)
		}

		h.ServeHTTP(w, r)
    }

    return http.HandlerFunc(fn)
}

Use it like so:

http.Handle("/static/", NoCache(http.StripPrefix("/static/", http.FileServer(http.Dir("/static")))))

Note: I originally wrote this at github.com/zenazn/goji/middleware, so you can also just import that, but it's a simple piece of code to write and I wanted to show a full example for posterity!

huangapple
  • 本文由 发表于 2015年11月24日 04:44:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/33880343.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定