Skip to content

Commit

Permalink
Refresh middleware documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
ReneWerner87 committed Mar 24, 2023
1 parent f0582a5 commit 1f52799
Show file tree
Hide file tree
Showing 10 changed files with 156 additions and 28 deletions.
10 changes: 9 additions & 1 deletion docs/api/middleware/cache.md
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}))

Expand All @@ -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
Expand Down Expand Up @@ -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())
Expand Down
27 changes: 24 additions & 3 deletions docs/api/middleware/csrf.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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) { ... },
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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,
}))
```
6 changes: 3 additions & 3 deletions docs/api/middleware/encryptcookie.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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",
Expand Down
10 changes: 6 additions & 4 deletions docs/api/middleware/envvar.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
69 changes: 63 additions & 6 deletions docs/api/middleware/filesystem.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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://<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

[https://github.com/markbates/pkger](https://github.com/markbates/pkger)
Expand All @@ -72,7 +120,7 @@ func main() {

app.Use("/assets", filesystem.New(filesystem.Config{
Root: pkger.Dir("/assets"),
})
}))

log.Fatal(app.Listen(":3000"))
}
Expand All @@ -97,7 +145,7 @@ func main() {

app.Use("/assets", filesystem.New(filesystem.Config{
Root: packr.New("Assets Box", "/assets"),
})
}))

log.Fatal(app.Listen(":3000"))
}
Expand All @@ -122,7 +170,7 @@ func main() {

app.Use("/assets", filesystem.New(filesystem.Config{
Root: rice.MustFindBox("assets").HTTPBox(),
})
}))

log.Fatal(app.Listen(":3000"))
}
Expand All @@ -147,7 +195,7 @@ func main() {

app.Use("/assets", filesystem.New(filesystem.Config{
Root: myEmbeddedFiles.HTTP,
})
}))

log.Fatal(app.Listen(":3000"))
}
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -230,6 +286,7 @@ type Config struct {
var ConfigDefault = Config{
Next: nil,
Root: nil,
PathPrefix: "",
Browse: false,
Index: "/index.html",
MaxAge: 0,
Expand Down
23 changes: 21 additions & 2 deletions docs/api/middleware/limiter.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down
2 changes: 2 additions & 0 deletions docs/api/middleware/monitor.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
9 changes: 5 additions & 4 deletions docs/api/middleware/requestid.md
Original file line number Diff line number Diff line change
Expand Up @@ -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",
}
```
24 changes: 20 additions & 4 deletions docs/api/middleware/session.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@ func (s *Session) Keys() []string
```

:::caution

Storing `interface{}` values are limited to built-ins Go types.
:::
### Examples
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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 "<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 "".
Expand Down Expand Up @@ -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
}
```

Expand All @@ -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,
}
```
4 changes: 3 additions & 1 deletion docs/api/middleware/timeout.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down

0 comments on commit 1f52799

Please sign in to comment.