Add custom data property to favicon middleware config (#2579)

* Add custom data property to favicon middleware

* Update favicon middleware docs

* Fix formatting
pull/2584/head
Jacob 2023-08-17 08:04:53 -05:00 committed by GitHub
parent bd9c3fc239
commit 892b23bd46
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 35 additions and 1 deletions

View File

@ -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` |

View File

@ -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)

View File

@ -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