diff --git a/docs/api/middleware/favicon.md b/docs/api/middleware/favicon.md index 3fea8b12..b1a9b0df 100644 --- a/docs/api/middleware/favicon.md +++ b/docs/api/middleware/favicon.md @@ -45,6 +45,7 @@ app.Use(favicon.New(favicon.Config{ | Property | Type | Description | Default | |:-------------|:------------------------|:---------------------------------------------------------------------------------|:---------------------------| | Next | `func(*fiber.Ctx) bool` | Next defines a function to skip this middleware when returned true. | `nil` | +| Data | `[]byte` | Raw data of the favicon file. This can be used instead of `File`. | `nil` | | File | `string` | File holds the path to an actual favicon that will be cached. | "" | | URL | `string` | URL for favicon handler. | "/favicon.ico" | | FileSystem | `http.FileSystem` | FileSystem is an optional alternate filesystem to search for the favicon in. | `nil` | diff --git a/middleware/favicon/favicon.go b/middleware/favicon/favicon.go index 84572b6d..45752891 100644 --- a/middleware/favicon/favicon.go +++ b/middleware/favicon/favicon.go @@ -16,6 +16,11 @@ type Config struct { // Optional. Default: nil Next func(c *fiber.Ctx) bool + // Raw data of the favicon file + // + // Optional. Default: nil + Data []byte `json:"-"` + // File holds the path to an actual favicon that will be cached // // Optional. Default: "" @@ -83,7 +88,11 @@ func New(config ...Config) fiber.Handler { icon []byte iconLen string ) - if cfg.File != "" { + if cfg.Data != nil { + // use the provided favicon data + icon = cfg.Data + iconLen = strconv.Itoa(len(cfg.Data)) + } else if cfg.File != "" { // read from configured filesystem if present if cfg.FileSystem != nil { f, err := cfg.FileSystem.Open(cfg.File) diff --git a/middleware/favicon/favicon_test.go b/middleware/favicon/favicon_test.go index 9e628cf7..6c8c9db7 100644 --- a/middleware/favicon/favicon_test.go +++ b/middleware/favicon/favicon_test.go @@ -99,6 +99,30 @@ func Test_Custom_Favicon_Url(t *testing.T) { utils.AssertEqual(t, "image/x-icon", resp.Header.Get(fiber.HeaderContentType)) } +// go test -run Test_Custom_Favicon_Data +func Test_Custom_Favicon_Data(t *testing.T) { + data, err := os.ReadFile("../../.github/testdata/favicon.ico") + if err != nil { + t.Fatal(err) + } + + app := fiber.New() + + app.Use(New(Config{ + Data: data, + })) + + app.Get("/", func(c *fiber.Ctx) error { + return nil + }) + + resp, err := app.Test(httptest.NewRequest(fiber.MethodGet, "/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=31536000", resp.Header.Get(fiber.HeaderCacheControl), "CacheControl Control") +} + // mockFS wraps local filesystem for the purposes of // Test_Middleware_Favicon_FileSystem located below // TODO use os.Dir if fiber upgrades to 1.16