|
| 1 | +package cache |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "net/http/httptest" |
| 6 | + "testing" |
| 7 | + "time" |
| 8 | + |
| 9 | + "github.com/stretchr/testify/require" |
| 10 | + "github.com/yaitoo/xun" |
| 11 | +) |
| 12 | + |
| 13 | +func TestCache(t *testing.T) { |
| 14 | + mux := http.NewServeMux() |
| 15 | + srv := httptest.NewServer(mux) |
| 16 | + defer srv.Close() |
| 17 | + |
| 18 | + app := xun.New(xun.WithMux(mux)) |
| 19 | + |
| 20 | + app.Use(New(Match("/starts", "", 1*time.Second), |
| 21 | + Match("", "banner.jpg", 2*time.Second), |
| 22 | + Match("/assets", "app.js", 3*time.Second))) |
| 23 | + |
| 24 | + app.Get("/starts", func(c *xun.Context) error { |
| 25 | + return c.View(nil) |
| 26 | + }) |
| 27 | + |
| 28 | + app.Get("/banner.jpg", func(c *xun.Context) error { |
| 29 | + return c.View(nil) |
| 30 | + }) |
| 31 | + |
| 32 | + app.Get("/assets/app.js", func(c *xun.Context) error { |
| 33 | + return c.View(nil) |
| 34 | + }) |
| 35 | + |
| 36 | + app.Get("/assets/app.css", func(c *xun.Context) error { |
| 37 | + return c.View(nil) |
| 38 | + }) |
| 39 | + |
| 40 | + app.Get("/logo", func(c *xun.Context) error { |
| 41 | + return c.View(nil) |
| 42 | + }) |
| 43 | + |
| 44 | + resp, err := http.Get(srv.URL + "/starts") |
| 45 | + require.NoError(t, err) |
| 46 | + require.Equal(t, http.StatusOK, resp.StatusCode) |
| 47 | + |
| 48 | + cacheControl := resp.Header.Get("Cache-Control") |
| 49 | + require.Equal(t, "public, max-age=1", cacheControl) |
| 50 | + resp.Body.Close() |
| 51 | + |
| 52 | + resp, err = http.Get(srv.URL + "/banner.jpg") |
| 53 | + require.NoError(t, err) |
| 54 | + require.Equal(t, http.StatusOK, resp.StatusCode) |
| 55 | + cacheControl = resp.Header.Get("Cache-Control") |
| 56 | + require.Equal(t, "public, max-age=2", cacheControl) |
| 57 | + resp.Body.Close() |
| 58 | + |
| 59 | + resp, err = http.Get(srv.URL + "/assets/app.js") |
| 60 | + require.NoError(t, err) |
| 61 | + require.Equal(t, http.StatusOK, resp.StatusCode) |
| 62 | + cacheControl = resp.Header.Get("Cache-Control") |
| 63 | + require.Equal(t, "public, max-age=3", cacheControl) |
| 64 | + resp.Body.Close() |
| 65 | + |
| 66 | + resp, err = http.Get(srv.URL + "/assets/app.css") |
| 67 | + require.NoError(t, err) |
| 68 | + require.Equal(t, http.StatusOK, resp.StatusCode) |
| 69 | + cacheControl = resp.Header.Get("Cache-Control") |
| 70 | + require.Empty(t, cacheControl) |
| 71 | + resp.Body.Close() |
| 72 | + |
| 73 | + resp, err = http.Get(srv.URL + "/logo") |
| 74 | + require.NoError(t, err) |
| 75 | + require.Equal(t, http.StatusOK, resp.StatusCode) |
| 76 | + cacheControl = resp.Header.Get("Cache-Control") |
| 77 | + require.Empty(t, cacheControl) |
| 78 | + resp.Body.Close() |
| 79 | +} |
0 commit comments