📝 docs: remove README.mds from middleware dirs

pull/2357/head
Muhammed Efe Çetin 2023-03-06 16:42:35 +03:00
parent 2e7e879d6f
commit 15e9235383
No known key found for this signature in database
GPG Key ID: 0AA4D45CBAA86F73
24 changed files with 2 additions and 2798 deletions

View File

@ -45,7 +45,7 @@ app.Use(limiter.New(limiter.Config{
LimitReached: func(c *fiber.Ctx) error {
return c.SendFile("./toofast.html")
},
Storage: myCustomStorage{}
Storage: myCustomStorage{},
}))
```
@ -59,7 +59,7 @@ A example of such configuration is:
app.Use(limiter.New(limiter.Config{
Max: 20,
Expiration: 30 * time.Second,
LimiterMiddleware: limiter.SlidingWindow{}
LimiterMiddleware: limiter.SlidingWindow{},
}))
```

View File

@ -1,130 +0,0 @@
# Basic Authentication Middleware
Basic Authentication middleware for [Fiber](https://github.com/gofiber/fiber) that provides an HTTP basic authentication. It calls the next handler for valid credentials and [401 Unauthorized](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401) or a custom response for missing or invalid credentials.
## Table of Contents
- [Basic Authentication Middleware](#basic-authentication-middleware)
- [Table of Contents](#table-of-contents)
- [Signatures](#signatures)
- [Examples](#examples)
- [Custom Config](#custom-config)
- [Config](#config)
- [Default Config](#default-config)
## Signatures
```go
func New(config Config) fiber.Handler
```
## Examples
First import the middleware from Fiber,
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/basicauth"
)
```
Then create a Fiber app with `app := fiber.New()`.
### Custom Config
```go
// Provide a minimal config
app.Use(basicauth.New(basicauth.Config{
Users: map[string]string{
"john": "doe",
"admin": "123456",
},
}))
// Or extend your config for customization
app.Use(basicauth.New(basicauth.Config{
Users: map[string]string{
"john": "doe",
"admin": "123456",
},
Realm: "Forbidden",
Authorizer: func(user, pass string) bool {
if user == "john" && pass == "doe" {
return true
}
if user == "admin" && pass == "123456" {
return true
}
return false
},
Unauthorized: func(c *fiber.Ctx) error {
return c.SendFile("./unauthorized.html")
},
ContextUsername: "_user",
ContextPassword: "_pass",
}))
```
## Config
```go
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// Users defines the allowed credentials
//
// Required. Default: map[string]string{}
Users map[string]string
// Realm is a string to define realm attribute of BasicAuth.
// the realm identifies the system to authenticate against
// and can be used by clients to save credentials
//
// Optional. Default: "Restricted".
Realm string
// Authorizer defines a function you can pass
// to check the credentials however you want.
// It will be called with a username and password
// and is expected to return true or false to indicate
// that the credentials were approved or not.
//
// Optional. Default: nil.
Authorizer func(string, string) bool
// Unauthorized defines the response body for unauthorized responses.
// By default it will return with a 401 Unauthorized and the correct WWW-Auth header
//
// Optional. Default: nil
Unauthorized fiber.Handler
// ContextUser is the key to store the username in Locals
//
// Optional. Default: "username"
ContextUsername string
// ContextPass is the key to store the password in Locals
//
// Optional. Default: "password"
ContextPassword string
}
```
## Default Config
```go
var ConfigDefault = Config{
Next: nil,
Users: map[string]string{},
Realm: "Restricted",
Authorizer: nil,
Unauthorized: nil,
ContextUsername: "username",
ContextPassword: "password",
}
```

View File

@ -1,159 +0,0 @@
# Cache Middleware
Cache middleware for [Fiber](https://github.com/gofiber/fiber) designed to intercept responses and cache them. This middleware will cache the `Body`, `Content-Type` and `StatusCode` using the `c.Path()` (or a string returned by the Key function) as unique identifier. Special thanks to [@codemicro](https://github.com/codemicro/fiber-cache) for creating this middleware for Fiber core!
Request Directives<br>
`Cache-Control: no-cache` will return the up-to-date response but still caches it. You will always get a `miss` cache status.<br>
`Cache-Control: no-store` will refrain from caching. You will always get the up-to-date response.
## Table of Contents
- [Cache Middleware](#cache-middleware)
- [Table of Contents](#table-of-contents)
- [Signatures](#signatures)
- [Examples](#examples)
- [Default Config](#default-config)
- [Custom Config](#custom-config)
- [Custom Cache Key Or Expiration](#custom-cache-key-or-expiration)
- [Config](#config)
- [Default Config](#default-config-1)
## Signatures
```go
func New(config ...Config) fiber.Handler
```
## Examples
First import the middleware from Fiber,
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cache"
)
```
Then create a Fiber app with `app := fiber.New()`.
### Default Config
```go
app.Use(cache.New())
```
### Custom Config
```go
app.Use(cache.New(cache.Config{
Next: func(c *fiber.Ctx) bool {
return c.Query("refresh") == "true"
},
Expiration: 30 * time.Minute,
CacheControl: true,
}))
```
### Custom Cache Key Or Expiration
```go
app.Use(New(Config{
ExpirationGenerator: func(c *fiber.Ctx, cfg *Config) time.Duration {
newCacheTime, _ := strconv.Atoi(c.GetRespHeader("Cache-Time", "600"))
return time.Second * time.Duration(newCacheTime)
},
KeyGenerator: func(c *fiber.Ctx) string {
return utils.CopyString(c.Path())
}
}))
app.Get("/", func(c *fiber.Ctx) error {
c.Response().Header.Add("Cache-Time", "6000")
return c.SendString("hi")
})
```
### Config
```go
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// Expiration is the time that an cached response will live
//
// Optional. Default: 1 * time.Minute
Expiration time.Duration
// CacheHeader header on response header, indicate cache status, with the following possible return value
//
// hit, miss, unreachable
//
// Optional. Default: X-Cache
CacheHeader string
// CacheControl enables client side caching if set to true
//
// Optional. Default: false
CacheControl bool
// Key allows you to generate custom keys, by default c.Path() is used
//
// Default: func(c *fiber.Ctx) string {
// return utils.CopyString(c.Path())
// }
KeyGenerator func(*fiber.Ctx) string
// allows you to generate custom Expiration Key By Key, default is Expiration (Optional)
//
// Default: nil
ExpirationGenerator func(*fiber.Ctx, *Config) time.Duration
// Store is used to store the state of the middleware
//
// Default: an in memory store for this process only
Storage fiber.Storage
// allows you to store additional headers generated by next middlewares & handler
//
// Default: false
StoreResponseHeaders bool
// Max number of bytes of response bodies simultaneously stored in cache. When limit is reached,
// entries with the nearest expiration are deleted to make room for new.
// 0 means no limit
//
// Default: 0
MaxBytes uint
// You can specify HTTP methods to cache.
// The middleware just caches the routes of its methods in this slice.
//
// Default: []string{fiber.MethodGet, fiber.MethodHead}
Methods []string
}
```
### Default Config
```go
// ConfigDefault is the default config
var ConfigDefault = Config{
Next: nil,
Expiration: 1 * time.Minute,
CacheHeader: "X-Cache",
CacheControl: false,
KeyGenerator: func(c *fiber.Ctx) string {
return utils.CopyString(c.Path())
},
ExpirationGenerator: nil,
StoreResponseHeaders: false,
Storage: nil,
MaxBytes: 0,
Methods: []string{fiber.MethodGet, fiber.MethodHead},
}
```

View File

@ -1,96 +0,0 @@
# Compress Middleware
Compression middleware for [Fiber](https://github.com/gofiber/fiber) that will compress the response using `gzip`, `deflate` and `brotli` compression depending on the [Accept-Encoding](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding) header.
- [Compress Middleware](#compress-middleware)
- [Signatures](#signatures)
- [Examples](#examples)
- [Default Config](#default-config)
- [Custom Config](#custom-config)
- [Config](#config)
- [Default Config](#default-config-1)
- [Constants](#constants)
## Signatures
```go
func New(config ...Config) fiber.Handler
```
## Examples
First import the middleware from Fiber,
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
)
```
Then create a Fiber app with `app := fiber.New()`.
### Default Config
```go
app.Use(compress.New())
```
### Custom Config
```go
// Provide a custom compression level
app.Use(compress.New(compress.Config{
Level: compress.LevelBestSpeed, // 1
}))
// Skip middleware for specific routes
app.Use(compress.New(compress.Config{
Next: func(c *fiber.Ctx) bool {
return c.Path() == "/dont_compress"
},
Level: compress.LevelBestSpeed, // 1
}))
```
## Config
```go
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// CompressLevel determines the compression algoritm
//
// Optional. Default: LevelDefault
// LevelDisabled: -1
// LevelDefault: 0
// LevelBestSpeed: 1
// LevelBestCompression: 2
Level int
}
```
## Default Config
```go
var ConfigDefault = Config{
Next: nil,
Level: LevelDefault,
}
```
## Constants
```go
// Compression levels
const (
LevelDisabled = -1
LevelDefault = 0
LevelBestSpeed = 1
LevelBestCompression = 2
)
```

View File

@ -1,111 +0,0 @@
# Cross-Origin Resource Sharing (CORS) Middleware
CORS middleware for [Fiber](https://github.com/gofiber/fiber) that that can be used to enable [Cross-Origin Resource Sharing](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) with various options.
## Table of Contents
- [Cross-Origin Resource Sharing (CORS) Middleware](#cross-origin-resource-sharing-cors-middleware)
- [Table of Contents](#table-of-contents)
- [Signatures](#signatures)
- [Examples](#examples)
- [Default Config](#default-config)
- [Custom Config](#custom-config)
- [Config](#config)
- [Default Config](#default-config-1)
## Signatures
```go
func New(config ...Config) fiber.Handler
```
## Examples
First import the middleware from Fiber,
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
)
```
Then create a Fiber app with `app := fiber.New()`.
### Default Config
```go
app.Use(cors.New())
```
### Custom Config
```go
app.Use(cors.New(cors.Config{
AllowOrigins: "https://gofiber.io, https://gofiber.net",
AllowHeaders: "Origin, Content-Type, Accept",
}))
```
## Config
```go
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// AllowOrigin defines a list of origins that may access the resource.
//
// Optional. Default value "*"
AllowOrigins string
// AllowMethods defines a list methods allowed when accessing the resource.
// This is used in response to a preflight request.
//
// Optional. Default value "GET,POST,HEAD,PUT,DELETE,PATCH"
AllowMethods string
// AllowHeaders defines a list of request headers that can be used when
// making the actual request. This is in response to a preflight request.
//
// Optional. Default value "".
AllowHeaders string
// AllowCredentials indicates whether or not the response to the request
// can be exposed when the credentials flag is true. When used as part of
// a response to a preflight request, this indicates whether or not the
// actual request can be made using credentials.
//
// Optional. Default value false.
AllowCredentials bool
// ExposeHeaders defines a whitelist headers that clients are allowed to
// access.
//
// Optional. Default value "".
ExposeHeaders string
// MaxAge indicates how long (in seconds) the results of a preflight request
// can be cached.
//
// Optional. Default value 0.
MaxAge int
}
```
## Default Config
```go
var ConfigDefault = Config{
Next: nil,
AllowOrigins: "*",
AllowMethods: "GET,POST,HEAD,PUT,DELETE,PATCH",
AllowHeaders: "",
AllowCredentials: false,
ExposeHeaders: "",
MaxAge: 0,
}
```

View File

@ -1,161 +0,0 @@
# CSRF Middleware
CSRF middleware for [Fiber](https://github.com/gofiber/fiber) that provides [Cross-site request forgery](https://en.wikipedia.org/wiki/Cross-site_request_forgery) protection by passing a csrf token via cookies. This cookie value will be used to compare against the client csrf token in POST requests. When the csrf token is invalid, this middleware will delete the `csrf_` cookie and return the `fiber.ErrForbidden` error.
CSRF Tokens are generated on GET requests. You can retrieve the CSRF token with `c.Locals(contextKey)`, where `contextKey` is the string you set in the config (see Custom Config below).
_NOTE: This middleware uses our [Storage](https://github.com/gofiber/storage) package to support various databases through a single interface. The default configuration for this middleware saves data to memory, see the examples below for other databases._
## Table of Contents
- [CSRF Middleware](#csrf-middleware)
- [Table of Contents](#table-of-contents)
- [Signatures](#signatures)
- [Examples](#examples)
- [Default Config](#default-config)
- [Custom Config](#custom-config)
- [Custom Storage/Database](#custom-storagedatabase)
- [Config](#config)
- [Default Config](#default-config-1)
## Signatures
```go
func New(config ...Config) fiber.Handler
```
### Examples
Import the middleware package that is part of the Fiber web framework
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/crsf"
)
```
After you initiate your Fiber app, you can use the following possibilities:
```go
app.Use(csrf.New()) // Default config
```
### Custom Config
```go
app.Use(csrf.New(csrf.Config{
KeyLookup: "header:X-Csrf-Token",
CookieName: "csrf_",
CookieSameSite: "Lax",
Expiration: 1 * time.Hour,
KeyGenerator: utils.UUID,
Extractor: func(c *fiber.Ctx) (string, error) { ... },
}))
```
Note: KeyLookup will be ignored if Extractor is explicitly set.
### Custom Storage/Database
You can use any storage from our [storage](https://github.com/gofiber/storage/) package.
```go
storage := sqlite3.New() // From github.com/gofiber/storage/sqlite3
app.Use(csrf.New(csrf.Config{
Storage: storage,
}))
```
### Config
```go
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// KeyLookup is a string in the form of "<source>:<key>" that is used
// to create an Extractor that extracts the token from the request.
// Possible values:
// - "header:<name>"
// - "query:<name>"
// - "param:<name>"
// - "form:<name>"
// - "cookie:<name>"
//
// Ignored if an Extractor is explicitly set.
//
// Optional. Default: "header:X-CSRF-Token"
KeyLookup string
// Name of the session cookie. This cookie will store session key.
// Optional. Default value "csrf_".
CookieName string
// Domain of the CSRF cookie.
// Optional. Default value "".
CookieDomain string
// Path of the CSRF cookie.
// Optional. Default value "".
CookiePath string
// Indicates if CSRF cookie is secure.
// Optional. Default value false.
CookieSecure bool
// Indicates if CSRF cookie is HTTP only.
// Optional. Default value false.
CookieHTTPOnly bool
// Indicates if CSRF cookie is requested by SameSite.
// Optional. Default value "Lax".
CookieSameSite string
// Decides whether cookie should last for only the browser sesison.
// Ignores Expiration if set to true
CookieSessionOnly bool
// Expiration is the duration before csrf token will expire
//
// Optional. Default: 1 * time.Hour
Expiration time.Duration
// Store is used to store the state of the middleware
//
// Optional. Default: memory.New()
Storage fiber.Storage
// Context key to store generated CSRF token into context.
// If left empty, token will not be stored in context.
//
// Optional. Default: ""
ContextKey string
// KeyGenerator creates a new CSRF token
//
// Optional. Default: utils.UUID
KeyGenerator func() string
// Extractor returns the csrf token
//
// If set this will be used in place of an Extractor based on KeyLookup.
//
// Optional. Default will create an Extractor based on KeyLookup.
Extractor func(c *fiber.Ctx) (string, error)
}
```
### Default Config
```go
var ConfigDefault = Config{
KeyLookup: "header:X-Csrf-Token",
CookieName: "csrf_",
CookieSameSite: "Lax",
Expiration: 1 * time.Hour,
KeyGenerator: utils.UUID,
}
```

View File

@ -1,101 +0,0 @@
# Early Data Middleware
The Early Data middleware for [Fiber](https://github.com/gofiber/fiber) adds support for TLS 1.3's early data ("0-RTT") feature.
Citing [RFC 8446](https://datatracker.ietf.org/doc/html/rfc8446#section-2-3), when a client and server share a PSK, TLS 1.3 allows clients to send data on the first flight ("early data") to speed up the request, effectively reducing the regular 1-RTT request to a 0-RTT request.
Make sure to enable fiber's `EnableTrustedProxyCheck` config option before using this middleware in order to not trust bogus HTTP request headers of the client.
Also be aware that enabling support for early data in your reverse proxy (e.g. nginx, as done with a simple `ssl_early_data on;`) makes requests replayable. Refer to the following documents before continuing:
- https://datatracker.ietf.org/doc/html/rfc8446#section-8
- https://blog.trailofbits.com/2019/03/25/what-application-developers-need-to-know-about-tls-early-data-0rtt/
By default, this middleware allows early data requests on safe HTTP request methods only and rejects the request otherwise, i.e. aborts the request before executing your handler. This behavior can be controlled by the `AllowEarlyData` config option.
Safe HTTP methods — `GET`, `HEAD`, `OPTIONS` and `TRACE` — should not modify a state on the server.
## Table of Contents
- [Early Data Middleware](#early-data-middleware)
- [Table of Contents](#table-of-contents)
- [Signatures](#signatures)
- [Examples](#examples)
- [Default Config](#default-config)
- [Custom Config](#custom-config)
- [Config](#config)
- [Default Config](#default-config-1)
## Signatures
```go
func New(config ...Config) fiber.Handler
```
## Examples
First import the middleware from Fiber,
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/earlydata"
)
```
Then create a Fiber app with `app := fiber.New()`.
### Default Config
```go
app.Use(earlydata.New())
```
### Custom Config
```go
app.Use(earlydata.New(earlydata.Config{
Error: fiber.ErrTooEarly,
// ...
}))
```
### Config
```go
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// IsEarlyData returns whether the request is an early-data request.
//
// Optional. Default: a function which checks if the "Early-Data" request header equals "1".
IsEarlyData func(c *fiber.Ctx) bool
// AllowEarlyData returns whether the early-data request should be allowed or rejected.
//
// Optional. Default: a function which rejects the request on unsafe and allows the request on safe HTTP request methods.
AllowEarlyData func(c *fiber.Ctx) bool
// Error is returned in case an early-data request is rejected.
//
// Optional. Default: fiber.ErrTooEarly.
Error error
}
```
### Default Config
```go
var ConfigDefault = Config{
IsEarlyData: func(c *fiber.Ctx) bool {
return c.Get("Early-Data") == "1"
},
AllowEarlyData: func(c *fiber.Ctx) bool {
return fiber.IsMethodSafe(c.Method())
},
Error: fiber.ErrTooEarly,
}
```

View File

@ -1,113 +0,0 @@
# Encrypt Cookie Middleware
Encrypt middleware for [Fiber](https://github.com/gofiber/fiber) which encrypts cookie values. Note: this middleware does not encrypt cookie names.
## Table of Contents
* [Signatures](encryptcookie.md#signatures)
* [Setup](encryptcookie.md#setup)
* [Config](encryptcookie.md#config)
* [Default Config](encryptcookie.md#default-config)
## Signatures
```go
// Intitializes the middleware
func New(config ...Config) fiber.Handler
// Returns a random 32 character long string
func GenerateKey() string
```
## Examples
Import the middleware package that is part of the Fiber web framework
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/encryptcookie"
)
```
After you initiate your Fiber app, you can use the following possibilities:
```go
// Default middleware config
app.Use(encryptcookie.New(encryptcookie.Config{
Key: "secret-thirty-2-character-string",
}))
// Get / reading out the encrypted cookie
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("value=" + c.Cookies("test"))
})
// Post / create the encrypted cookie
app.Post("/", func(c *fiber.Ctx) error {
c.Cookie(&fiber.Cookie{
Name: "test",
Value: "SomeThing",
})
return nil
})
```
## Config
```go
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// Array of cookie keys that should not be encrypted.
//
// Optional. Default: ["csrf_"]
Except []string
// Base64 encoded unique key to encode & decode cookies.
//
// Required. The key should be 32 bytes of random data in base64-encoded form.
// You may run `openssl rand -base64 32` or use `encryptcookie.GenerateKey()` to generate a new key.
Key string
// Custom function to encrypt cookies.
//
// Optional. Default: EncryptCookie
Encryptor func(decryptedString, key string) (string, error)
// Custom function to decrypt cookies.
//
// Optional. Default: DecryptCookie
Decryptor func(encryptedString, key string) (string, error)
}
```
## Default Config
```go
// `Key` must be a 32 character string. It's used to encrpyt the values, so make sure it is random and keep it secret.
// You can run `openssl rand -base64 32` or call `encryptcookie.GenerateKey()` to create a random key for you.
// Make sure not to set `Key` to `encryptcookie.GenerateKey()` because that will create a new key every run.
app.Use(encryptcookie.New(encryptcookie.Config{
Key: "secret-thirty-2-character-string",
}))
```
## Usage of CSRF and Encryptcookie Middlewares with Custom Cookie Names
Normally, encryptcookie middleware skips `csrf_` cookies. However, it won't work when you use custom cookie names for CSRF. You should update `Except` config to avoid this problem. For example:
```go
app.Use(encryptcookie.New(encryptcookie.Config{
Key: "secret-thirty-2-character-string",
Except: []string{"csrf_1"}, // exclude CSRF cookie
}))
app.Use(csrf.New(csrf.Config{
KeyLookup: "form:test",
CookieName: "csrf_1",
CookieHTTPOnly: true,
}))
```

View File

@ -1,83 +0,0 @@
# Exposing Environment Variables Middleware
EnvVar middleware for [Fiber](https://github.com/gofiber/fiber) that can be used to expose environment variables with various options.
## Table of Contents
- [Environment Variables (EnvVar) Middleware](#environment-variables-envvar-middleware)
- [Table of Contents](#table-of-contents)
- [Signatures](#signatures)
- [Examples](#examples)
- [Default Config](#default-config)
- [Custom Config](#custom-config)
- [Response](#response)
- [Config](#config)
- [Default Config](#default-config-1)
## Signatures
```go
func New(config ...Config) fiber.Handler
```
## Examples
First import the middleware from Fiber,
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/envvar"
)
```
Then create a Fiber app with `app := fiber.New()`.
**Note**: You need to provide a path to use envvar middleware.
### Default Config
```go
app.Use("/expose/envvars", envvar.New())
```
### Custom Config
```go
app.Use("/expose/envvars", envvar.New(
envvar.Config{
ExportVars: map[string]string{"testKey": "", "testDefaultKey": "testDefaultVal"},
ExcludeVars: map[string]string{"excludeKey": ""},
}),
)
```
### Response
Http response contract:
```
{
"vars": {
"someEnvVariable": "someValue",
"anotherEnvVariable": "anotherValue"
}
}
```
## Config
```go
// Config defines the config for middleware.
type Config struct {
// ExportVars specifies the environment variables that should export
ExportVars map[string]string
// ExcludeVars specifies the environment variables that should not export
ExcludeVars map[string]string
}
```
## Default Config
```go
Config{}
```

View File

@ -1,88 +0,0 @@
# ETag Middleware
ETag middleware for [Fiber](https://github.com/gofiber/fiber) that lets caches be more efficient and save bandwidth, as a web server does not need to resend a full response if the content has not changed.
## Table of Contents
- [ETag Middleware](#etag-middleware)
- [Table of Contents](#table-of-contents)
- [Signatures](#signatures)
- [Examples](#examples)
- [Default Config](#default-config)
- [Custom Config](#custom-config)
- [Config](#config)
- [Default Config](#default-config-2)
## Signatures
```go
func New(config ...Config) fiber.Handler
```
## Examples
Import the middleware package that is part of the Fiber web framework
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/etag"
)
```
After you initiate your Fiber app, you can use the following possibilities:
### Default Config
```go
app.Use(etag.New())
// Get / receives Etag: "13-1831710635" in response header
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
})
```
### Custom Config
```go
app.Use(etag.New(etag.Config{
Weak: true,
}))
// Get / receives Etag: "W/"13-1831710635" in response header
app.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
})
```
## Config
```go
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// Weak indicates that a weak validator is used. Weak etags are easy
// to generate, but are far less useful for comparisons. Strong
// validators are ideal for comparisons but can be very difficult
// to generate efficiently. Weak ETag values of two representations
// of the same resources might be semantically equivalent, but not
// byte-for-byte identical. This means weak etags prevent caching
// when byte range requests are used, but strong etags mean range
// requests can still be cached.
Weak bool
}
```
## Default Config
```go
var ConfigDefault = Config{
Next: nil,
Weak: false,
}
```

View File

@ -1,85 +0,0 @@
# Expvar Middleware
Expvar middleware for [Fiber](https://github.com/gofiber/fiber) that serves via its HTTP server runtime exposed variants in the JSON format. The package is typically only imported for the side effect of registering its HTTP handlers. The handled path is `/debug/vars`.
- [Expvar Middleware](#expvar-middleware)
- [Signatures](#signatures)
- [Example](#example)
## Signatures
```go
func New() fiber.Handler
```
## Example
Import the expvar package that is part of the Fiber web framework
```go
package main
import (
"expvar"
"fmt"
"github.com/gofiber/fiber/v2"
expvarmw "github.com/gofiber/fiber/v2/middleware/expvar"
)
var count = expvar.NewInt("count")
func main() {
app := fiber.New()
app.Use(expvarmw.New())
app.Get("/", func(c *fiber.Ctx) error {
count.Add(1)
return c.SendString(fmt.Sprintf("hello expvar count %d", count.Value()))
})
fmt.Println(app.Listen(":3000"))
}
```
Visit path `/debug/vars` to see all vars and use query `r=key` to filter exposed variables.
```bash
curl 127.0.0.1:3000
hello expvar count 1
curl 127.0.0.1:3000/debug/vars
{
"cmdline": ["xxx"],
"count": 1,
"expvarHandlerCalls": 33,
"expvarRegexpErrors": 0,
"memstats": {...}
}
curl 127.0.0.1:3000/debug/vars?r=c
{
"cmdline": ["xxx"],
"count": 1
}
```
## Config
```go
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
}
```
## Default Config
```go
var ConfigDefault = Config{
Next: nil,
}
```

View File

@ -1,91 +0,0 @@
# Favicon Middleware
Favicon middleware for [Fiber](https://github.com/gofiber/fiber) that ignores favicon requests or caches a provided icon in memory to improve performance by skipping disk access. User agents request favicon.ico frequently and indiscriminately, so you may wish to exclude these requests from your logs by using this middleware before your logger middleware.
**Note** This middleware is exclusively for serving the default, implicit favicon, which is GET /favicon.ico or [custom favicon URL](#config).
## Table of Contents
- [Favicon Middleware](#favicon-middleware)
- [Table of Contents](#table-of-contents)
- [Signatures](#signatures)
- [Examples](#examples)
- [Default Config](#default-config)
- [Custom Config](#custom-config)
- [Config](#config)
- [Default Config](#default-config-1)
## Signatures
```go
func New(config ...Config) fiber.Handler
```
## Examples
First import the middleware from Fiber,
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/favicon"
)
```
Then create a Fiber app with `app := fiber.New()`.
### Default Config
```go
app.Use(favicon.New())
```
### Custom Config
```go
app.Use(favicon.New(favicon.Config{
File: "./favicon.ico",
URL: "/favicon.ico",
}))
```
### Config
```go
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// File holds the path to an actual favicon that will be cached
//
// Optional. Default: ""
File string
// URL for favicon handler
//
// Optional. Default: "/favicon.ico"
URL string
// FileSystem is an optional alternate filesystem to search for the favicon in.
// An example of this could be an embedded or network filesystem
//
// Optional. Default: nil
FileSystem http.FileSystem
// CacheControl defines how the Cache-Control header in the response should be set
//
// Optional. Default: "public, max-age=31536000"
CacheControl string
}
```
### Default Config
```go
var ConfigDefault = Config{
Next: nil,
File: "",
URL: "/favicon.ico",
}
```

View File

@ -1,298 +0,0 @@
# Filesystem Middleware
Filesystem middleware for [Fiber](https://github.com/gofiber/fiber) that enables you to serve files from a directory.
⚠️ **`:params` & `:optionals?` within the prefix path are not supported!**
⚠️ **To handle paths with spaces (or other url encoded values) make sure to set `fiber.Config{ UnescapePath: true}`**
## Table of Contents
- [Filesystem Middleware](#filesystem-middleware)
- [Table of Contents](#table-of-contents)
- [Signatures](#signatures)
- [Examples](#examples)
- [Config](#config)
- [embed](#embed)
- [pkger](#pkger)
- [packr](#packr)
- [go.rice](#gorice)
- [fileb0x](#fileb0x)
- [statik](#statik)
- [Config](#config-1)
- [Default Config](#default-config)
## Signatures
```go
func New(config Config) fiber.Handler
```
## Examples
First import the middleware from Fiber,
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"
)
```
Then create a Fiber app with `app := fiber.New()`.
### Config
```go
// Provide a minimal config
app.Use(filesystem.New(filesystem.Config{
Root: http.Dir("./assets"),
}))
// Or extend your config for customization
app.Use(filesystem.New(filesystem.Config{
Root: http.Dir("./assets"),
Browse: true,
Index: "index.html",
NotFoundFile: "404.html",
MaxAge: 3600,
}))
```
> If your environment (Go 1.16+) supports it, we recommend using Go Embed instead of the other solutions listed as this one is native to Go and the easiest to use.
### embed
[Embed](https://golang.org/pkg/embed/) is the native method to embed files in a Golang excecutable. Introduced in Go 1.16.
```go
package main
import (
"embed"
"io/fs"
"log"
"net/http"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"
)
// Embed a single file
//go:embed index.html
var f embed.FS
// Embed a directory
//go:embed static/*
var embedDirStatic embed.FS
func main() {
app := fiber.New()
app.Use("/", filesystem.New(filesystem.Config{
Root: http.FS(f),
}))
// Access file "image.png" under `static/` directory via URL: `http://<server>/static/image.png`.
// Without `PathPrefix`, you have to access it via URL:
// `http://<server>/static/static/image.png`.
app.Use("/static", filesystem.New(filesystem.Config{
Root: http.FS(embedDirStatic),
PathPrefix: "static",
Browse: true,
}))
log.Fatal(app.Listen(":3000"))
}
```
### pkger
[Pkger](https://github.com/markbates/pkger) can be used to embed files in a Golang excecutable.
```go
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"
"github.com/markbates/pkger"
)
func main() {
app := fiber.New()
app.Use("/assets", filesystem.New(filesystem.Config{
Root: pkger.Dir("/assets"),
}))
log.Fatal(app.Listen(":3000"))
}
```
### packr
[Packr](https://github.com/gobuffalo/packr) can be used to embed files in a Golang excecutable.
```go
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"
"github.com/gobuffalo/packr/v2"
)
func main() {
app := fiber.New()
app.Use("/assets", filesystem.New(filesystem.Config{
Root: packr.New("Assets Box", "/assets"),
}))
log.Fatal(app.Listen(":3000"))
}
```
### go.rice
https://github.com/GeertJohan/go.rice
```go
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"
"github.com/GeertJohan/go.rice"
)
func main() {
app := fiber.New()
app.Use("/assets", filesystem.New(filesystem.Config{
Root: rice.MustFindBox("assets").HTTPBox(),
}))
log.Fatal(app.Listen(":3000"))
}
```
### fileb0x
[Fileb0x](https://github.com/UnnoTed/fileb0x) can be used to embed files in a Golang excecutable.
```go
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"
"<Your go module>/myEmbeddedFiles"
)
func main() {
app := fiber.New()
app.Use("/assets", filesystem.New(filesystem.Config{
Root: myEmbeddedFiles.HTTP,
}))
log.Fatal(app.Listen(":3000"))
}
```
### statik
[Statik](https://github.com/rakyll/statik) can be used to embed files in a Golang excecutable.
```go
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/filesystem"
// Use blank to invoke init function and register data to statik
_ "<Your go module>/statik"
"github.com/rakyll/statik/fs"
)
func main() {
statikFS, err := fs.New()
if err != nil {
panic(err)
}
app := fiber.New()
app.Use("/", filesystem.New(filesystem.Config{
Root: statikFS,
}))
log.Fatal(app.Listen(":3000"))
}
```
## Config
```go
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// Root is a FileSystem that provides access
// to a collection of files and directories.
//
// Required. Default: nil
Root http.FileSystem `json:"-"`
// PathPrefix defines a prefix to be added to a filepath when
// reading a file from the FileSystem.
//
// Use when using Go 1.16 embed.FS
//
// Optional. Default ""
PathPrefix string `json:"path_prefix"`
// Enable directory browsing.
//
// Optional. Default: false
Browse bool `json:"browse"`
// Index file for serving a directory.
//
// Optional. Default: "index.html"
Index string `json:"index"`
// The value for the Cache-Control HTTP-header
// that is set on the file response. MaxAge is defined in seconds.
//
// Optional. Default value 0.
MaxAge int `json:"max_age"`
// File to return if path is not found. Useful for SPA's.
//
// Optional. Default: ""
NotFoundFile string `json:"not_found_file"`
}
```
### Default Config
```go
var ConfigDefault = Config{
Next: nil,
Root: nil,
PathPrefix: "",
Browse: false,
Index: "/index.html",
MaxAge: 0,
}
```

View File

@ -1,118 +0,0 @@
# Idempotency Middleware
Idempotency middleware for [Fiber](https://github.com/gofiber/fiber) allows for fault-tolerant APIs where duplicate requests — for example due to networking issues on the client-side — do not erroneously cause the same action performed multiple times on the server-side.
Refer to https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header-02 for a better understanding.
## Table of Contents
- [Idempotency Middleware](#idempotency-middleware)
- [Table of Contents](#table-of-contents)
- [Signatures](#signatures)
- [Examples](#examples)
- [Default Config](#default-config)
- [Custom Config](#custom-config)
- [Config](#config)
- [Default Config](#default-config-1)
## Signatures
```go
func New(config ...Config) fiber.Handler
```
## Examples
First import the middleware from Fiber,
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/idempotency"
)
```
Then create a Fiber app with `app := fiber.New()`.
### Default Config
```go
app.Use(idempotency.New())
```
### Custom Config
```go
app.Use(idempotency.New(idempotency.Config{
Lifetime: 42 * time.Minute,
// ...
}))
```
### Config
```go
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: a function which skips the middleware on safe HTTP request method.
Next func(c *fiber.Ctx) bool
// Lifetime is the maximum lifetime of an idempotency key.
//
// Optional. Default: 30 * time.Minute
Lifetime time.Duration
// KeyHeader is the name of the header that contains the idempotency key.
//
// Optional. Default: X-Idempotency-Key
KeyHeader string
// KeyHeaderValidate defines a function to validate the syntax of the idempotency header.
//
// Optional. Default: a function which ensures the header is 36 characters long (the size of an UUID).
KeyHeaderValidate func(string) error
// KeepResponseHeaders is a list of headers that should be kept from the original response.
//
// Optional. Default: nil (to keep all headers)
KeepResponseHeaders []string
// Lock locks an idempotency key.
//
// Optional. Default: an in-memory locker for this process only.
Lock Locker
// Storage stores response data by idempotency key.
//
// Optional. Default: an in-memory storage for this process only.
Storage fiber.Storage
}
```
### Default Config
```go
var ConfigDefault = Config{
Next: func(c *fiber.Ctx) bool {
// Skip middleware if the request was done using a safe HTTP method
return fiber.IsMethodSafe(c.Method())
},
Lifetime: 30 * time.Minute,
KeyHeader: "X-Idempotency-Key",
KeyHeaderValidate: func(k string) error {
if l, wl := len(k), 36; l != wl { // UUID length is 36 chars
return fmt.Errorf("%w: invalid length: %d != %d", ErrInvalidIdempotencyKey, l, wl)
}
return nil
},
KeepResponseHeaders: nil,
Lock: nil, // Set in configDefault so we don't allocate data here.
Storage: nil, // Set in configDefault so we don't allocate data here.
}
```

View File

@ -1,146 +0,0 @@
# Limiter Middleware
Limiter middleware for [Fiber](https://github.com/gofiber/fiber) that is used to limit repeat requests to public APIs and/or endpoints such as password reset. It is also useful for API clients, web crawling, or other tasks that need to be throttled.
_NOTE: This middleware uses our [Storage](https://github.com/gofiber/storage) package to support various databases through a single interface. The default configuration for this middleware saves data to memory, see the examples below for other databases._
**NOTE: this module does not share state with other processes/servers by default.**
## Table of Contents
- [Limiter Middleware](#limiter-middleware)
- [Table of Contents](#table-of-contents)
- [Signatures](#signatures)
- [Examples](#examples)
- [Default Config](#default-config)
- [Custom Config](#custom-config)
- [Custom Storage/Database](#custom-storagedatabase)
- [Config](#config)
- [Default Config](#default-config-1)
## Signatures
```go
func New(config ...Config) fiber.Handler
```
## Examples
First import the middleware from Fiber,
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/limiter"
)
```
Then create a Fiber app with `app := fiber.New()`.
### Default Config
```go
// Default middleware config
app.Use(limiter.New())
```
### Custom Config
```go
// Or extend your config for customization
app.Use(limiter.New(limiter.Config{
Next: func(c *fiber.Ctx) bool {
return c.IP() == "127.0.0.1"
},
Max: 20,
Expiration: 30 * time.Second,
KeyGenerator: func(c *fiber.Ctx) string{
return "key"
},
LimitReached: func(c *fiber.Ctx) error {
return c.SendFile("./toofast.html")
},
Storage: myCustomStore{},
}))
```
### Custom Storage/Database
You can use any storage from our [storage](https://github.com/gofiber/storage/) package.
```go
storage := sqlite3.New() // From github.com/gofiber/storage/sqlite3
app.Use(limiter.New(limiter.Config{
Storage: storage,
}))
```
## Config
```go
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// Max number of recent connections during `Duration` seconds before sending a 429 response
//
// Default: 5
Max int
// KeyGenerator allows you to generate custom keys, by default c.IP() is used
//
// Default: func(c *fiber.Ctx) string {
// return c.IP()
// }
KeyGenerator func(*fiber.Ctx) string
// Expiration is the time on how long to keep records of requests in memory
//
// Default: 1 * time.Minute
Expiration time.Duration
// LimitReached is called when a request hits the limit
//
// Default: func(c *fiber.Ctx) error {
// return c.SendStatus(fiber.StatusTooManyRequests)
// }
LimitReached fiber.Handler
// When set to true, requests with StatusCode >= 400 won't be counted.
//
// Default: false
SkipFailedRequests bool
// When set to true, requests with StatusCode < 400 won't be counted.
//
// Default: false
SkipSuccessfulRequests bool
// Store is used to store the state of the middleware
//
// Default: an in memory store for this process only
Storage fiber.Storage
}
```
A custom store can be used if it implements the `Storage` interface - more details and an example can be found in `store.go`.
### Default Config
```go
var ConfigDefault = Config{
Max: 5,
Expiration: 1 * time.Minute,
KeyGenerator: func(c *fiber.Ctx) string {
return c.IP()
},
LimitReached: func(c *fiber.Ctx) error {
return c.SendStatus(fiber.StatusTooManyRequests)
},
SkipFailedRequests: false,
SkipSuccessfulRequests: false,
}
```

View File

@ -1,212 +0,0 @@
# Logger Middleware
Logger middleware for [Fiber](https://github.com/gofiber/fiber) that logs HTTP request/response details.
## Table of Contents
- [Logger Middleware](#logger-middleware)
- [Table of Contents](#table-of-contents)
- [Signatures](#signatures)
- [Examples](#examples)
- [Default Config](#default-config)
- [Logging remote IP and Port](#logging-remote-ip-and-port)
- [Logging Request ID](#logging-request-id)
- [Changing TimeZone & TimeFormat](#changing-timezone--timeformat)
- [Custom File Writer](#custom-file-writer)
- [Add Custom Tags](#add-custom-tags)
- [Config](#config)
- [Default Config](#default-config-1)
- [Constants](#constants)
## Signatures
```go
func New(config ...Config) fiber.Handler
```
## Examples
First ensure the appropriate packages are imported
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
)
```
### Default Config
```go
// Default middleware config
app.Use(logger.New())
```
### Logging remote IP and Port
```go
app.Use(logger.New(logger.Config{
Format: "[${ip}]:${port} ${status} - ${method} ${path}\n",
}))
```
### Logging Request ID
```go
app.Use(requestid.New())
app.Use(logger.New(logger.Config{
// For more options, see the Config section
Format: "${pid} ${locals:requestid} ${status} - ${method} ${path}\n",
}))
```
### Changing TimeZone & TimeFormat
```go
app.Use(logger.New(logger.Config{
Format: "${pid} ${status} - ${method} ${path}\n",
TimeFormat: "02-Jan-2006",
TimeZone: "America/New_York",
}))
```
### Custom File Writer
```go
file, err := os.OpenFile("./123.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
log.Fatalf("error opening file: %v", err)
}
defer file.Close()
app.Use(logger.New(logger.Config{
Output: file,
}))
```
### Add Custom Tags
```go
app.Use(logger.New(logger.Config{
CustomTags: map[string]logger.LogFunc{
"custom_tag": func(output logger.Buffer, c *fiber.Ctx, data *logger.Data, extraParam string) (int, error) {
return output.WriteString("it is a custom tag")
},
},
}))
```
### Callback after log is written
```go
app.Use(logger.New(logger.Config{
TimeFormat: time.RFC3339Nano,
TimeZone: "Asia/Shanghai",
Done: func(c *fiber.Ctx, logString []byte) {
if c.Response().StatusCode() != fiber.StatusOK {
reporter.SendToSlack(logString)
}
},
}))
```
## Config
```go
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// Done is a function that is called after the log string for a request is written to Output,
// and pass the log string as parameter.
//
// Optional. Default: nil
Done func(c *fiber.Ctx, logString []byte)
// tagFunctions defines the custom tag action
//
// Optional. Default: map[string]LogFunc
CustomTags map[string]LogFunc
// Format defines the logging tags
//
// Optional. Default: [${time}] ${status} - ${latency} ${method} ${path}\n
Format string
// TimeFormat https://programming.guide/go/format-parse-string-time-date-example.html
//
// Optional. Default: 15:04:05
TimeFormat string
// TimeZone can be specified, such as "UTC" and "America/New_York" and "Asia/Chongqing", etc
//
// Optional. Default: "Local"
TimeZone string
// TimeInterval is the delay before the timestamp is updated
//
// Optional. Default: 500 * time.Millisecond
TimeInterval time.Duration
// Output is a writer where logs are written
//
// Default: os.Stdout
Output io.Writer
}
type LogFunc func(buf logger.Buffer, c *fiber.Ctx, data *logger.Data, extraParam string) (int, error)
```
## Default Config
```go
var ConfigDefault = Config{
Next: nil,
Done: nil,
Format: "[${time}] ${status} - ${latency} ${method} ${path}\n",
TimeFormat: "15:04:05",
TimeZone: "Local",
TimeInterval: 500 * time.Millisecond,
Output: os.Stdout,
}
```
## Constants
```go
// Logger variables
const (
TagPid = "pid"
TagTime = "time"
TagReferer = "referer"
TagProtocol = "protocol"
TagPort = "port"
TagIP = "ip"
TagIPs = "ips"
TagHost = "host"
TagMethod = "method"
TagPath = "path"
TagURL = "url"
TagUA = "ua"
TagLatency = "latency"
TagStatus = "status" // response status
TagResBody = "resBody" // response body
TagReqHeaders = "reqHeaders"
TagQueryStringParams = "queryParams" // request query parameters
TagBody = "body" // request body
TagBytesSent = "bytesSent"
TagBytesReceived = "bytesReceived"
TagRoute = "route"
TagError = "error"
// Deprecated: Use TagReqHeader instead
TagHeader = "header:" // request header
TagReqHeader = "reqHeader:" // request header
TagRespHeader = "respHeader:" // response header
TagQuery = "query:" // request query
TagForm = "form:" // request form
TagCookie = "cookie:" // request cookie
TagLocals = "locals:"
// colors
TagBlack = "black"
TagRed = "red"
TagGreen = "green"
TagYellow = "yellow"
TagBlue = "blue"
TagMagenta = "magenta"
TagCyan = "cyan"
TagWhite = "white"
TagReset = "reset"
)
```

View File

@ -1,98 +0,0 @@
# Monitor
Monitor middleware for [Fiber](https://github.com/gofiber/fiber) that reports server metrics, inspired by [express-status-monitor](https://github.com/RafalWilinski/express-status-monitor)
:warning: **Warning:** Monitor is still in beta, API might change in the future!
![](https://i.imgur.com/nHAtBpJ.gif)
### Signatures
```go
func New() fiber.Handler
```
### Examples
Import the middleware package and assign it to a route.
```go
package main
import (
"log"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/monitor"
)
func main() {
app := fiber.New()
app.Get("/metrics", monitor.New(monitor.Config{Title: "MyService Metrics Page"}))
log.Fatal(app.Listen(":3000"))
}
```
You can also access the API endpoint with
`curl -X GET -H "Accept: application/json" http://localhost:3000/metrics` which returns:
```json
{"pid":{ "cpu":0.4568381746582226, "ram":20516864, "conns":3 },
"os": { "cpu":8.759124087593099, "ram":3997155328, "conns":44,
"total_ram":8245489664, "load_avg":0.51 }}
```
## Config
```go
// Config defines the config for middleware.
type Config struct {
// Metrics page title
//
// Optional. Default: "Fiber Monitor"
Title string
// Refresh period
//
// Optional. Default: 3 seconds
Refresh time.Duration
// Whether the service should expose only the monitoring API.
//
// Optional. Default: false
APIOnly bool
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// Custom HTML Code to Head Section(Before End)
//
// Optional. Default: empty
CustomHead string
// FontURL for specify font resource path or URL . also you can use relative path
//
// Optional. Default: https://fonts.googleapis.com/css2?family=Roboto:wght@400;900&display=swap
FontURL string
// ChartJsURL for specify ChartJS library path or URL . also you can use relative path
//
// Optional. Default: https://cdn.jsdelivr.net/npm/chart.js@2.9/dist/Chart.bundle.min.js
ChartJsURL string
}
```
## Default Config
```go
var ConfigDefault = Config{
Title: "Fiber Monitor",
Refresh: 3 * time.Second,
APIOnly: false,
Next: nil,
CustomHead:"",
FontURL:"https://fonts.googleapis.com/css2?family=Roboto:wght@400;900&display=swap",
ChartJsURL:"https://cdn.jsdelivr.net/npm/chart.js@2.9/dist/Chart.bundle.min.js"
}
```

View File

@ -1,62 +0,0 @@
# Pprof
Pprof middleware for [Fiber](https://github.com/gofiber/fiber) that serves via its HTTP server runtime profiling data in the format expected by the pprof visualization tool. The package is typically only imported for the side effect of registering its HTTP handlers. The handled paths all begin with /debug/pprof/.
- [Signatures](#signatures)
- [Examples](#examples)
### Signatures
```go
func New() fiber.Handler
```
### Examples
Import the middleware package that is part of the Fiber web framework
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/pprof"
)
```
After you initiate your Fiber app, you can use the following possibilities:
```go
// Default middleware
app.Use(pprof.New())
```
In systems where you have multiple ingress endpoints, it is common to add a URL prefix, like so:
```go
// Default middleware
app.Use(pprof.New(pprof.Config{Prefix: "/endpoint-prefix"}))
```
This prefix will be added to the default path of "/debug/pprof/", for a resulting URL of:
"/endpoint-prefix/debug/pprof/".
## Config
```go
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// Prefix defines a URL prefix added before "/debug/pprof".
// Note that it should start with (but not end with) a slash.
// Example: "/federated-fiber"
//
// Optional. Default: ""
Prefix string
}
```
## Default Config
```go
var ConfigDefault = Config{
Next: nil,
}
```

View File

@ -1,208 +0,0 @@
# Proxy
Proxy middleware for [Fiber](https://github.com/gofiber/fiber) that allows you to proxy requests to multiple servers.
### Table of Contents
- [Signatures](#signatures)
- [Examples](#examples)
- [Config](#config)
- [Default Config](#default-config)
### Signatures
```go
// Balancer create a load balancer among multiple upstrem servers.
func Balancer(config Config) fiber.Handler
// Forward performs the given http request and fills the given http response.
func Forward(addr string, clients ...*fasthttp.Client) fiber.Handler
// Do performs the given http request and fills the given http response.
func Do(c *fiber.Ctx, addr string, clients ...*fasthttp.Client) error
// DoRedirects performs the given http request and fills the given http response while following up to maxRedirectsCount redirects.
func DoRedirects(c *fiber.Ctx, addr string, maxRedirectsCount int, clients ...*fasthttp.Client) error
// DoDeadline performs the given request and waits for response until the given deadline.
func DoDeadline(c *fiber.Ctx, addr string, deadline time.Time, clients ...*fasthttp.Client) error
// DoTimeout performs the given request and waits for response during the given timeout duration.
func DoTimeout(c *fiber.Ctx, addr string, timeout time.Duration, clients ...*fasthttp.Client) error
// DomainForward the given http request based on the given domain and fills the given http response
func DomainForward(hostname string, addr string, clients ...*fasthttp.Client) fiber.Handler
// BalancerForward performs the given http request based round robin balancer and fills the given http response
func BalancerForward(servers []string, clients ...*fasthttp.Client) fiber.Handler
```
### Examples
Import the middleware package that is part of the Fiber web framework
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/proxy"
)
```
After you initiate your Fiber app, you can use the following possibilities:
```go
// if target https site uses a self-signed certificate, you should
// call WithTlsConfig before Do and Forward
proxy.WithTlsConfig(&tls.Config{
InsecureSkipVerify: true,
})
// if you need to use global self-custom client, you should use proxy.WithClient.
proxy.WithClient(&fasthttp.Client{
NoDefaultUserAgentHeader: true,
DisablePathNormalizing: true,
})
// Forward to url
app.Get("/gif", proxy.Forward("https://i.imgur.com/IWaBepg.gif"))
// If you want to forward with a specific domain. You have to use proxy.DomainForward.
app.Get("/payments", proxy.DomainForward("docs.gofiber.io", "http://localhost:8000"))
// Forward to url with local custom client
app.Get("/gif", proxy.Forward("https://i.imgur.com/IWaBepg.gif", &fasthttp.Client{
NoDefaultUserAgentHeader: true,
DisablePathNormalizing: true,
}))
// Make request within handler
app.Get("/:id", func(c *fiber.Ctx) error {
url := "https://i.imgur.com/"+c.Params("id")+".gif"
if err := proxy.Do(c, url); err != nil {
return err
}
// Remove Server header from response
c.Response().Header.Del(fiber.HeaderServer)
return nil
})
// Make proxy requests while following redirects
app.Get("/proxy", func(c *fiber.Ctx) error {
if err := proxy.DoRedirects(c, "http://google.com", 3); err != nil {
return err
}
// Remove Server header from response
c.Response().Header.Del(fiber.HeaderServer)
return nil
})
// Make proxy requests and wait up to 5 seconds before timing out
app.Get("/proxy", func(c *fiber.Ctx) error {
if err := proxy.DoTimeout(c, "http://localhost:3000", time.Second * 5); err != nil {
return err
}
// Remove Server header from response
c.Response().Header.Del(fiber.HeaderServer)
return nil
})
// Make proxy requests, timeout a minute from now
app.Get("/proxy", func(c *fiber.Ctx) error {
if err := DoDeadline(c, "http://localhost", time.Now().Add(time.Minute)); err != nil {
return err
}
// Remove Server header from response
c.Response().Header.Del(fiber.HeaderServer)
return nil
})
// Minimal round robin balancer
app.Use(proxy.Balancer(proxy.Config{
Servers: []string{
"http://localhost:3001",
"http://localhost:3002",
"http://localhost:3003",
},
}))
// Or extend your balancer for customization
app.Use(proxy.Balancer(proxy.Config{
Servers: []string{
"http://localhost:3001",
"http://localhost:3002",
"http://localhost:3003",
},
ModifyRequest: func(c *fiber.Ctx) error {
c.Request().Header.Add("X-Real-IP", c.IP())
return nil
},
ModifyResponse: func(c *fiber.Ctx) error {
c.Response().Header.Del(fiber.HeaderServer)
return nil
},
}))
// Or this way if the balancer is using https and the destination server is only using http.
app.Use(proxy.BalancerForward([]string{
"http://localhost:3001",
"http://localhost:3002",
"http://localhost:3003",
}))
```
### Config
```go
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// Servers defines a list of <scheme>://<host> HTTP servers,
//
// which are used in a round-robin manner.
// i.e.: "https://foobar.com, http://www.foobar.com"
//
// Required
Servers []string
// ModifyRequest allows you to alter the request
//
// Optional. Default: nil
ModifyRequest fiber.Handler
// ModifyResponse allows you to alter the response
//
// Optional. Default: nil
ModifyResponse fiber.Handler
// Timeout is the request timeout used when calling the proxy client
//
// Optional. Default: 1 second
Timeout time.Duration
// Per-connection buffer size for requests' reading.
// This also limits the maximum header size.
// Increase this buffer if your clients send multi-KB RequestURIs
// and/or multi-KB headers (for example, BIG cookies).
ReadBufferSize int
// Per-connection buffer size for responses' writing.
WriteBufferSize int
// tls config for the http client.
TlsConfig *tls.Config
// Client is custom client when client config is complex.
// Note that Servers, Timeout, WriteBufferSize, ReadBufferSize and TlsConfig
// will not be used if the client are set.
Client *fasthttp.LBClient
}
```
### Default Config
```go
// ConfigDefault is the default config
var ConfigDefault = Config{
Next: nil,
ModifyRequest: nil,
ModifyResponse: nil,
Timeout: fasthttp.DefaultLBClientTimeout,
}
```

View File

@ -1,64 +0,0 @@
# Recover
Recover middleware for [Fiber](https://github.com/gofiber/fiber) that recovers from panics anywhere in the stack chain and handles the control to the centralized [ErrorHandler](https://docs.gofiber.io/error-handling).
### Table of Contents
- [Signatures](#signatures)
- [Examples](#examples)
- [Config](#config)
- [Default Config](#default-config)
### Signatures
```go
func New(config ...Config) fiber.Handler
```
### Examples
Import the middleware package that is part of the Fiber web framework
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/recover"
)
```
After you initiate your Fiber app, you can use the following possibilities:
```go
// Default middleware config
app.Use(recover.New())
// This panic will be caught by the middleware
app.Get("/", func(c *fiber.Ctx) error {
panic("I'm an error")
})
```
### Config
```go
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// EnableStackTrace enables handling stack trace
//
// Optional. Default: false
EnableStackTrace bool
// StackTraceHandler defines a function to handle stack trace
//
// Optional. Default: defaultStackTraceHandler
StackTraceHandler func(c *fiber.Ctx, e interface{})
}
```
### Default Config
```go
var ConfigDefault = Config{
Next: nil,
EnableStackTrace: false,
StackTraceHandler: defaultStackTraceHandler,
}
```

View File

@ -1,78 +0,0 @@
# RequestID
RequestID middleware for [Fiber](https://github.com/gofiber/fiber) that adds an identifier to the response.
### Table of Contents
- [Signatures](#signatures)
- [Examples](#examples)
- [Config](#config)
- [Default Config](#default-config)
### Signatures
```go
func New(config ...Config) fiber.Handler
```
### Examples
Import the middleware package that is part of the Fiber web framework
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/requestid"
)
```
After you initiate your Fiber app, you can use the following possibilities:
```go
// Default middleware config
app.Use(requestid.New())
// Or extend your config for customization
app.Use(requestid.New(requestid.Config{
Header: "X-Custom-Header",
Generator: func() string {
return "static-id"
},
}))
```
### Config
```go
// Config defines the config for middleware.
type Config struct {
// Next defines a function to skip this middleware when returned true.
//
// Optional. Default: nil
Next func(c *fiber.Ctx) bool
// Header is the header key where to get/set the unique request ID
//
// Optional. Default: "X-Request-ID"
Header string
// Generator defines a function to generate the unique identifier.
//
// Optional. Default: utils.UUID
Generator func() string
// ContextKey defines the key used when storing the request ID in
// the locals for a specific request.
//
// Optional. Default: requestid
ContextKey string
}
```
### Default Config
The default config uses a fast UUID generator which will expose the number of
requests made to the server. To conceal this value for better privacy, use the
`utils.UUIDv4` generator.
```go
var ConfigDefault = Config{
Next: nil,
Header: fiber.HeaderXRequestID,
Generator: utils.UUID,
ContextKey: "requestid",
}
```

View File

@ -1,170 +0,0 @@
# Session
Session middleware for [Fiber](https://github.com/gofiber/fiber).
_NOTE: This middleware uses our [Storage](https://github.com/gofiber/storage) package to support various databases through a single interface. The default configuration for this middleware saves data to memory, see the examples below for other databases._
## Table of Contents
- [Session](#session)
- [Table of Contents](#table-of-contents)
- [Signatures](#signatures)
- [Examples](#examples)
- [Default Configuration](#default-configuration)
- [Custom Storage/Database](#custom-storagedatabase)
- [Config](#config)
- [Default Config](#default-config)
## Signatures
```go
func New(config ...Config) *Store
func (s *Store) RegisterType(i interface{})
func (s *Store) Get(c *fiber.Ctx) (*Session, error)
func (s *Store) Reset() error
func (s *Session) Get(key string) interface{}
func (s *Session) Set(key string, val interface{})
func (s *Session) Delete(key string)
func (s *Session) Destroy() error
func (s *Session) Regenerate() error
func (s *Session) Save() error
func (s *Session) Fresh() bool
func (s *Session) ID() string
func (s *Session) Keys() []string
func (s *Session) SetExpiry(time.Duration)
```
**⚠ _Storing `interface{}` values are limited to built-ins Go types_**
### Examples
Import the middleware package that is part of the Fiber web framework
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/session"
)
```
Then create a Fiber app with `app := fiber.New()`.
### Default Configuration
```go
// This stores all of your app's sessions
// Default middleware config
store := session.New()
// This panic will be catch by the middleware
app.Get("/", func(c *fiber.Ctx) error {
// Get session from storage
sess, err := store.Get(c)
if err != nil {
panic(err)
}
// Get value
name := sess.Get("name")
// Set key/value
sess.Set("name", "john")
// Get all Keys
keys := sess.Keys()
// Delete key
sess.Delete("name")
// Destroy session
if err := sess.Destroy(); err != nil {
panic(err)
}
// Sets a specific expiration for this session
sess.SetExpiry(time.Second * 2)
// Save session
if err := sess.Save(); err != nil {
panic(err)
}
return c.SendString(fmt.Sprintf("Welcome %v", name))
})
```
### Custom Storage/Database
You can use any storage from our [storage](https://github.com/gofiber/storage/) package.
```go
storage := sqlite3.New() // From github.com/gofiber/storage/sqlite3
store := session.New(session.Config{
Storage: storage,
})
```
To use the the store, see the above example.
## Config
```go
// Config defines the config for middleware.
type Config struct {
// Allowed session duration
// Optional. Default value 24 * time.Hour
Expiration time.Duration
// Storage interface to store the session data
// Optional. Default value memory.New()
Storage fiber.Storage
// KeyLookup is a string in the form of "<source>:<name>" that is used
// to extract session id from the request.
// Possible values: "header:<name>", "query:<name>" or "cookie:<name>"
// Optional. Default value "cookie:session_id".
KeyLookup string
// Domain of the cookie.
// Optional. Default value "".
CookieDomain string
// Path of the cookie.
// Optional. Default value "".
CookiePath string
// Indicates if cookie is secure.
// Optional. Default value false.
CookieSecure bool
// Indicates if cookie is HTTP only.
// Optional. Default value false.
CookieHTTPOnly bool
// Sets the cookie SameSite attribute.
// Optional. Default value "Lax".
CookieSameSite string
// KeyGenerator generates the session key.
// Optional. Default value utils.UUID
KeyGenerator func() string
// Deprecated: Please use KeyLookup
CookieName string
// Source defines where to obtain the session id
source Source
// The session name
sessionName string
}
```
## Default Config
```go
var ConfigDefault = Config{
Expiration: 24 * time.Hour,
KeyLookup: "cookie:session_id",
KeyGenerator: utils.UUID,
}
```

View File

@ -1,26 +0,0 @@
# Skip
Skip middleware for [Fiber](https://github.com/gofiber/fiber) that skips a wrapped handler is a predicate is true.
### Table of Contents
- [Signatures](#signatures)
- [Examples](#examples)
### Signatures
```go
func New(handler fiber.Handler, exclude func(c *fiber.Ctx) bool) fiber.Handler
```
### Examples
Import the middleware package that is part of the Fiber web framework
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/skip"
)
```
After you initiate your Fiber app, you can use the following possibilities:
```go
app.Use(skip.New(handler, func(ctx *fiber.Ctx) bool { return ctx.Method() == fiber.MethodOptions }))
```

View File

@ -1,98 +0,0 @@
# Timeout
Timeout middleware for Fiber. As a `fiber.Handler` wrapper, it creates a context with `context.WithTimeout` and pass it in `UserContext`.
If the context passed executions (eg. DB ops, Http calls) takes longer than the given duration to return, the timeout error is set and forwarded to the centralized `ErrorHandler`.
It has no race conditions, ready to use on production.
### Table of Contents
- [Signatures](#signatures)
- [Examples](#examples)
### Signatures
```go
func New(handler fiber.Handler, timeout time.Duration, timeoutErrors ...error) fiber.Handler
```
### Examples
Import the middleware package that is part of the Fiber web framework
```go
import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/timeout"
)
```
Sample timeout middleware usage
```go
func main() {
app := fiber.New()
h := func(c *fiber.Ctx) error {
sleepTime, _ := time.ParseDuration(c.Params("sleepTime") + "ms")
if err := sleepWithContext(c.UserContext(), sleepTime); err != nil {
return fmt.Errorf("%w: execution error", err)
}
return nil
}
app.Get("/foo/:sleepTime", timeout.New(h, 2*time.Second))
_ = app.Listen(":3000")
}
func sleepWithContext(ctx context.Context, d time.Duration) error {
timer := time.NewTimer(d)
select {
case <-ctx.Done():
if !timer.Stop() {
<-timer.C
}
return context.DeadlineExceeded
case <-timer.C:
}
return nil
}
```
Test http 200 with curl:
```bash
curl --location -I --request GET 'http://localhost:3000/foo/1000'
```
Test http 408 with curl:
```bash
curl --location -I --request GET 'http://localhost:3000/foo/3000'
```
When using with custom error:
```go
var ErrFooTimeOut = errors.New("foo context canceled")
func main() {
app := fiber.New()
h := func(c *fiber.Ctx) error {
sleepTime, _ := time.ParseDuration(c.Params("sleepTime") + "ms")
if err := sleepWithContextWithCustomError(c.UserContext(), sleepTime); err != nil {
return fmt.Errorf("%w: execution error", err)
}
return nil
}
app.Get("/foo/:sleepTime", timeout.New(h, 2*time.Second, ErrFooTimeOut))
_ = app.Listen(":3000")
}
func sleepWithContextWithCustomError(ctx context.Context, d time.Duration) error {
timer := time.NewTimer(d)
select {
case <-ctx.Done():
if !timer.Stop() {
<-timer.C
}
return ErrFooTimeOut
case <-timer.C:
}
return nil
}
```