{"id":13481154,"url":"https://github.com/rs/cors","last_synced_at":"2025-05-12T05:24:43.838Z","repository":{"id":22382541,"uuid":"25719147","full_name":"rs/cors","owner":"rs","description":"Go net/http configurable handler to handle CORS requests","archived":false,"fork":false,"pushed_at":"2024-12-12T01:03:34.000Z","size":237,"stargazers_count":2768,"open_issues_count":7,"forks_count":224,"subscribers_count":33,"default_branch":"master","last_synced_at":"2025-05-12T02:41:16.203Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Go","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/rs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2014-10-25T03:49:45.000Z","updated_at":"2025-05-11T14:07:48.000Z","dependencies_parsed_at":"2023-01-13T21:59:18.992Z","dependency_job_id":"874028e1-d8d4-46a2-b1ce-018b8caa406b","html_url":"https://github.com/rs/cors","commit_stats":{"total_commits":131,"total_committers":43,"mean_commits":3.046511627906977,"dds":0.6870229007633588,"last_synced_commit":"1084d89a16921942356d1c831fbe523426cf836e"},"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fcors","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fcors/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fcors/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/rs%2Fcors/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/rs","download_url":"https://codeload.github.com/rs/cors/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253672700,"owners_count":21945480,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-07-31T17:00:49.217Z","updated_at":"2025-05-12T05:24:43.790Z","avatar_url":"https://github.com/rs.png","language":"Go","readme":"# Go CORS handler [![godoc](http://img.shields.io/badge/godoc-reference-blue.svg?style=flat)](https://godoc.org/github.com/rs/cors) [![license](http://img.shields.io/badge/license-MIT-red.svg?style=flat)](https://raw.githubusercontent.com/rs/cors/master/LICENSE) [![Go Coverage](https://github.com/rs/cors/wiki/coverage.svg)](https://raw.githack.com/wiki/rs/cors/coverage.html)\n\nCORS is a `net/http` handler implementing [Cross Origin Resource Sharing W3 specification](http://www.w3.org/TR/cors/) in Golang.\n\n## Getting Started\n\nAfter installing Go and setting up your [GOPATH](http://golang.org/doc/code.html#GOPATH), create your first `.go` file. We'll call it `server.go`.\n\n```go\npackage main\n\nimport (\n    \"net/http\"\n\n    \"github.com/rs/cors\"\n)\n\nfunc main() {\n    mux := http.NewServeMux()\n    mux.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) {\n        w.Header().Set(\"Content-Type\", \"application/json\")\n        w.Write([]byte(\"{\\\"hello\\\": \\\"world\\\"}\"))\n    })\n\n    // cors.Default() setup the middleware with default options being\n    // all origins accepted with simple methods (GET, POST). See\n    // documentation below for more options.\n    handler := cors.Default().Handler(mux)\n    http.ListenAndServe(\":8080\", handler)\n}\n```\n\nInstall `cors`:\n\n    go get github.com/rs/cors\n\nThen run your server:\n\n    go run server.go\n\nThe server now runs on `localhost:8080`:\n\n    $ curl -D - -H 'Origin: http://foo.com' http://localhost:8080/\n    HTTP/1.1 200 OK\n    Access-Control-Allow-Origin: foo.com\n    Content-Type: application/json\n    Date: Sat, 25 Oct 2014 03:43:57 GMT\n    Content-Length: 18\n\n    {\"hello\": \"world\"}\n\n### Allow * With Credentials Security Protection\n\nThis library has been modified to avoid a well known security issue when configured with `AllowedOrigins` to `*` and `AllowCredentials` to `true`. Such setup used to make the library reflects the request `Origin` header value, working around a security protection embedded into the standard that makes clients to refuse such configuration. This behavior has been removed with [#55](https://github.com/rs/cors/issues/55) and [#57](https://github.com/rs/cors/issues/57).\n\nIf you depend on this behavior and understand the implications, you can restore it using the `AllowOriginFunc` with `func(origin string) {return true}`.\n\nPlease refer to [#55](https://github.com/rs/cors/issues/55) for more information about the security implications.\n\n### More Examples\n\n* `net/http`: [examples/nethttp/server.go](https://github.com/rs/cors/blob/master/examples/nethttp/server.go)\n* [Goji](https://goji.io): [examples/goji/server.go](https://github.com/rs/cors/blob/master/examples/goji/server.go)\n* [Martini](http://martini.codegangsta.io): [examples/martini/server.go](https://github.com/rs/cors/blob/master/examples/martini/server.go)\n* [Negroni](https://github.com/codegangsta/negroni): [examples/negroni/server.go](https://github.com/rs/cors/blob/master/examples/negroni/server.go)\n* [Alice](https://github.com/justinas/alice): [examples/alice/server.go](https://github.com/rs/cors/blob/master/examples/alice/server.go)\n* [HttpRouter](https://github.com/julienschmidt/httprouter): [examples/httprouter/server.go](https://github.com/rs/cors/blob/master/examples/httprouter/server.go)\n* [Gorilla](http://www.gorillatoolkit.org/pkg/mux): [examples/gorilla/server.go](https://github.com/rs/cors/blob/master/examples/gorilla/server.go)\n* [Buffalo](https://gobuffalo.io): [examples/buffalo/server.go](https://github.com/rs/cors/blob/master/examples/buffalo/server.go)\n* [Gin](https://gin-gonic.github.io/gin): [examples/gin/server.go](https://github.com/rs/cors/blob/master/examples/gin/server.go)\n* [Chi](https://github.com/go-chi/chi): [examples/chi/server.go](https://github.com/rs/cors/blob/master/examples/chi/server.go)\n\n## Parameters\n\nParameters are passed to the middleware thru the `cors.New` method as follow:\n\n```go\nc := cors.New(cors.Options{\n    AllowedOrigins: []string{\"http://foo.com\", \"http://foo.com:8080\"},\n    AllowCredentials: true,\n    // Enable Debugging for testing, consider disabling in production\n    Debug: true,\n})\n\n// Insert the middleware\nhandler = c.Handler(handler)\n```\n\n* **AllowedOrigins** `[]string`: A list of origins a cross-domain request can be executed from. If the special `*` value is present in the list, all origins will be allowed. An origin may contain a wildcard (`*`) to replace 0 or more characters (i.e.: `http://*.domain.com`). Usage of wildcards implies a small performance penality. Only one wildcard can be used per origin. The default value is `*`.\n* **AllowOriginFunc** `func (origin string) bool`: A custom function to validate the origin. It takes the origin as an argument and returns true if allowed, or false otherwise. If this option is set, the content of `AllowedOrigins` is ignored.\n* **AllowOriginRequestFunc** `func (r *http.Request, origin string) bool`: A custom function to validate the origin. It takes the HTTP Request object and the origin as argument and returns true if allowed or false otherwise. If this option is set, the contents of `AllowedOrigins` and `AllowOriginFunc` are ignored.\nDeprecated: use `AllowOriginVaryRequestFunc` instead.\n* **AllowOriginVaryRequestFunc** `func(r *http.Request, origin string) (bool, []string)`: A custom function to validate the origin. It takes the HTTP Request object and the origin as argument and returns true if allowed or false otherwise with a list of headers used to take that decision if any so they can be added to the Vary header. If this option is set, the contents of `AllowedOrigins`, `AllowOriginFunc` and `AllowOriginRequestFunc` are ignored.\n* **AllowedMethods** `[]string`: A list of methods the client is allowed to use with cross-domain requests. Default value is simple methods (`GET` and `POST`).\n* **AllowedHeaders** `[]string`: A list of non simple headers the client is allowed to use with cross-domain requests.\n* **ExposedHeaders** `[]string`: Indicates which headers are safe to expose to the API of a CORS API specification.\n* **AllowCredentials** `bool`: Indicates whether the request can include user credentials like cookies, HTTP authentication or client side SSL certificates. The default is `false`.\n* **AllowPrivateNetwork** `bool`: Indicates whether to accept cross-origin requests over a private network.\n* **MaxAge** `int`: Indicates how long (in seconds) the results of a preflight request can be cached. The default is `0` which stands for no max age.\n* **OptionsPassthrough** `bool`: Instructs preflight to let other potential next handlers to process the `OPTIONS` method. Turn this on if your application handles `OPTIONS`.\n* **OptionsSuccessStatus** `int`: Provides a status code to use for successful OPTIONS requests. Default value is `http.StatusNoContent` (`204`).\n* **Debug** `bool`: Debugging flag adds additional output to debug server side CORS issues.\n\nSee [API documentation](http://godoc.org/github.com/rs/cors) for more info.\n\n## Benchmarks\n\n```\ngoos: darwin\ngoarch: arm64\npkg: github.com/rs/cors\nBenchmarkWithout-10            \t135325480\t         8.124 ns/op\t       0 B/op\t       0 allocs/op\nBenchmarkDefault-10            \t24082140\t        51.40 ns/op\t       0 B/op\t       0 allocs/op\nBenchmarkAllowedOrigin-10      \t16424518\t        88.25 ns/op\t       0 B/op\t       0 allocs/op\nBenchmarkPreflight-10          \t 8010259\t       147.3 ns/op\t       0 B/op\t       0 allocs/op\nBenchmarkPreflightHeader-10    \t 6850962\t       175.0 ns/op\t       0 B/op\t       0 allocs/op\nBenchmarkWildcard/match-10     \t253275342\t         4.714 ns/op\t       0 B/op\t       0 allocs/op\nBenchmarkWildcard/too_short-10 \t1000000000\t         0.6235 ns/op\t       0 B/op\t       0 allocs/op\nPASS\nok  \tgithub.com/rs/cors\t99.131s\n```\n\n## Licenses\n\nAll source code is licensed under the [MIT License](https://raw.github.com/rs/cors/master/LICENSE).\n","funding_links":[],"categories":["开源类库","Web Frameworks","Misc","Go","Actual middlewares","Web框架","Open source library","Security","中间件","Web 框架","Middlewares","中间件### 中间件","XML","Members"],"sub_categories":["HTTP","Middlewares","中间件","Fail injection","HTTP Print Test","Microsoft Word","版本控制`版本控制相关库`","中間件"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frs%2Fcors","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Frs%2Fcors","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Frs%2Fcors/lists"}