mirror of
https://github.com/chai2010/advanced-go-programming-book.git
synced 2025-05-24 04:22:22 +00:00
更新服务脚本, 禁止本地文件缓存
This commit is contained in:
parent
0fc0bbe5aa
commit
9876071ce2
45
server.go
45
server.go
@ -19,6 +19,7 @@ import (
|
|||||||
var (
|
var (
|
||||||
flagRootDir = flag.String("dir", ".", "root dir")
|
flagRootDir = flag.String("dir", ".", "root dir")
|
||||||
flagHttpAddr = flag.String("http", ":8080", "HTTP service address")
|
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")
|
flagOpenBrowser = flag.Bool("openbrowser", true, "open browser automatically")
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -47,7 +48,11 @@ func main() {
|
|||||||
log.Printf("Hit CTRL-C to stop the server\n")
|
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
|
// waitServer waits some time for the http Server to start
|
||||||
@ -97,3 +102,41 @@ func startBrowser(url string) bool {
|
|||||||
cmd := exec.Command(args[0], append(args[1:], url)...)
|
cmd := exec.Command(args[0], append(args[1:], url)...)
|
||||||
return cmd.Start() == nil
|
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)
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user