在开发阶段,不需要静态文件缓存,特别是 CSS 文件,这里介绍通过中间件方式设置不用缓存的方法。
首先要删掉 etag
相关的 Headers 内容
1
2
3
4
5
6
"ETag"
"If-Modified-Since"
"If-Match"
"If-None-Match"
"If-Range"
"If-Unmodified-Since"
然后添加跟缓存相关的 Header 内容
1
2
3
4
"Expires": time,
"Cache-Control": "no-cache, private, max-age=0",
"Pragma": "no-cache",
"X-Accel-Expires": "0",
放在一起就是这样:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package mdw
import (
"github.com/valyala/fasthttp"
"time"
)
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 RspNoCache(next fasthttp.RequestHandler) fasthttp.RequestHandler {
return func(ctx *fasthttp.RequestCtx) {
// Delete any ETag headers that may have been set
for _, v := range etagHeaders {
if string(ctx.Request.Header.Peek(v)) != "" {
ctx.Request.Header.Del(v)
}
}
// Set our NoCache headers
for k, v := range noCacheHeaders {
ctx.Response.Header.Set(k, v)
}
next(ctx)
}
}
最后在 Handle 里引用中间件
1
2
3
4
5
mux := router.New()
srv := &fasthttp.Server{
Handler: mdw.RspNoCache(mux.Handler),
}
在标准的 net/http 里也可以使用这种方法做一个中间件。
There are 1 Comments to "Fasthttp 取消页面、静态文件缓存的方法"
如果只修改 CSS ,可在 CSS 文件后面加入时间戳参数,每次请求都能动态载入。