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

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. )

After you initiate your Fiber app, you can use the following possibilities:

  1. // Default config
  2. app.Use(cors.New())
  3. // Or extend your config for customization
  4. app.Use(cors.New(cors.Config{
  5. AllowOrigins: "https://gofiber.io, https://gofiber.net",
  6. AllowHeaders: "Origin, Content-Type, Accept",
  7. }))

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. // AllowOrigin defines a list of origins that may access the resource.
  8. //
  9. // Optional. Default value "*"
  10. AllowOrigins string
  11. // AllowMethods defines a list methods allowed when accessing the resource.
  12. // This is used in response to a preflight request.
  13. //
  14. // Optional. Default value "GET,POST,HEAD,PUT,DELETE,PATCH"
  15. AllowMethods string
  16. // AllowHeaders defines a list of request headers that can be used when
  17. // making the actual request. This is in response to a preflight request.
  18. //
  19. // Optional. Default value "".
  20. AllowHeaders string
  21. // AllowCredentials indicates whether or not the response to the request
  22. // can be exposed when the credentials flag is true. When used as part of
  23. // a response to a preflight request, this indicates whether or not the
  24. // actual request can be made using credentials.
  25. //
  26. // Optional. Default value false.
  27. AllowCredentials bool
  28. // ExposeHeaders defines a whitelist headers that clients are allowed to
  29. // access.
  30. //
  31. // Optional. Default value "".
  32. ExposeHeaders string
  33. // MaxAge indicates how long (in seconds) the results of a preflight request
  34. // can be cached.
  35. //
  36. // Optional. Default value 0.
  37. MaxAge int
  38. }

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. }