diff --git a/.github/ISSUE_TEMPLATE/bug-report.yaml b/.github/ISSUE_TEMPLATE/bug-report.yaml index 0f7e123505..c48df1dec7 100644 --- a/.github/ISSUE_TEMPLATE/bug-report.yaml +++ b/.github/ISSUE_TEMPLATE/bug-report.yaml @@ -10,15 +10,15 @@ body: value: | ### Notice **This repository is not related to external or third-part Fiber modules. If you have a problem with them, open an issue under their repos. If you think the problem is related to Fiber, open the issue here.** - - Dont't forget you can ask your questions on our [Discord server](https://gofiber.io/discord). - - If you think Fiber doesn't have a nice feature that you think, open the issue with **✏️ Feature Request** template. + - Don't forget you can ask your questions in our [Discord server](https://gofiber.io/discord). + - If you have a suggestion for a Fiber feature you would like to see, open the issue with the **✏️ Feature Request** template. - Write your issue with clear and understandable English. - type: textarea id: description attributes: label: "Bug Description" description: "A clear and detailed description of what the bug is." - placeholder: "Explain your problem as clear and detailed." + placeholder: "Explain your problem clearly and in detail." validations: required: true - type: textarea @@ -39,7 +39,7 @@ body: id: expected-behavior attributes: label: Expected Behavior - description: "A clear and detailed description of what you think should happens." + description: "A clear and detailed description of what you think should happen." placeholder: "Tell us what Fiber should normally do." validations: required: true @@ -56,7 +56,7 @@ body: attributes: label: "Code Snippet (optional)" description: "For some issues, we need to know some parts of your code." - placeholder: "Share a code you think related to the issue." + placeholder: "Share a code snippet that you think is related to the issue." render: go value: | package main diff --git a/.github/ISSUE_TEMPLATE/feature-request.yaml b/.github/ISSUE_TEMPLATE/feature-request.yaml index 733dcc7f02..fbdb871f62 100644 --- a/.github/ISSUE_TEMPLATE/feature-request.yaml +++ b/.github/ISSUE_TEMPLATE/feature-request.yaml @@ -9,15 +9,15 @@ body: attributes: value: | ### Notice - - Dont't forget you can ask your questions on our [Discord server](https://gofiber.io/discord). - - If you think this is just a bug, open the issue with **☢️ Bug Report** template. + - Don't forget you can ask your questions in our [Discord server](https://gofiber.io/discord). + - If you think this is just a bug, open the issue with the **☢️ Bug Report** template. - Write your issue with clear and understandable English. - type: textarea id: description attributes: label: "Feature Description" - description: "A clear and detailed description of the feature we need to do." - placeholder: "Explain your feature as clear and detailed." + description: "A clear and detailed description of the feature you would like to see added." + placeholder: "Explain your feature clearly, and in detail." validations: required: true - type: textarea @@ -31,7 +31,7 @@ body: attributes: label: "Code Snippet (optional)" description: "Code snippet may be really helpful to describe some features." - placeholder: "Share a code to explain the feature better." + placeholder: "Share a code snippet to explain the feature better." render: go value: | package main diff --git a/.github/ISSUE_TEMPLATE/question.yaml b/.github/ISSUE_TEMPLATE/question.yaml index 976c34a6e9..7204183bdb 100644 --- a/.github/ISSUE_TEMPLATE/question.yaml +++ b/.github/ISSUE_TEMPLATE/question.yaml @@ -9,16 +9,16 @@ body: attributes: value: | ### Notice - - Dont't forget you can ask your questions on our [Discord server](https://gofiber.io/discord). - - If you think this is just a bug, open the issue with **☢️ Bug Report** template. - - If you think Fiber doesn't have a nice feature that you think, open the issue with **✏️ Feature Request** template. + - Don't forget you can ask your questions in our [Discord server](https://gofiber.io/discord). + - If you think this is just a bug, open the issue with the **☢️ Bug Report** template. + - If you have a suggestion for a Fiber feature you would like to see, open the issue with the **✏️ Feature Request** template. - Write your issue with clear and understandable English. - type: textarea id: description attributes: label: "Question Description" description: "A clear and detailed description of the question." - placeholder: "Explain your question as clear and detailed." + placeholder: "Explain your question clearly, and in detail." validations: required: true - type: textarea @@ -26,7 +26,7 @@ body: attributes: label: "Code Snippet (optional)" description: "Code snippet may be really helpful to describe some features." - placeholder: "Share a code to explain the feature better." + placeholder: "Share a code snippet to explain the feature better." render: go value: | package main diff --git a/docs/api/middleware/cache.md b/docs/api/middleware/cache.md index 5ffe20ba2d..209865ba3b 100644 --- a/docs/api/middleware/cache.md +++ b/docs/api/middleware/cache.md @@ -128,7 +128,6 @@ type Config struct { ## Default Config ```go -// ConfigDefault is the default config var ConfigDefault = Config{ Next: nil, Expiration: 1 * time.Minute, diff --git a/docs/api/middleware/compress.md b/docs/api/middleware/compress.md index 1ea51f5751..6066ac7246 100644 --- a/docs/api/middleware/compress.md +++ b/docs/api/middleware/compress.md @@ -25,10 +25,10 @@ import ( After you initiate your Fiber app, you can use the following possibilities: ```go -// Default middleware config +// Initialize default config app.Use(compress.New()) -// Provide a custom compression level +// Or extend your config for customization app.Use(compress.New(compress.Config{ Level: compress.LevelBestSpeed, // 1 })) @@ -52,7 +52,7 @@ type Config struct { // Optional. Default: nil Next func(c *fiber.Ctx) bool - // CompressLevel determines the compression algoritm + // Level determines the compression algoritm // // Optional. Default: LevelDefault // LevelDisabled: -1 diff --git a/docs/api/middleware/cors.md b/docs/api/middleware/cors.md index 38783f7ca9..e84f14bfd7 100644 --- a/docs/api/middleware/cors.md +++ b/docs/api/middleware/cors.md @@ -25,7 +25,7 @@ import ( After you initiate your Fiber app, you can use the following possibilities: ```go -// Default config +// Initialize default config app.Use(cors.New()) // Or extend your config for customization @@ -88,12 +88,19 @@ type Config struct { ```go var ConfigDefault = Config{ - Next: nil, - AllowOrigins: "*", - AllowMethods: "GET,POST,HEAD,PUT,DELETE,PATCH", - AllowHeaders: "", - AllowCredentials: false, - ExposeHeaders: "", - MaxAge: 0, + Next: nil, + AllowOrigins: "*", + AllowMethods: strings.Join([]string{ + fiber.MethodGet, + fiber.MethodPost, + fiber.MethodHead, + fiber.MethodPut, + fiber.MethodDelete, + fiber.MethodPatch, + }, ","), + AllowHeaders: "", + AllowCredentials: false, + ExposeHeaders: "", + MaxAge: 0, } ``` diff --git a/docs/api/middleware/csrf.md b/docs/api/middleware/csrf.md index b5982e3b28..d0452a8ece 100644 --- a/docs/api/middleware/csrf.md +++ b/docs/api/middleware/csrf.md @@ -10,9 +10,7 @@ CSRF Tokens are generated on GET requests. You can retrieve the CSRF token with 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._ - +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 @@ -49,7 +47,9 @@ app.Use(csrf.New(csrf.Config{ })) ``` -Note: KeyLookup will be ignored if Extractor is explicitly set. +:::note +KeyLookup will be ignored if Extractor is explicitly set. +::: ## Config @@ -137,14 +137,24 @@ type Config struct { ```go var ConfigDefault = Config{ - KeyLookup: "header:X-Csrf-Token", - CookieName: "csrf_", - CookieSameSite: "Lax", - Expiration: 1 * time.Hour, - KeyGenerator: utils.UUID, + KeyLookup: "header:" + HeaderName, + CookieName: "csrf_", + CookieSameSite: "Lax", + Expiration: 1 * time.Hour, + KeyGenerator: utils.UUID, + ErrorHandler: defaultErrorHandler, + Extractor: CsrfFromHeader(HeaderName), } ``` +## Constants + +```go +const ( + HeaderName = "X-Csrf-Token" +) +``` + ### Custom Storage/Database You can use any storage from our [storage](https://github.com/gofiber/storage/) package. diff --git a/docs/api/middleware/earlydata.md b/docs/api/middleware/earlydata.md index 46da54b573..6b83f1214f 100644 --- a/docs/api/middleware/earlydata.md +++ b/docs/api/middleware/earlydata.md @@ -24,7 +24,7 @@ func New(config ...Config) fiber.Handler ## Examples -First import the middleware from Fiber, +Import the middleware package that is part of the Fiber web framework ```go import ( @@ -33,26 +33,23 @@ import ( ) ``` -Then create a Fiber app with `app := fiber.New()`. - -### Default Config +After you initiate your Fiber app, you can use the following possibilities: ```go +// Initialize default config app.Use(earlydata.New()) -``` -### Custom Config - -```go +// Or extend your config for customization app.Use(earlydata.New(earlydata.Config{ Error: fiber.ErrTooEarly, // ... })) ``` -### Config +## Config ```go +// Config defines the config for middleware. type Config struct { // Next defines a function to skip this middleware when returned true. // @@ -76,12 +73,12 @@ type Config struct { } ``` -### Default Config +## Default Config ```go var ConfigDefault = Config{ IsEarlyData: func(c *fiber.Ctx) bool { - return c.Get("Early-Data") == "1" + return c.Get(DefaultHeaderName) == DefaultHeaderTrueValue }, AllowEarlyData: func(c *fiber.Ctx) bool { @@ -91,3 +88,12 @@ var ConfigDefault = Config{ Error: fiber.ErrTooEarly, } ``` + +## Constants + +```go +const ( + DefaultHeaderName = "Early-Data" + DefaultHeaderTrueValue = "1" +) +``` \ No newline at end of file diff --git a/docs/api/middleware/encryptcookie.md b/docs/api/middleware/encryptcookie.md index 5b2d34e9a5..594df96389 100644 --- a/docs/api/middleware/encryptcookie.md +++ b/docs/api/middleware/encryptcookie.md @@ -29,7 +29,10 @@ import ( After you initiate your Fiber app, you can use the following possibilities: ```go -// Default middleware config +// Provide a minimal config +// `Key` must be a 32 character string. It's used to encrypt 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", })) @@ -52,6 +55,7 @@ app.Post("/", func(c *fiber.Ctx) error { ## Config ```go +// Config defines the config for middleware. type Config struct { // Next defines a function to skip this middleware when returned true. // @@ -84,12 +88,13 @@ type Config struct { ## 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", -})) +var ConfigDefault = Config{ + Next: nil, + Except: []string{"csrf_"}, + Key: "", + Encryptor: EncryptCookie, + Decryptor: DecryptCookie, +} ``` ## Usage of CSRF and Encryptcookie Middlewares with Custom Cookie Names diff --git a/docs/api/middleware/envvar.md b/docs/api/middleware/envvar.md index c2eb6794ad..592a502df4 100644 --- a/docs/api/middleware/envvar.md +++ b/docs/api/middleware/envvar.md @@ -13,7 +13,7 @@ func New(config ...Config) fiber.Handler ## Examples -First import the middleware from Fiber, +Import the middleware package that is part of the Fiber web framework ```go import ( @@ -22,19 +22,13 @@ import ( ) ``` -Then create a Fiber app with `app := fiber.New()`. - -**Note**: You need to provide a path to use envvar middleware. - -### Default Config +After you initiate your Fiber app, you can use the following possibilities: ```go +// Initialize default config app.Use("/expose/envvars", envvar.New()) -``` -### Custom Config - -```go +// Or extend your config for customization app.Use("/expose/envvars", envvar.New( envvar.Config{ ExportVars: map[string]string{"testKey": "", "testDefaultKey": "testDefaultVal"}, @@ -43,7 +37,11 @@ app.Use("/expose/envvars", envvar.New( ) ``` -### Response +:::note +You will need to provide a path to use the envvar middleware. +::: + +## Response Http response contract: ``` diff --git a/docs/api/middleware/etag.md b/docs/api/middleware/etag.md index ee2fa4ee28..b9df4e93fe 100644 --- a/docs/api/middleware/etag.md +++ b/docs/api/middleware/etag.md @@ -24,20 +24,16 @@ import ( After you initiate your Fiber app, you can use the following possibilities: -### Default Config - ```go +// Initialize default config 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 +// Or extend your config for customization app.Use(etag.New(etag.Config{ Weak: true, })) diff --git a/docs/api/middleware/expvar.md b/docs/api/middleware/expvar.md index a4ecb3c421..c2023fbb33 100644 --- a/docs/api/middleware/expvar.md +++ b/docs/api/middleware/expvar.md @@ -11,34 +11,27 @@ Expvar middleware for [Fiber](https://github.com/gofiber/fiber) that serves via func New() fiber.Handler ``` -## Example +## Examples -Import the expvar package that is part of the Fiber web framework +Import the middleware 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" + "github.com/gofiber/fiber/v2" + expvarmw "github.com/gofiber/fiber/v2/middleware/expvar" ) +``` +After you initiate your Fiber app, you can use the following possibilities: +```go 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())) - }) +app.Use(expvarmw.New()) +app.Get("/", func(c *fiber.Ctx) error { + count.Add(1) - fmt.Println(app.Listen(":3000")) -} + return c.SendString(fmt.Sprintf("hello expvar count %d", count.Value())) +}) ``` Visit path `/debug/vars` to see all vars and use query `r=key` to filter exposed variables. diff --git a/docs/api/middleware/favicon.md b/docs/api/middleware/favicon.md index 20fe6682b3..39432d45b9 100644 --- a/docs/api/middleware/favicon.md +++ b/docs/api/middleware/favicon.md @@ -29,7 +29,7 @@ import ( After you initiate your Fiber app, you can use the following possibilities: ```go -// Provide a minimal config +// Initialize default config app.Use(favicon.New()) // Or extend your config for customization @@ -76,10 +76,9 @@ type Config struct { ```go var ConfigDefault = Config{ - Next: nil, - File: "", - URL: "/favicon.ico", - FileSystem: nil, - CacheControl: "public, max-age=31536000", + Next: nil, + File: "", + URL: fPath, + CacheControl: "public, max-age=31536000", } ``` diff --git a/docs/api/middleware/filesystem.md b/docs/api/middleware/filesystem.md index d0a41a7166..a3029f96f1 100644 --- a/docs/api/middleware/filesystem.md +++ b/docs/api/middleware/filesystem.md @@ -11,20 +11,20 @@ Filesystem middleware for [Fiber](https://github.com/gofiber/fiber) that enables **To handle paths with spaces (or other url encoded values) make sure to set `fiber.Config{ UnescapePath: true }`** ::: -### Table of Contents +## Table of Contents * [Signatures](filesystem.md#signatures) * [Examples](filesystem.md#examples) * [Config](filesystem.md#config) * [Default Config](filesystem.md#default-config) -### Signatures +## Signatures ```go func New(config Config) fiber.Handler ``` -### Examples +## Examples Import the middleware package that is part of the Fiber web framework @@ -56,7 +56,7 @@ 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 [Embed](https://golang.org/pkg/embed/) is the native method to embed files in a Golang excecutable. Introduced in Go 1.16. @@ -233,7 +233,7 @@ func main() { } ``` -### Config +## Config ```go // Config defines the config for middleware. @@ -280,7 +280,7 @@ type Config struct { } ``` -### Default Config +## Default Config ```go var ConfigDefault = Config{ diff --git a/docs/api/middleware/idempotency.md b/docs/api/middleware/idempotency.md index 72eee4b4bb..dc0cda8a15 100644 --- a/docs/api/middleware/idempotency.md +++ b/docs/api/middleware/idempotency.md @@ -15,7 +15,7 @@ func New(config ...Config) fiber.Handler ## Examples -First import the middleware from Fiber, +Import the middleware package that is part of the Fiber web framework ```go import ( @@ -24,7 +24,7 @@ import ( ) ``` -Then create a Fiber app with `app := fiber.New()`. +After you initiate your Fiber app, you can use the following possibilities: ### Default Config @@ -44,6 +44,7 @@ app.Use(idempotency.New(idempotency.Config{ ### Config ```go +// Config defines the config for middleware. type Config struct { // Next defines a function to skip this middleware when returned true. // @@ -81,7 +82,7 @@ type Config struct { } ``` -### Default Config +## Default Config ```go var ConfigDefault = Config{ diff --git a/docs/api/middleware/limiter.md b/docs/api/middleware/limiter.md index cc5c23666f..5a88d69f4a 100644 --- a/docs/api/middleware/limiter.md +++ b/docs/api/middleware/limiter.md @@ -6,15 +6,11 @@ title: Limiter 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 @@ -37,7 +33,7 @@ import ( After you initiate your Fiber app, you can use the following possibilities: ```go -// Default middleware config +// Initialize default config app.Use(limiter.New()) // Or extend your config for customization @@ -77,17 +73,6 @@ 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 @@ -144,7 +129,9 @@ type Config struct { } ``` +:::note 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 @@ -163,3 +150,14 @@ var ConfigDefault = Config{ LimiterMiddleware: FixedWindow{}, } ``` + +### 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, +})) +``` \ No newline at end of file diff --git a/docs/api/middleware/logger.md b/docs/api/middleware/logger.md index 1da3342431..1c0860eb2f 100644 --- a/docs/api/middleware/logger.md +++ b/docs/api/middleware/logger.md @@ -10,7 +10,9 @@ Logger middleware for [Fiber](https://github.com/gofiber/fiber) that logs HTTP r func New(config ...Config) fiber.Handler ``` ## Examples -First ensure the appropriate packages are imported + +Import the middleware package that is part of the Fiber web framework + ```go import ( "github.com/gofiber/fiber/v2" @@ -19,45 +21,37 @@ import ( ``` :::tip - The order of registration plays a role. Only all routes that are registered after this one will be logged. The middleware should therefore be one of the first to be registered. - ::: -### Default Config +After you initiate your Fiber app, you can use the following possibilities: + ```go -// Default middleware config +// Initialize default config app.Use(logger.New()) -``` -### Logging remote IP and Port -```go + +// Or extend your config for customization +// Logging remote IP and Port app.Use(logger.New(logger.Config{ Format: "[${ip}]:${port} ${status} - ${method} ${path}\n", })) -``` -### Logging Request ID -```go +// Logging Request ID 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 +// Changing TimeZone & TimeFormat app.Use(logger.New(logger.Config{ Format: "${pid} ${status} - ${method} ${path}\n", TimeFormat: "02-Jan-2006", TimeZone: "America/New_York", })) -``` -### Custom File Writer -```go +// Custom File Writer 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) @@ -66,9 +60,8 @@ defer file.Close() app.Use(logger.New(logger.Config{ Output: file, })) -``` -### Add Custom Tags -```go + +// Add Custom Tags 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) { @@ -76,11 +69,8 @@ app.Use(logger.New(logger.Config{ }, }, })) -``` -### Callback after log is written - -```go +// Callback after log is written app.Use(logger.New(logger.Config{ TimeFormat: time.RFC3339Nano, TimeZone: "Asia/Shanghai", @@ -100,48 +90,60 @@ type Config struct { // // 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 + + enableColors bool + enableLatency bool + timeZoneLocation *time.Location } 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, + Next: nil, + Done: nil, + Format: "[${time}] ${status} - ${latency} ${method} ${path}\n", + TimeFormat: "15:04:05", + TimeZone: "Local", + TimeInterval: 500 * time.Millisecond, + Output: os.Stdout, + enableColors: true, } ``` diff --git a/docs/api/middleware/monitor.md b/docs/api/middleware/monitor.md index 459b47d1e9..4ecdca647d 100644 --- a/docs/api/middleware/monitor.md +++ b/docs/api/middleware/monitor.md @@ -19,24 +19,24 @@ func New() fiber.Handler ``` ### Examples -Import the middleware package and assign it to a route. -```go -package main +Import the middleware package that is part of the Fiber web framework +```go import ( - "log" - - "github.com/gofiber/fiber/v2" - "github.com/gofiber/fiber/v2/middleware/monitor" + "github.com/gofiber/fiber/v2" + "github.com/gofiber/fiber/v2/middleware/favicon" ) +``` -func main() { - app := fiber.New() - - app.Get("/metrics", monitor.New(monitor.Config{Title: "MyService Metrics Page"})) +After you initiate your Fiber app, you can use the following possibilities: +```go +// Initialize default config (Assign the middleware to /metrics) +app.Get("/metrics", monitor.New()) - log.Fatal(app.Listen(":3000")) -} +// Or extend your config for customization +// Assign the middleware to /metrics +// and change the Title to `MyService Metrics Page` +app.Get("/metrics", monitor.New(monitor.Config{Title: "MyService Metrics Page"})) ``` You can also access the API endpoint with `curl -X GET -H "Accept: application/json" http://localhost:3000/metrics` which returns: @@ -51,42 +51,42 @@ You can also access the API endpoint with ```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 + // Metrics page title // - // Optional. Default: https://cdn.jsdelivr.net/npm/chart.js@2.9/dist/Chart.bundle.min.js + // 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 + index string } ``` @@ -94,13 +94,19 @@ type Config struct { ```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" - + Title: defaultTitle, + Refresh: defaultRefresh, + FontURL: defaultFontURL, + ChartJsURL: defaultChartJSURL, + CustomHead: defaultCustomHead, + APIOnly: false, + Next: nil, + index: newIndex(viewBag{ + defaultTitle, + defaultRefresh, + defaultFontURL, + defaultChartJSURL, + defaultCustomHead, + }), } ``` diff --git a/docs/api/middleware/pprof.md b/docs/api/middleware/pprof.md index fbcb47e6a0..c56971e566 100644 --- a/docs/api/middleware/pprof.md +++ b/docs/api/middleware/pprof.md @@ -28,19 +28,16 @@ import ( After you initiate your Fiber app, you can use the following possibilities: ```go -// Default middleware +// Initialize default config app.Use(pprof.New()) -``` -In systems where you have multiple ingress endpoints, it is common to add a URL prefix, like so: +// Or extend your config for customization -```go -// Default middleware +// For example, in systems where you have multiple ingress endpoints, it is common to add a URL prefix, like so: 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/". +// This prefix will be added to the default path of "/debug/pprof/", for a resulting URL of: "/endpoint-prefix/debug/pprof/". +``` ## Config diff --git a/docs/api/middleware/proxy.md b/docs/api/middleware/proxy.md index 3ca54dad48..3179414036 100644 --- a/docs/api/middleware/proxy.md +++ b/docs/api/middleware/proxy.md @@ -193,7 +193,6 @@ type Config struct { ## Default Config ```go -// ConfigDefault is the default config var ConfigDefault = Config{ Next: nil, ModifyRequest: nil, diff --git a/docs/api/middleware/recover.md b/docs/api/middleware/recover.md index 89013ed3d8..e60703f2de 100644 --- a/docs/api/middleware/recover.md +++ b/docs/api/middleware/recover.md @@ -25,10 +25,10 @@ import ( After you initiate your Fiber app, you can use the following possibilities: ```go -// Default middleware config +// Initialize default config app.Use(recover.New()) -// This panic will be catch by the middleware +// This panic will be caught by the middleware app.Get("/", func(c *fiber.Ctx) error { panic("I'm an error") }) diff --git a/docs/api/middleware/requestid.md b/docs/api/middleware/requestid.md index b1510ca76a..aafbd1799e 100644 --- a/docs/api/middleware/requestid.md +++ b/docs/api/middleware/requestid.md @@ -25,7 +25,7 @@ import ( After you initiate your Fiber app, you can use the following possibilities: ```go -// Default middleware config +// Initialize default config app.Use(requestid.New()) // Or extend your config for customization diff --git a/docs/api/middleware/session.md b/docs/api/middleware/session.md index be121326ea..f27eaf42bc 100644 --- a/docs/api/middleware/session.md +++ b/docs/api/middleware/session.md @@ -29,12 +29,10 @@ func (s *Session) Keys() []string ``` :::caution - Storing `interface{}` values are limited to built-ins Go types. - ::: -### Examples +## Examples Import the middleware package that is part of the Fiber web framework ```go import ( @@ -43,16 +41,13 @@ import ( ) ``` -Then create a Fiber app with `app := fiber.New()`. - -### Default Configuration +After you initiate your Fiber app, you can use the following possibilities: ```go +// Initialize default config // This stores all of your app's sessions -// Default middleware config store := session.New() -// This panic will be caught by the middleware app.Get("/", func(c *fiber.Ctx) error { // Get session from storage sess, err := store.Get(c) @@ -89,19 +84,6 @@ app.Get("/", func(c *fiber.Ctx) error { }) ``` -### 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 store, see the above example. - ## Config ```go @@ -121,23 +103,23 @@ type Config struct { // Optional. Default value "cookie:session_id". KeyLookup string - // Domain of the cookie. + // Domain of the CSRF cookie. // Optional. Default value "". CookieDomain string - // Path of the cookie. + // Path of the CSRF cookie. // Optional. Default value "". CookiePath string - // Indicates if cookie is secure. + // Indicates if CSRF cookie is secure. // Optional. Default value false. CookieSecure bool - // Indicates if cookie is HTTP only. + // Indicates if CSRF cookie is HTTP only. // Optional. Default value false. CookieHTTPOnly bool - // Sets the cookie SameSite attribute. + // Value of SameSite cookie. // Optional. Default value "Lax". CookieSameSite string @@ -147,14 +129,14 @@ type Config struct { CookieSessionOnly bool // KeyGenerator generates the session key. - // Optional. Default value utils.UUID + // Optional. Default value utils.UUIDv4 KeyGenerator func() string // Deprecated: Please use KeyLookup CookieName string // Source defines where to obtain the session id - source Source + source Source // The session name sessionName string @@ -167,6 +149,31 @@ type Config struct { var ConfigDefault = Config{ Expiration: 24 * time.Hour, KeyLookup: "cookie:session_id", - KeyGenerator: utils.UUID, + KeyGenerator: utils.UUIDv4, + source: "cookie", + sessionName: "session_id", } ``` + +## Constants + +```go +const ( + SourceCookie Source = "cookie" + SourceHeader Source = "header" + SourceURLQuery Source = "query" +) +``` + +### 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 store, see the [Examples](#examples). \ No newline at end of file diff --git a/docs/api/middleware/skip.md b/docs/api/middleware/skip.md index 17e19b7e77..1c026715fe 100644 --- a/docs/api/middleware/skip.md +++ b/docs/api/middleware/skip.md @@ -5,12 +5,12 @@ title: Skip Skip middleware for [Fiber](https://github.com/gofiber/fiber) that skips a wrapped handler if a predicate is true. -### Signatures +## Signatures ```go func New(handler fiber.Handler, exclude func(c *fiber.Ctx) bool) fiber.Handler ``` -### Examples +## Examples Import the middleware package that is part of the Fiber web framework ```go import ( @@ -20,6 +20,27 @@ import ( ``` 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 })) +func main() { + app := fiber.New() + + app.Use(skip.New(BasicHandler, func(ctx *fiber.Ctx) bool { + return ctx.Method() == fiber.MethodGet + })) + + app.Get("/", func(ctx *fiber.Ctx) error { + return ctx.SendString("It was a GET request!") + }) + + app.Listen(":3000") +} + +func BasicHandler(ctx *fiber.Ctx) error { + return ctx.SendString("It was not a GET request!") +} ``` + +:::tip +app.Use will handle requests from any route, and any method. In the example above, it will only skip if the method is GET. +::: \ No newline at end of file diff --git a/docs/api/middleware/timeout.md b/docs/api/middleware/timeout.md index 7f8adf9336..3caa2c2f26 100644 --- a/docs/api/middleware/timeout.md +++ b/docs/api/middleware/timeout.md @@ -7,13 +7,15 @@ There exist two distinct implementations of timeout middleware [Fiber](https://g **New** - Wraps a `fiber.Handler` with a timeout. If the handler takes longer than the given duration to return, the timeout error is set and forwarded to the centralized [ErrorHandler](https://docs.gofiber.io/error-handling). +Wraps a `fiber.Handler` with a timeout. If the handler takes longer than the given duration to return, the timeout error is set and forwarded to the centralized [ErrorHandler](https://docs.gofiber.io/error-handling). - Note: This has been depreciated since it raises race conditions. +:::caution +This has been deprecated since it raises race conditions. +::: **NewWithContext** - As a `fiber.Handler` wrapper, it creates a context with `context.WithTimeout` and pass it in `UserContext`. +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`. @@ -39,11 +41,12 @@ import ( ) ``` -Sample timeout middleware usage: +After you initiate your Fiber app, you can use the following possibilities: ```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 { @@ -53,7 +56,8 @@ func main() { } app.Get("/foo/:sleepTime", timeout.New(h, 2*time.Second)) - _ = app.Listen(":3000") + + app.Listen(":3000") } func sleepWithContext(ctx context.Context, d time.Duration) error { @@ -99,7 +103,7 @@ func main() { } app.Get("/foo/:sleepTime", timeout.NewWithContext(h, 2*time.Second, ErrFooTimeOut)) - _ = app.Listen(":3000") + app.Listen(":3000") } func sleepWithContextWithCustomError(ctx context.Context, d time.Duration) error {