mirror of
https://github.com/gofiber/fiber.git
synced 2025-02-24 16:23:59 +00:00
Merge pull request #883 from r-52/r-favicon-cache-control
🔥add the option to set a custom Cache-Control value for a favicon response
This commit is contained in:
commit
748001b8d6
@ -18,18 +18,23 @@ type Config struct {
|
||||
//
|
||||
// Optional. Default: ""
|
||||
File string
|
||||
|
||||
// CacheControl defines how the Cache-Control header in the response should be set
|
||||
//
|
||||
// Optional. Default: "public, max-age=31536000"
|
||||
CacheControl string
|
||||
}
|
||||
|
||||
// ConfigDefault is the default config
|
||||
var ConfigDefault = Config{
|
||||
Next: nil,
|
||||
File: "",
|
||||
Next: nil,
|
||||
File: "",
|
||||
CacheControl: "public, max-age=31536000",
|
||||
}
|
||||
|
||||
const (
|
||||
hType = "image/x-icon"
|
||||
hAllow = "GET, HEAD, OPTIONS"
|
||||
hCache = "public, max-age=31536000"
|
||||
hZero = "0"
|
||||
)
|
||||
|
||||
@ -49,6 +54,9 @@ func New(config ...Config) fiber.Handler {
|
||||
if cfg.File == "" {
|
||||
cfg.File = ConfigDefault.File
|
||||
}
|
||||
if cfg.CacheControl == "" {
|
||||
cfg.CacheControl = ConfigDefault.CacheControl
|
||||
}
|
||||
}
|
||||
|
||||
// Load icon if provided
|
||||
@ -92,7 +100,7 @@ func New(config ...Config) fiber.Handler {
|
||||
if len(icon) > 0 {
|
||||
c.Set(fiber.HeaderContentLength, iconLen)
|
||||
c.Set(fiber.HeaderContentType, hType)
|
||||
c.Set(fiber.HeaderCacheControl, hCache)
|
||||
c.Set(fiber.HeaderCacheControl, cfg.CacheControl)
|
||||
return c.Status(fiber.StatusOK).Send(icon)
|
||||
}
|
||||
|
||||
|
@ -68,6 +68,22 @@ func Test_Middleware_Favicon_Found(t *testing.T) {
|
||||
utils.AssertEqual(t, nil, err, "app.Test(req)")
|
||||
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode, "Status code")
|
||||
utils.AssertEqual(t, "image/x-icon", resp.Header.Get(fiber.HeaderContentType))
|
||||
utils.AssertEqual(t, "public, max-age=31536000", resp.Header.Get(fiber.HeaderCacheControl), "CacheControl Control")
|
||||
}
|
||||
|
||||
// go test -run Test_Middleware_Favicon_CacheControl
|
||||
func Test_Middleware_Favicon_CacheControl(t *testing.T) {
|
||||
app := fiber.New()
|
||||
|
||||
app.Use(New(Config{
|
||||
CacheControl: "public, max-age=100",
|
||||
File: "../../.github/testdata/favicon.ico",
|
||||
}))
|
||||
resp, err := app.Test(httptest.NewRequest("GET", "/favicon.ico", nil))
|
||||
utils.AssertEqual(t, nil, err, "app.Test(req)")
|
||||
utils.AssertEqual(t, fiber.StatusOK, resp.StatusCode, "Status code")
|
||||
utils.AssertEqual(t, "image/x-icon", resp.Header.Get(fiber.HeaderContentType))
|
||||
utils.AssertEqual(t, "public, max-age=100", resp.Header.Get(fiber.HeaderCacheControl), "CacheControl Control")
|
||||
}
|
||||
|
||||
// go test -v -run=^$ -bench=Benchmark_Middleware_Favicon -benchmem -count=4
|
||||
|
Loading…
x
Reference in New Issue
Block a user