diff --git a/docs/api/middleware/cache.md b/docs/api/middleware/cache.md index c4d5375982..5ffe20ba2d 100644 --- a/docs/api/middleware/cache.md +++ b/docs/api/middleware/cache.md @@ -51,7 +51,7 @@ app.Use(New(Config{ return time.Second * time.Duration(newCacheTime) }, KeyGenerator: func(c *fiber.Ctx) string { - return c.Path() + return utils.CopyString(c.Path()) } })) @@ -76,6 +76,13 @@ type Config struct { // 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 @@ -125,6 +132,7 @@ type Config struct { 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()) diff --git a/docs/api/middleware/csrf.md b/docs/api/middleware/csrf.md index 0ccce01ed1..b5982e3b28 100644 --- a/docs/api/middleware/csrf.md +++ b/docs/api/middleware/csrf.md @@ -3,7 +3,17 @@ id: csrf title: CSRF --- -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 on requests, other than those defined as "safe" by RFC7231 \(GET, HEAD, OPTIONS, or TRACE\). When the csrf token is invalid, this middleware will return the `fiber.ErrForbidden` error. When no `_csrf` cookie is set, or the token has expired, a new token will be generated and `_csrf` cookie set. +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 on requests, other than those defined as "safe" by RFC7231 \(GET, HEAD, OPTIONS, or TRACE\). When the csrf token is invalid, this middleware will 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). + +When no `csrf_` cookie is set, or the token has expired, a new token will be generated and `csrf_` cookie set. + +:::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._ + +::: ## Signatures @@ -32,7 +42,7 @@ app.Use(csrf.New()) app.Use(csrf.New(csrf.Config{ KeyLookup: "header:X-Csrf-Token", CookieName: "csrf_", - CookieSameSite: "Strict", + CookieSameSite: "Lax", Expiration: 1 * time.Hour, KeyGenerator: utils.UUID, Extractor: func(c *fiber.Ctx) (string, error) { ... }, @@ -66,7 +76,7 @@ type Config struct { KeyLookup string // Name of the session cookie. This cookie will store session key. - // Optional. Default value "_csrf". + // Optional. Default value "csrf_". CookieName string // Domain of the CSRF cookie. @@ -134,3 +144,14 @@ var ConfigDefault = Config{ KeyGenerator: utils.UUID, } ``` + +### 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, +})) +``` diff --git a/docs/api/middleware/encryptcookie.md b/docs/api/middleware/encryptcookie.md index 9a8f3141f6..5b2d34e9a5 100644 --- a/docs/api/middleware/encryptcookie.md +++ b/docs/api/middleware/encryptcookie.md @@ -65,8 +65,8 @@ type Config struct { // Base64 encoded unique key to encode & decode cookies. // - // Required. Key length should be 32 characters. - // You may use `encryptcookie.GenerateKey()` to generate a new key. + // 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. @@ -85,7 +85,7 @@ type Config struct { ```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 call `encryptcookie.GenerateKey()` to create a random key for you. +// 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", diff --git a/docs/api/middleware/envvar.md b/docs/api/middleware/envvar.md index e72c403ea6..c2eb6794ad 100644 --- a/docs/api/middleware/envvar.md +++ b/docs/api/middleware/envvar.md @@ -35,10 +35,12 @@ 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": ""}, -})) +app.Use("/expose/envvars", envvar.New( + envvar.Config{ + ExportVars: map[string]string{"testKey": "", "testDefaultKey": "testDefaultVal"}, + ExcludeVars: map[string]string{"excludeKey": ""}, + }), +) ``` ### Response diff --git a/docs/api/middleware/filesystem.md b/docs/api/middleware/filesystem.md index 71bdc92972..d0a41a7166 100644 --- a/docs/api/middleware/filesystem.md +++ b/docs/api/middleware/filesystem.md @@ -8,7 +8,7 @@ Filesystem middleware for [Fiber](https://github.com/gofiber/fiber) that enables :::caution **`: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}`** +**To handle paths with spaces (or other url encoded values) make sure to set `fiber.Config{ UnescapePath: true }`** ::: ### Table of Contents @@ -40,7 +40,7 @@ After you initiate your Fiber app, you can use the following possibilities: ```go // Provide a minimal config app.Use(filesystem.New(filesystem.Config{ - Root: http.Dir("./assets") + Root: http.Dir("./assets"), })) // Or extend your config for customization @@ -53,6 +53,54 @@ app.Use(filesystem.New(filesystem.Config{ })) ``` + +> 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:///static/image.png`. + // Without `PathPrefix`, you have to access it via URL: + // `http:///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 [https://github.com/markbates/pkger](https://github.com/markbates/pkger) @@ -72,7 +120,7 @@ func main() { app.Use("/assets", filesystem.New(filesystem.Config{ Root: pkger.Dir("/assets"), - }) + })) log.Fatal(app.Listen(":3000")) } @@ -97,7 +145,7 @@ func main() { app.Use("/assets", filesystem.New(filesystem.Config{ Root: packr.New("Assets Box", "/assets"), - }) + })) log.Fatal(app.Listen(":3000")) } @@ -122,7 +170,7 @@ func main() { app.Use("/assets", filesystem.New(filesystem.Config{ Root: rice.MustFindBox("assets").HTTPBox(), - }) + })) log.Fatal(app.Listen(":3000")) } @@ -147,7 +195,7 @@ func main() { app.Use("/assets", filesystem.New(filesystem.Config{ Root: myEmbeddedFiles.HTTP, - }) + })) log.Fatal(app.Listen(":3000")) } @@ -201,6 +249,14 @@ type Config struct { // 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 @@ -230,6 +286,7 @@ type Config struct { var ConfigDefault = Config{ Next: nil, Root: nil, + PathPrefix: "", Browse: false, Index: "/index.html", MaxAge: 0, diff --git a/docs/api/middleware/limiter.md b/docs/api/middleware/limiter.md index d54cf40329..cc5c23666f 100644 --- a/docs/api/middleware/limiter.md +++ b/docs/api/middleware/limiter.md @@ -3,10 +3,18 @@ id: limiter title: Limiter --- -Limiter middleware for [Fiber](https://github.com/gofiber/fiber) used to limit repeated requests to public APIs and/or endpoints such as password reset etc. Also useful for API clients, web crawling, or other tasks that need to be throttled. +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. + ::: ## Signatures @@ -69,6 +77,17 @@ weightOfPreviousWindpw = previous window's amount request * (whenNewWindow / Exp rate = weightOfPreviousWindpw + current window's amount request. ``` +## 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 @@ -79,7 +98,7 @@ type Config struct { // Optional. Default: nil Next func(c *fiber.Ctx) bool - // Max number of recent connections during `Expiration` seconds before sending a 429 response + // Max number of recent connections during `Duration` seconds before sending a 429 response // // Default: 5 Max int diff --git a/docs/api/middleware/monitor.md b/docs/api/middleware/monitor.md index 66353ea49e..459b47d1e9 100644 --- a/docs/api/middleware/monitor.md +++ b/docs/api/middleware/monitor.md @@ -6,7 +6,9 @@ title: 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) :::caution + Monitor is still in beta, API might change in the future! + ::: ![](https://i.imgur.com/nHAtBpJ.gif) diff --git a/docs/api/middleware/requestid.md b/docs/api/middleware/requestid.md index 7617f76ae9..b1510ca76a 100644 --- a/docs/api/middleware/requestid.md +++ b/docs/api/middleware/requestid.md @@ -66,14 +66,15 @@ type Config struct { ``` ## 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: func() string { - return utils.UUID() - }, - ContextKey: "requestid" + Generator: utils.UUID, + ContextKey: "requestid", } ``` diff --git a/docs/api/middleware/session.md b/docs/api/middleware/session.md index 6c746ceb49..be121326ea 100644 --- a/docs/api/middleware/session.md +++ b/docs/api/middleware/session.md @@ -29,7 +29,9 @@ func (s *Session) Keys() []string ``` :::caution + Storing `interface{}` values are limited to built-ins Go types. + ::: ### Examples @@ -75,6 +77,9 @@ app.Get("/", func(c *fiber.Ctx) error { panic(err) } + // Sets a specific expiration for this session + sess.SetExpiry(time.Second * 2) + // Save session if err := sess.Save(); err != nil { panic(err) @@ -110,9 +115,11 @@ type Config struct { // Optional. Default value memory.New() Storage fiber.Storage - // Name of the session cookie. This cookie will store session key. - // Optional. Default value "session_id". - CookieName string + // KeyLookup is a string in the form of ":" that is used + // to extract session id from the request. + // Possible values: "header:", "query:" or "cookie:" + // Optional. Default value "cookie:session_id". + KeyLookup string // Domain of the cookie. // Optional. Default value "". @@ -142,6 +149,15 @@ type Config struct { // 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 } ``` @@ -150,7 +166,7 @@ type Config struct { ```go var ConfigDefault = Config{ Expiration: 24 * time.Hour, - CookieName: "session_id", + KeyLookup: "cookie:session_id", KeyGenerator: utils.UUID, } ``` diff --git a/docs/api/middleware/timeout.md b/docs/api/middleware/timeout.md index cdd88496bc..aa0f2eb3c4 100644 --- a/docs/api/middleware/timeout.md +++ b/docs/api/middleware/timeout.md @@ -3,7 +3,9 @@ id: timeout title: Timeout --- -Timeout middleware for [Fiber](https://github.com/gofiber/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`. +Timeout middleware for [Fiber](https://github.com/gofiber/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 does not cancel long running executions. Underlying executions must handle timeout by using `context.Context` parameter.