Skip to content

Commit

Permalink
static: support setting "Cache-Control" (#143)
Browse files Browse the repository at this point in the history
Co-authored-by: Phil Harris <phil@harris-family.info>
Co-authored-by: Joe Chen <jc@unknwon.io>
  • Loading branch information
3 people committed Oct 19, 2022
1 parent 485f440 commit 9e2c44f
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
6 changes: 6 additions & 0 deletions static.go
Expand Up @@ -37,6 +37,9 @@ type StaticOptions struct {
// EnableLogging indicates whether to print "[Static]" log messages whenever a
// static file is served.
EnableLogging bool
// CacheControl is used to set the "Cache-Control" response header for every
// static file that is served. Default is not set.
CacheControl func() string
}

func generateETag(size int64, name string, modtime time.Time) string {
Expand Down Expand Up @@ -141,6 +144,9 @@ func Static(opts ...StaticOptions) Handler {
if opt.Expires != nil {
c.ResponseWriter().Header().Set("Expires", opt.Expires())
}
if opt.CacheControl != nil {
c.ResponseWriter().Header().Set("Cache-Control", opt.CacheControl())
}

if opt.SetETag {
etag := generateETag(fi.Size(), fi.Name(), fi.ModTime())
Expand Down
22 changes: 22 additions & 0 deletions static_test.go
Expand Up @@ -173,6 +173,28 @@ func TestStatic_Options(t *testing.T) {
assert.Equal(t, "2830", resp.Header().Get("Expires"))
})

t.Run("cache-control", func(t *testing.T) {
const cacheControl = "public, max-age=60"
f := NewWithLogger(&bytes.Buffer{})
f.Use(Static(
StaticOptions{
Directory: ".",
CacheControl: func() string {
return cacheControl
},
},
))

resp := httptest.NewRecorder()
req, err := http.NewRequest(http.MethodHead, "/.editorconfig", http.NoBody)
assert.Nil(t, err)

f.ServeHTTP(resp, req)

assert.Equal(t, http.StatusOK, resp.Code)
assert.Equal(t, cacheControl, resp.Header().Get("Cache-Control"))
})

t.Run("etag", func(t *testing.T) {
f := NewWithLogger(&bytes.Buffer{})
f.Use(Static(
Expand Down

0 comments on commit 9e2c44f

Please sign in to comment.