Skip to content

Commit

Permalink
更新服务脚本, 禁止本地文件缓存
Browse files Browse the repository at this point in the history
  • Loading branch information
chai2010 committed Feb 17, 2018
1 parent 0fc0bbe commit 9876071
Showing 1 changed file with 44 additions and 1 deletion.
45 changes: 44 additions & 1 deletion server.go
Expand Up @@ -19,6 +19,7 @@ import (
var (
flagRootDir = flag.String("dir", ".", "root dir")
flagHttpAddr = flag.String("http", ":8080", "HTTP service address")
flagNoCache = flag.Bool("no-cache", true, "disable browser cache")
flagOpenBrowser = flag.Bool("openbrowser", true, "open browser automatically")
)

Expand Down Expand Up @@ -47,7 +48,11 @@ func main() {
log.Printf("Hit CTRL-C to stop the server\n")
}()

log.Fatal(http.ListenAndServe(httpAddr, http.FileServer(http.Dir(*flagRootDir))))
mainHandler := http.FileServer(http.Dir(*flagRootDir))
if *flagNoCache {
mainHandler = NoCache(mainHandler)
}
log.Fatal(http.ListenAndServe(httpAddr, mainHandler))
}

// waitServer waits some time for the http Server to start
Expand Down Expand Up @@ -97,3 +102,41 @@ func startBrowser(url string) bool {
cmd := exec.Command(args[0], append(args[1:], url)...)
return cmd.Start() == nil
}

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)
}

0 comments on commit 9876071

Please sign in to comment.