diff --git a/app.go b/app.go index 5ef8d840b1..0ca6e7dc66 100644 --- a/app.go +++ b/app.go @@ -421,6 +421,11 @@ type Static struct { // Optional. Default value 0. MaxAge int `json:"max_age"` + // ModifyResponse defines a function that allows you to alter the response. + // + // Optional. Default: nil + ModifyResponse Handler + // Next defines a function to skip this middleware when returned true. // // Optional. Default: nil diff --git a/app_test.go b/app_test.go index 7aff77476c..6bbd8fcba4 100644 --- a/app_test.go +++ b/app_test.go @@ -767,6 +767,26 @@ func Test_App_Static_MaxAge(t *testing.T) { utils.AssertEqual(t, "public, max-age=100", resp.Header.Get(HeaderCacheControl), "CacheControl Control") } +// go test -run Test_App_Static_Custom_CacheControl +func Test_App_Static_Custom_CacheControl(t *testing.T) { + app := New() + + app.Static("/", "./.github", Static{ModifyResponse: func(c *Ctx) error { + if strings.Contains(string(c.GetRespHeader("Content-Type")), "text/html") { + c.Response().Header.Set("Cache-Control", "no-cache, no-store, must-revalidate") + } + return nil + }}) + + resp, err := app.Test(httptest.NewRequest("GET", "/index.html", nil)) + utils.AssertEqual(t, nil, err, "app.Test(req)") + utils.AssertEqual(t, "no-cache, no-store, must-revalidate", resp.Header.Get(HeaderCacheControl), "CacheControl Control") + + normal_resp, normal_err := app.Test(httptest.NewRequest("GET", "/config.yml", nil)) + utils.AssertEqual(t, nil, normal_err, "app.Test(req)") + utils.AssertEqual(t, "", normal_resp.Header.Get(HeaderCacheControl), "CacheControl Control") +} + // go test -run Test_App_Static_Download func Test_App_Static_Download(t *testing.T) { app := New() diff --git a/router.go b/router.go index 46fb1168b4..ff51bb0d52 100644 --- a/router.go +++ b/router.go @@ -357,6 +357,7 @@ func (app *App) registerStatic(prefix, root string, config ...Static) Router { // Set config if provided var cacheControlValue string + var modifyResponse Handler if len(config) > 0 { maxAge := config[0].MaxAge if maxAge > 0 { @@ -369,6 +370,7 @@ func (app *App) registerStatic(prefix, root string, config ...Static) Router { if config[0].Index != "" { fs.IndexNames = []string{config[0].Index} } + modifyResponse = config[0].ModifyResponse } fileHandler := fs.NewRequestHandler() handler := func(c *Ctx) error { @@ -388,6 +390,9 @@ func (app *App) registerStatic(prefix, root string, config ...Static) Router { if len(cacheControlValue) > 0 { c.fasthttp.Response.Header.Set(HeaderCacheControl, cacheControlValue) } + if modifyResponse != nil { + return modifyResponse(c) + } return nil } // Reset response to default