This repository has been archived by the owner on May 10, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcache-control_test.go
119 lines (97 loc) · 2.46 KB
/
cache-control_test.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
package cachecontrol
import (
"bytes"
"io/ioutil"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/go-chi/chi"
"github.com/stretchr/testify/assert"
)
var fs = http.Dir(`./assets`)
func createMux(options ...Option) *chi.Mux {
rt := chi.NewRouter()
rt.Route("/assets/*", func(rt chi.Router) {
options = append(options, StripPrefix("/assets"))
rt.Use(CacheControl(fs, options...))
rt.Get("/*", http.StripPrefix("/assets", http.FileServer(fs)).ServeHTTP)
})
return rt
}
const goInternalETagHeader = "Etag" // it's case-insensitive; but why the change?
// etags gets calculated on first call
func TestETag1WarmUp(t *testing.T) {
assert := assert.New(t)
files := []string{
"/assets/js/app.js",
"/assets/vue/vue.min.js",
"/assets/axios/axios.min.js",
"/assets/bulma/css/bulma.rtl.css",
}
mux := createMux()
srv := httptest.NewServer(mux)
defer srv.Close()
for _, vf := range files {
var u bytes.Buffer
u.WriteString(string(srv.URL))
u.WriteString(vf)
// 1
res, err := http.Get(u.String())
assert.NoError(err)
if res != nil {
defer res.Body.Close()
}
}
WAIT_FOR_ETAG:
for _, vf := range files {
_, ok := kv.Get(vf)
if !ok {
time.Sleep(time.Millisecond * 100)
goto WAIT_FOR_ETAG
}
}
}
func TestETag1(t *testing.T) {
assert := assert.New(t)
files := []string{
"/assets/js/app.js",
"/assets/vue/vue.min.js",
"/assets/axios/axios.min.js",
"/assets/bulma/css/bulma.rtl.css",
}
mux := createMux()
srv := httptest.NewServer(mux)
defer srv.Close()
for _, vf := range files {
var u bytes.Buffer
u.WriteString(string(srv.URL))
u.WriteString(vf)
// 1
res, err := http.Get(u.String())
assert.NoError(err)
if res != nil {
defer res.Body.Close()
}
b, err := ioutil.ReadAll(res.Body)
assert.NoError(err)
assert.Equal("public, max-age=2419200", res.Header[cacheControlServer][0])
foundETag := res.Header[goInternalETagHeader][0]
assert.Equal(http.StatusOK, res.StatusCode)
// 2
req, err := http.NewRequest("GET", u.String(), nil)
assert.NoError(err)
req.Header.Set(etagHeaderClient, foundETag)
res, err = (&http.Client{}).Do(req)
assert.NoError(err)
if res != nil {
defer res.Body.Close()
}
b, err = ioutil.ReadAll(res.Body)
assert.NoError(err)
assert.Equal("public, max-age=2419200", res.Header[cacheControlServer][0])
assert.Equal(foundETag, res.Header[goInternalETagHeader][0])
assert.True(len(b) == 0)
assert.Equal(http.StatusNotModified, res.StatusCode)
}
}