CORS net/http middleware for Go
Switch branches/tags
Nothing to show
Clone or download
VojtechVitek Merge pull request #7 from nicksrandall/patch-1
Allow CORs lib to work with AWS Lamba Chi Adapter
Latest commit 07727c8 Aug 16, 2018
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
_example Include _example program Jul 28, 2017
LICENSE Add upstream copyright claim Jul 26, 2018
README.md Update docs to cover inline mux edge case Jan 29, 2018
cors.go Allow CORs to lib to work with AWS Lamv Aug 15, 2018
utils.go Init Apr 27, 2016

README.md

CORS net/http middleware

go-chi/cors is a fork of github.com/rs/cors that provides a net/http compatible middleware for performing preflight CORS checks on the server side. These headers are required for using the browser native Fetch API.

This middleware is designed to be used as a global middleware on the chi router. Applying with within a r.Group() or using With() will not work without routes matching OPTIONS added.

Usage

func main() {
  r := chi.NewRouter()

  // Basic CORS
  // for more ideas, see: https://developer.github.com/v3/#cross-origin-resource-sharing
  cors := cors.New(cors.Options{
    // AllowedOrigins: []string{"https://foo.com"}, // Use this to allow specific origin hosts
    AllowedOrigins:   []string{"*"},
    // AllowOriginFunc:  func(r *http.Request, origin string) bool { return true },
    AllowedMethods:   []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
    AllowedHeaders:   []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
    ExposedHeaders:   []string{"Link"},
    AllowCredentials: true,
    MaxAge:           300, // Maximum value not ignored by any of major browsers
  })
  r.Use(cors.Handler)
  
  r.Get("/", func(w http.ResponseWriter, r *http.Request) {
    w.Write([]byte("welcome"))
  })
  
  http.ListenAndServe(":3000", r)
}