go - 利用静态文件的浏览器缓存

标签 go browser-cache static-files

我不确定,在 Golang 中,我们如何利用浏览器缓存来仅针对 CSSjs 而不是 HTML 模板文件.

在 Apache 中使用 .htaccess,它曾经很容易,但我在 golang 中没有看到任何这样的东西

我想知道任何可以缓存静态文件(如 cssjs)的 hack 或方法

不使用 cloudflare - 我的应用不适用于 cloudflare。

最佳答案

浏览器缓存由服务器发送的 header 控制。这样它不依赖于特定安装的软件。

您需要发送 header EtagCache-Control。像这样

func Handler(w http.ResponseWriter, r *http.Request) {
    e := "SomeKey describing content - eg checksum"
    w.Header().Set("Etag", e)
    w.Header().Set("Cache-Control", "max-age=2592000") // 30 days

    if match := r.Header.Get("If-None-Match"); match != "" {
        if strings.Contains(match, e) {
            w.WriteHeader(http.StatusNotModified)
            return
        }
    }
    ...
}

有用的链接:

关于go - 利用静态文件的浏览器缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47806498/

相关文章:

go - NATS JetStream : Is it possible to explicitly ask from JetStream to (re)send the last few messages it received in subject foo. *?

webview - Electron WebView Back Button 清除表单

css - 部署到 Azure : Fixing the Mime Type sends an empty css file to the server

java - 如何在 Glassfish 服务器中设置 HTTP header

WebSphere 在静态文件上返回 503 错误(Servlet 暂时无法提供服务)

python - send_static_file 未从蓝图中根目录的静态文件夹中获取

go - 为什么下面的 Golang 代码没有运行?

json - 解码 JSON 响应时遇到问题

go - 如何使用go模板连接变量和字符串

javascript - 如何在 Durandal 中禁用缓存 View