Skip to content

Commit 1f52799

Browse files
committed
Refresh middleware documentation
1 parent f0582a5 commit 1f52799

File tree

10 files changed

+156
-28
lines changed

10 files changed

+156
-28
lines changed

docs/api/middleware/cache.md

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ app.Use(New(Config{
5151
return time.Second * time.Duration(newCacheTime)
5252
},
5353
KeyGenerator: func(c *fiber.Ctx) string {
54-
return c.Path()
54+
return utils.CopyString(c.Path())
5555
}
5656
}))
5757

@@ -76,6 +76,13 @@ type Config struct {
7676
// Optional. Default: 1 * time.Minute
7777
Expiration time.Duration
7878

79+
// CacheHeader header on response header, indicate cache status, with the following possible return value
80+
//
81+
// hit, miss, unreachable
82+
//
83+
// Optional. Default: X-Cache
84+
CacheHeader string
85+
7986
// CacheControl enables client side caching if set to true
8087
//
8188
// Optional. Default: false
@@ -125,6 +132,7 @@ type Config struct {
125132
var ConfigDefault = Config{
126133
Next: nil,
127134
Expiration: 1 * time.Minute,
135+
CacheHeader: "X-Cache",
128136
CacheControl: false,
129137
KeyGenerator: func(c *fiber.Ctx) string {
130138
return utils.CopyString(c.Path())

docs/api/middleware/csrf.md

Lines changed: 24 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,17 @@ id: csrf
33
title: CSRF
44
---
55

6-
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.
6+
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.
7+
8+
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).
9+
10+
When no `csrf_` cookie is set, or the token has expired, a new token will be generated and `csrf_` cookie set.
11+
12+
:::note
13+
14+
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._
15+
16+
:::
717

818
## Signatures
919

@@ -32,7 +42,7 @@ app.Use(csrf.New())
3242
app.Use(csrf.New(csrf.Config{
3343
KeyLookup: "header:X-Csrf-Token",
3444
CookieName: "csrf_",
35-
CookieSameSite: "Strict",
45+
CookieSameSite: "Lax",
3646
Expiration: 1 * time.Hour,
3747
KeyGenerator: utils.UUID,
3848
Extractor: func(c *fiber.Ctx) (string, error) { ... },
@@ -66,7 +76,7 @@ type Config struct {
6676
KeyLookup string
6777

6878
// Name of the session cookie. This cookie will store session key.
69-
// Optional. Default value "_csrf".
79+
// Optional. Default value "csrf_".
7080
CookieName string
7181

7282
// Domain of the CSRF cookie.
@@ -134,3 +144,14 @@ var ConfigDefault = Config{
134144
KeyGenerator: utils.UUID,
135145
}
136146
```
147+
148+
### Custom Storage/Database
149+
150+
You can use any storage from our [storage](https://github.com/gofiber/storage/) package.
151+
152+
```go
153+
storage := sqlite3.New() // From github.com/gofiber/storage/sqlite3
154+
app.Use(csrf.New(csrf.Config{
155+
Storage: storage,
156+
}))
157+
```

docs/api/middleware/encryptcookie.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,8 @@ type Config struct {
6565

6666
// Base64 encoded unique key to encode & decode cookies.
6767
//
68-
// Required. Key length should be 32 characters.
69-
// You may use `encryptcookie.GenerateKey()` to generate a new key.
68+
// Required. The key should be 32 bytes of random data in base64-encoded form.
69+
// You may run `openssl rand -base64 32` or use `encryptcookie.GenerateKey()` to generate a new key.
7070
Key string
7171

7272
// Custom function to encrypt cookies.
@@ -85,7 +85,7 @@ type Config struct {
8585

8686
```go
8787
// `Key` must be a 32 character string. It's used to encrpyt the values, so make sure it is random and keep it secret.
88-
// You can call `encryptcookie.GenerateKey()` to create a random key for you.
88+
// You can run `openssl rand -base64 32` or call `encryptcookie.GenerateKey()` to create a random key for you.
8989
// Make sure not to set `Key` to `encryptcookie.GenerateKey()` because that will create a new key every run.
9090
app.Use(encryptcookie.New(encryptcookie.Config{
9191
Key: "secret-thirty-2-character-string",

docs/api/middleware/envvar.md

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,10 +35,12 @@ app.Use("/expose/envvars", envvar.New())
3535
### Custom Config
3636

3737
```go
38-
app.Use("/expose/envvars", envvar.New(envvar.Config{
39-
ExportVars: map[string]string{"testKey": "", "testDefaultKey": "testDefaultVal"},
40-
ExcludeVars: map[string]string{"excludeKey": ""},
41-
}))
38+
app.Use("/expose/envvars", envvar.New(
39+
envvar.Config{
40+
ExportVars: map[string]string{"testKey": "", "testDefaultKey": "testDefaultVal"},
41+
ExcludeVars: map[string]string{"excludeKey": ""},
42+
}),
43+
)
4244
```
4345

4446
### Response

docs/api/middleware/filesystem.md

Lines changed: 63 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ Filesystem middleware for [Fiber](https://github.com/gofiber/fiber) that enables
88
:::caution
99
**`:params` & `:optionals?` within the prefix path are not supported!**
1010

11-
**To handle paths with spaces (or other url encoded values) make sure to set `fiber.Config{ UnescapePath: true}`**
11+
**To handle paths with spaces (or other url encoded values) make sure to set `fiber.Config{ UnescapePath: true }`**
1212
:::
1313

1414
### Table of Contents
@@ -40,7 +40,7 @@ After you initiate your Fiber app, you can use the following possibilities:
4040
```go
4141
// Provide a minimal config
4242
app.Use(filesystem.New(filesystem.Config{
43-
Root: http.Dir("./assets")
43+
Root: http.Dir("./assets"),
4444
}))
4545

4646
// Or extend your config for customization
@@ -53,6 +53,54 @@ app.Use(filesystem.New(filesystem.Config{
5353
}))
5454
```
5555

56+
57+
> 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.
58+
59+
### embed
60+
61+
[Embed](https://golang.org/pkg/embed/) is the native method to embed files in a Golang excecutable. Introduced in Go 1.16.
62+
63+
```go
64+
package main
65+
66+
import (
67+
"embed"
68+
"io/fs"
69+
"log"
70+
"net/http"
71+
72+
"github.com/gofiber/fiber/v2"
73+
"github.com/gofiber/fiber/v2/middleware/filesystem"
74+
)
75+
76+
// Embed a single file
77+
//go:embed index.html
78+
var f embed.FS
79+
80+
// Embed a directory
81+
//go:embed static/*
82+
var embedDirStatic embed.FS
83+
84+
func main() {
85+
app := fiber.New()
86+
87+
app.Use("/", filesystem.New(filesystem.Config{
88+
Root: http.FS(f),
89+
}))
90+
91+
// Access file "image.png" under `static/` directory via URL: `http://<server>/static/image.png`.
92+
// Without `PathPrefix`, you have to access it via URL:
93+
// `http://<server>/static/static/image.png`.
94+
app.Use("/static", filesystem.New(filesystem.Config{
95+
Root: http.FS(embedDirStatic),
96+
PathPrefix: "static",
97+
Browse: true,
98+
}))
99+
100+
log.Fatal(app.Listen(":3000"))
101+
}
102+
```
103+
56104
## pkger
57105

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

73121
app.Use("/assets", filesystem.New(filesystem.Config{
74122
Root: pkger.Dir("/assets"),
75-
})
123+
}))
76124

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

98146
app.Use("/assets", filesystem.New(filesystem.Config{
99147
Root: packr.New("Assets Box", "/assets"),
100-
})
148+
}))
101149

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

123171
app.Use("/assets", filesystem.New(filesystem.Config{
124172
Root: rice.MustFindBox("assets").HTTPBox(),
125-
})
173+
}))
126174

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

148196
app.Use("/assets", filesystem.New(filesystem.Config{
149197
Root: myEmbeddedFiles.HTTP,
150-
})
198+
}))
151199

152200
log.Fatal(app.Listen(":3000"))
153201
}
@@ -201,6 +249,14 @@ type Config struct {
201249
// Required. Default: nil
202250
Root http.FileSystem `json:"-"`
203251

252+
// PathPrefix defines a prefix to be added to a filepath when
253+
// reading a file from the FileSystem.
254+
//
255+
// Use when using Go 1.16 embed.FS
256+
//
257+
// Optional. Default ""
258+
PathPrefix string `json:"path_prefix"`
259+
204260
// Enable directory browsing.
205261
//
206262
// Optional. Default: false
@@ -230,6 +286,7 @@ type Config struct {
230286
var ConfigDefault = Config{
231287
Next: nil,
232288
Root: nil,
289+
PathPrefix: "",
233290
Browse: false,
234291
Index: "/index.html",
235292
MaxAge: 0,

docs/api/middleware/limiter.md

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,18 @@ id: limiter
33
title: Limiter
44
---
55

6-
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.
6+
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.
77

88
:::note
9+
10+
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.
11+
12+
:::
13+
14+
:::note
15+
916
This module does not share state with other processes/servers by default.
17+
1018
:::
1119

1220
## Signatures
@@ -69,6 +77,17 @@ weightOfPreviousWindpw = previous window's amount request * (whenNewWindow / Exp
6977
rate = weightOfPreviousWindpw + current window's amount request.
7078
```
7179

80+
## Custom Storage/Database
81+
82+
You can use any storage from our [storage](https://github.com/gofiber/storage/) package.
83+
84+
```go
85+
storage := sqlite3.New() // From github.com/gofiber/storage/sqlite3
86+
app.Use(limiter.New(limiter.Config{
87+
Storage: storage,
88+
}))
89+
```
90+
7291
## Config
7392

7493
```go
@@ -79,7 +98,7 @@ type Config struct {
7998
// Optional. Default: nil
8099
Next func(c *fiber.Ctx) bool
81100

82-
// Max number of recent connections during `Expiration` seconds before sending a 429 response
101+
// Max number of recent connections during `Duration` seconds before sending a 429 response
83102
//
84103
// Default: 5
85104
Max int

docs/api/middleware/monitor.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,9 @@ title: Monitor
66
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)
77

88
:::caution
9+
910
Monitor is still in beta, API might change in the future!
11+
1012
:::
1113

1214
![](https://i.imgur.com/nHAtBpJ.gif)

docs/api/middleware/requestid.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,14 +66,15 @@ type Config struct {
6666
```
6767

6868
## Default Config
69+
The default config uses a fast UUID generator which will expose the number of
70+
requests made to the server. To conceal this value for better privacy, use the
71+
`utils.UUIDv4` generator.
6972

7073
```go
7174
var ConfigDefault = Config{
7275
Next: nil,
7376
Header: fiber.HeaderXRequestID,
74-
Generator: func() string {
75-
return utils.UUID()
76-
},
77-
ContextKey: "requestid"
77+
Generator: utils.UUID,
78+
ContextKey: "requestid",
7879
}
7980
```

docs/api/middleware/session.md

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,9 @@ func (s *Session) Keys() []string
2929
```
3030

3131
:::caution
32+
3233
Storing `interface{}` values are limited to built-ins Go types.
34+
3335
:::
3436
3537
### Examples
@@ -75,6 +77,9 @@ app.Get("/", func(c *fiber.Ctx) error {
7577
panic(err)
7678
}
7779

80+
// Sets a specific expiration for this session
81+
sess.SetExpiry(time.Second * 2)
82+
7883
// Save session
7984
if err := sess.Save(); err != nil {
8085
panic(err)
@@ -110,9 +115,11 @@ type Config struct {
110115
// Optional. Default value memory.New()
111116
Storage fiber.Storage
112117

113-
// Name of the session cookie. This cookie will store session key.
114-
// Optional. Default value "session_id".
115-
CookieName string
118+
// KeyLookup is a string in the form of "<source>:<name>" that is used
119+
// to extract session id from the request.
120+
// Possible values: "header:<name>", "query:<name>" or "cookie:<name>"
121+
// Optional. Default value "cookie:session_id".
122+
KeyLookup string
116123

117124
// Domain of the cookie.
118125
// Optional. Default value "".
@@ -142,6 +149,15 @@ type Config struct {
142149
// KeyGenerator generates the session key.
143150
// Optional. Default value utils.UUID
144151
KeyGenerator func() string
152+
153+
// Deprecated: Please use KeyLookup
154+
CookieName string
155+
156+
// Source defines where to obtain the session id
157+
source Source
158+
159+
// The session name
160+
sessionName string
145161
}
146162
```
147163

@@ -150,7 +166,7 @@ type Config struct {
150166
```go
151167
var ConfigDefault = Config{
152168
Expiration: 24 * time.Hour,
153-
CookieName: "session_id",
169+
KeyLookup: "cookie:session_id",
154170
KeyGenerator: utils.UUID,
155171
}
156172
```

docs/api/middleware/timeout.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,9 @@ id: timeout
33
title: Timeout
44
---
55

6-
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`.
6+
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`.
7+
8+
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`.
79

810
It does not cancel long running executions. Underlying executions must handle timeout by using `context.Context` parameter.
911

0 commit comments

Comments
 (0)