-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathnocache.go
87 lines (76 loc) · 2.12 KB
/
nocache.go
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package middleware
// Ported from Goji's middleware, source:
// https://github.com/zenazn/goji/tree/master/web/middleware
import (
"time"
"github.com/labstack/echo"
emw "github.com/labstack/echo/middleware"
)
type (
// NoCacheConfig defines the config for nocache middleware.
NoCacheConfig struct {
// Skipper defines a function to skip middleware.
Skipper emw.Skipper
}
)
var (
// Unix epoch time
epoch = time.Unix(0, 0).Format(time.RFC1123)
// Taken from https://github.com/mytrile/nocache
noCacheHeaders = map[string]string{
"Expires": epoch,
"Cache-Control": "no-cache, private, max-age=0",
"Pragma": "no-cache",
"X-Accel-Expires": "0",
}
etagHeaders = []string{
"ETag",
"If-Modified-Since",
"If-Match",
"If-None-Match",
"If-Range",
"If-Unmodified-Since",
}
// DefaultNoCacheConfig is the default nocache middleware config.
DefaultNoCacheConfig = NoCacheConfig{
Skipper: emw.DefaultSkipper,
}
)
// NoCache is a simple piece of middleware that sets a number of HTTP headers to prevent
// a router (or subrouter) from being cached by an upstream proxy and/or client.
//
// As per http://wiki.nginx.org/HttpProxyModule - NoCache sets:
// Expires: Thu, 01 Jan 1970 00:00:00 UTC
// Cache-Control: no-cache, private, max-age=0
// X-Accel-Expires: 0
// Pragma: no-cache (for HTTP/1.0 proxies/clients)
func NoCache() echo.MiddlewareFunc {
return NoCacheWithConfig(DefaultNoCacheConfig)
}
// NoCacheWithConfig returns a nocache middleware with config.
func NoCacheWithConfig(config NoCacheConfig) echo.MiddlewareFunc {
// Defaults
if config.Skipper == nil {
config.Skipper = DefaultNoCacheConfig.Skipper
}
return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) (err error) {
if config.Skipper(c) {
return next(c)
}
req := c.Request()
// Delete any ETag headers that may have been set
for _, v := range etagHeaders {
if req.Header.Get(v) != "" {
req.Header.Del(v)
}
}
// Set our NoCache headers
res := c.Response()
for k, v := range noCacheHeaders {
res.Header().Set(k, v)
}
return next(c)
}
}
}