dtup3446 2018-04-26 16:17
浏览 77
已采纳

如何强制客户端重新下载我的网站?

I'm writing a web server in Go, using the github.com/gorilla/mux router. My program checks if the client has a cookie called "name" and based on that, serves one of two files. Here's the handler function:

func indexHandler(w http.ResponseWriter, r *http.Request) {
    if name, err := r.Cookie("name"); err == nil && name.Value != "" {
        http.ServeFile(w, r, "static/messager.html")
    } else {
        http.ServeFile(w, r, "static/index.html")
    }
}

Testing this on Firefox, I load my website, which correctly serves index.html since I don't have the cookie set. In index.html, there's a form which sets the cookie and reloads the page when submitted.

This is the problem. The page reloads, but due to caching index.html is still displayed in the browser (despite the server actually serving messager.html - I added a debug log.) I can reload the page manually as many times as I want, making no difference, but once I do a hard refresh it works and displays messager.html.

This only seems to happen on Firefox (I've tested Safari, Edge, and Firefox). Any suggestions on how I can force the browser to display the correct page?

  • 写回答

1条回答 默认 最新

  • dongxidui1227 2018-04-26 16:31
    关注

    http.ServeFile sends a Last-Modified header (with the value set to the file's mtime), and no Cache-Control header. In this case browsers will implement heuristics to determine if and how long the response may be cached.

    To instruct clients not to cache a response, send the Cache-Control header yourself:

    func indexHandler(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Cache-Control", "max-age=0")
    
        if name, err := r.Cookie("name"); err == nil && name.Value != "" {
            http.ServeFile(w, r, "static/messager.html")
        } else {
            http.ServeFile(w, r, "static/index.html")
        }
    }
    

    Caution: the Cache-Control header is really unintuitive. For instance, there is a value called "no-cache", but that doesn't actually cause clients not to cache a response. Read the docs carefully to get your desired affect.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题