CORS

CORS middleware implements CORS specification. CORS gives web servers cross-domain access controls, which enable secure cross-domain data transfers.

Installation

  1. go get -u github.com/gofiber/cors

Signature

  1. cors.New(config ...Config) func(*fiber.Ctx)

Config

PropertyTypeDescriptionDefault
Filterfunc(Ctx) boolDefines a function to skip middlewarenil
AllowOrigins[]stringAllowOrigin defines a list of origins that may access the resource.[]string{““}
AllowMethods[]stringAllowMethods defines a list methods allowed when accessing the resource. This is used in response to a preflight request.[]string{“GET”, “POST”, “HEAD”, “PUT”, “DELETE”, “PATCH”}
AllowCredentialsstringAllowCredentials indicates whether or not the response to the request can be exposed when the credentials flag is true. When used as part of a response to a preflight request, this indicates whether or not the actual request can be made using credentials.nil
ExposeHeaders[]stringExposeHeaders defines a whitelist headers that clients are allowed to access.nil
MaxAgeintMaxAge indicates how long (in seconds) the results of a preflight request can be cached.0
  1. package main
  2.  
  3. import (
  4. "github.com/gofiber/fiber"
  5. "github.com/gofiber/cors"
  6. )
  7.  
  8. func main() {
  9. app := fiber.New()
  10.  
  11. app.Use(cors.New())
  12.  
  13. app.Get("/", func(c *fiber.Ctx) {
  14. c.Send("Welcome!")
  15. })
  16.  
  17. app.Listen(3000)
  18. // curl -H "Origin: http://example.com" --verbose http://localhost:3000
  19. }