README.md
1# CORS net/http middleware
2
3[go-chi/cors](https://github.com/go-chi/cors) is a fork of [github.com/rs/cors](https://github.com/rs/cors) that
4provides a `net/http` compatible middleware for performing preflight CORS checks on the server side. These headers
5are required for using the browser native [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API).
6
7This middleware is designed to be used as a top-level middleware on the [chi](https://github.com/go-chi/chi) router.
8Applying with within a `r.Group()` or using `With()` will not work without routes matching `OPTIONS` added.
9
10## Usage
11
12```go
13func main() {
14 r := chi.NewRouter()
15
16 // Basic CORS
17 // for more ideas, see: https://developer.github.com/v3/#cross-origin-resource-sharing
18 r.Use(cors.Handler(cors.Options{
19 // AllowedOrigins: []string{"https://foo.com"}, // Use this to allow specific origin hosts
20 AllowedOrigins: []string{"https://*", "http://*"},
21 // AllowOriginFunc: func(r *http.Request, origin string) bool { return true },
22 AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
23 AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
24 ExposedHeaders: []string{"Link"},
25 AllowCredentials: false,
26 MaxAge: 300, // Maximum value not ignored by any of major browsers
27 }))
28
29 r.Get("/", func(w http.ResponseWriter, r *http.Request) {
30 w.Write([]byte("welcome"))
31 })
32
33 http.ListenAndServe(":3000", r)
34}
35```
36
37## Credits
38
39All credit for the original work of this middleware goes out to [github.com/rs](github.com/rs).
40