Back to Fiber

Favicon

docs/middleware/favicon.md

3.2.02.6 KB
Original Source

Favicon

Favicon middleware for Fiber that drops repeated /favicon.ico requests or serves a cached icon from memory. Mount it before your logger to suppress noisy requests and avoid disk reads.

It handles only GET, HEAD, and OPTIONS to the configured URL; other methods return 405 Method Not Allowed.

:::note This middleware only serves the default /favicon.ico (or a custom URL). For multiple icons, use the Static middleware. :::

Signatures

go
func New(config ...Config) fiber.Handler

Examples

Import the middleware package:

go
import (
    "github.com/gofiber/fiber/v3"
    "github.com/gofiber/fiber/v3/middleware/favicon"
)

Once your Fiber app is initialized, use the middleware like this:

go
// Initialize default config
app.Use(favicon.New())

// Or extend your config for customization
app.Use(favicon.New(favicon.Config{
    File: "./favicon.ico",
    URL: "/favicon.ico",
}))

Config

PropertyTypeDescriptionDefault
Nextfunc(fiber.Ctx) boolNext defines a function to skip this middleware when it returns true.nil
Data[]byteRaw data of the favicon file. This can be used instead of File.nil
FilestringFile holds the path to an actual favicon that will be cached.""
URLstringURL for favicon handler."/favicon.ico"
FileSystemfs.FSFileSystem is an optional alternate filesystem from which to load the favicon file (e.g. using os.DirFS or an embed.FS).nil
CacheControlstringCacheControl defines how the Cache-Control header in the response should be set."public, max-age=31536000"
MaxBytesint64MaxBytes limits the maximum size of the cached favicon asset.1048576

Default Config

go
var ConfigDefault = Config{
    Next:         nil,
    File:         "",
    URL:          fPath,
    CacheControl: "public, max-age=31536000",
    MaxBytes:     1024 * 1024,
}