CORS
CORS middleware for Fiber that that can be used to enable Cross-Origin Resource Sharing with various options.

Table of Contents

Signatures

1
func New(config ...Config) fiber.Handler
Copied!

Examples

Import the middleware package that is part of the Fiber web framework
1
import (
2
"github.com/gofiber/fiber/v2"
3
"github.com/gofiber/fiber/v2/middleware/cors"
4
)
Copied!
After you initiate your Fiber app, you can use the following possibilities:
1
// Default config
2
app.Use(cors.New())
3
​
4
// Or extend your config for customization
5
app.Use(cors.New(cors.Config{
6
AllowOrigins: "https://gofiber.io, https://gofiber.net",
7
AllowHeaders: "Origin, Content-Type, Accept",
8
}))
Copied!

Config

1
// Config defines the config for middleware.
2
type Config struct {
3
// Next defines a function to skip this middleware when returned true.
4
//
5
// Optional. Default: nil
6
Next func(c *fiber.Ctx) bool
7
​
8
// AllowOrigin defines a list of origins that may access the resource.
9
//
10
// Optional. Default value "*"
11
AllowOrigins string
12
​
13
// AllowMethods defines a list methods allowed when accessing the resource.
14
// This is used in response to a preflight request.
15
//
16
// Optional. Default value "GET,POST,HEAD,PUT,DELETE,PATCH"
17
AllowMethods string
18
​
19
// AllowHeaders defines a list of request headers that can be used when
20
// making the actual request. This is in response to a preflight request.
21
//
22
// Optional. Default value "".
23
AllowHeaders string
24
​
25
// AllowCredentials indicates whether or not the response to the request
26
// can be exposed when the credentials flag is true. When used as part of
27
// a response to a preflight request, this indicates whether or not the
28
// actual request can be made using credentials.
29
//
30
// Optional. Default value false.
31
AllowCredentials bool
32
​
33
// ExposeHeaders defines a whitelist headers that clients are allowed to
34
// access.
35
//
36
// Optional. Default value "".
37
ExposeHeaders string
38
​
39
// MaxAge indicates how long (in seconds) the results of a preflight request
40
// can be cached.
41
//
42
// Optional. Default value 0.
43
MaxAge int
44
}
Copied!

Default Config

1
var ConfigDefault = Config{
2
Next: nil,
3
AllowOrigins: "*",
4
AllowMethods: "GET,POST,HEAD,PUT,DELETE,PATCH",
5
AllowHeaders: "",
6
AllowCredentials: false,
7
ExposeHeaders: "",
8
MaxAge: 0,
9
}
Copied!
Last modified 7mo ago