rs/cors
GitHub: rs/cors
一个遵循 W3C 规范的 Go 语言 CORS 中间件,为 net/http 及主流 Web 框架提供可配置的跨域请求处理能力。
Stars: 2893 | Forks: 232
# Go CORS handler [](https://godoc.org/github.com/rs/cors) [](https://raw.githubusercontent.com/rs/cors/master/LICENSE) [](https://raw.githack.com/wiki/rs/cors/coverage.html)
CORS 是一个用 Golang 实现的 `net/http` handler,遵循 [Cross Origin Resource Sharing W3 specification](http://www.w3.org/TR/cors/)。
## 入门指南
安装好 Go 并配置好你的 [GOPATH](http://golang.org/doc/code.html#GOPATH) 之后,创建你的第一个 `.go` 文件。我们将其命名为 `server.go`。
```
package main
import (
"net/http"
"github.com/rs/cors"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("{\"hello\": \"world\"}"))
})
// cors.Default() setup the middleware with default options being
// all origins accepted with simple methods (GET, POST). See
// documentation below for more options.
handler := cors.Default().Handler(mux)
http.ListenAndServe(":8080", handler)
}
```
安装 `cors`:
```
go get github.com/rs/cors
```
然后运行你的服务器:
```
go run server.go
```
服务器现在运行在 `localhost:8080` 上:
```
$ curl -D - -H 'Origin: http://foo.com' http://localhost:8080/
HTTP/1.1 200 OK
Access-Control-Allow-Origin: foo.com
Content-Type: application/json
Date: Sat, 25 Oct 2014 03:43:57 GMT
Content-Length: 18
{"hello": "world"}
```
### 允许 * 带凭据的安全保护
该库已被修改,以避免在配置 `AllowedOrigins` 为 `*` 且 `AllowCredentials` 为 `true` 时出现的一个众所周知的安全问题。这种设置曾经会让库直接反射请求的 `Origin` header 值,从而绕过标准中内置的安全保护(该保护使得客户端拒绝此类配置)。此行为已通过 [#55](https://github.com/rs/cors/issues/55) 和 [#57](https://github.com/rs/cors/issues/57) 移除。
如果你依赖此行为并且了解其带来的影响,你可以使用 `AllowOriginFunc` 并传入 `func(origin string) {return true}` 来恢复它。
有关安全影响的更多信息,请参阅 [#55](https://github.com/rs/cors/issues/55)。
### 更多示例
* `net/http`:[examples/nethttp/server.go](https://github.com/rs/cors/blob/master/examples/nethttp/server.go)
* [Goji](https://goji.io):[examples/goji/server.go](https://github.com/rs/cors/blob/master/examples/goji/server.go)
* [Martini](http://martini.codegangsta.io):[examples/martini/server.go](https://github.com/rs/cors/blob/master/examples/martini/server.go)
* [Negroni](https://github.com/codegangsta/negroni):[examples/negroni/server.go](https://github.com/rs/cors/blob/master/examples/negroni/server.go)
* [Alice](https://github.com/justinas/alice):[examples/alice/server.go](https://github.com/rs/cors/blob/master/examples/alice/server.go)
* [HttpRouter](https://github.com/julienschmidt/httprouter):[examples/httprouter/server.go](https://github.com/rs/cors/blob/master/examples/httprouter/server.go)
* [Gorilla](http://www.gorillatoolkit.org/pkg/mux):[examples/gorilla/server.go](https://github.com/rs/cors/blob/master/examples/gorilla/server.go)
* [Buffalo](https://gobuffalo.io):[examples/buffalo/server.go](https://github.com/rs/cors/blob/master/examples/buffalo/server.go)
* [Gin](https://gin-gonic.github.io/gin):[examples/gin/server.go](https://github.com/rs/cors/blob/master/examples/gin/server.go)
* [Chi](https://github.com/go-chi/chi):[examples/chi/server.go](https://github.com/rs/cors/blob/master/examples/chi/server.go)
## 参数
```
c := cors.New(cors.Options{
AllowedOrigins: []string{"http://foo.com", "http://foo.com:8080"},
AllowCredentials: true,
// Enable Debugging for testing, consider disabling in production
Debug: true,
})
// Insert the middleware
handler = c.Handler(handler)
```
* **AllowedOrigins** `[]string`:允许执行跨域请求的 origin 列表。如果列表中存在特殊的 `*` 值,则将允许所有 origin。一个 origin 可以包含一个通配符 (`*`) 来替换 0 个或多个字符(例如:`http://*.domain.com`)。使用通配符会带来微小的性能损耗。每个 origin 只能使用一个通配符。默认值为 `*`。
* **AllowOriginFunc** `func (origin string) bool`:用于验证 origin 的自定义函数。它将 origin 作为参数,如果允许则返回 true,否则返回 false。如果设置了此选项,`AllowedOrigins` 的内容将被忽略。
* **AllowOriginRequestFunc** `func (r *http.Request, origin string) bool`:用于验证 origin 的自定义函数。它将 HTTP Request 对象和 origin 作为参数,如果允许则返回 true,否则返回 false。如果设置了此选项,`AllowedOrigins` 和 `AllowOriginFunc` 的内容将被忽略。
已弃用:请改用 `AllowOriginVaryRequestFunc`。
* **AllowOriginVaryRequestFunc** `func(r *http.Request, origin string) (bool, []string)`:用于验证 origin 的自定义函数。它将 HTTP Request 对象和 origin 作为参数,如果允许则返回 true,否则返回 false,并附带用于做出该决定的 header 列表(如果有),以便它们可以被添加到 Vary header 中。如果设置了此选项,`AllowedOrigins`、`AllowOriginFunc` 和 `AllowOriginRequestFunc` 的内容将被忽略。
* **AllowedMethods** `[]string`:允许客户端在跨域请求中使用的方法列表。默认值为简单方法(`GET` 和 `POST`)。
* **AllowedHeaders** `[]string`:允许客户端在跨域请求中使用的非简单 header 列表。
* **ExposedHeaders** `[]string`:指示哪些 header 可以安全地暴露给 CORS API 规范的 API。
* **AllowCredentials** `bool`:指示请求是否可以包含用户凭据,如 cookie、HTTP 认证或客户端 SSL 证书。默认值为 `false`。
* **AllowPrivateNetwork** `bool`:指示是否接受通过专用网络发起的跨域请求。
* **MaxAge** `int`:指示预检请求的结果可以缓存多长时间(以秒为单位)。默认值为 `0`,表示没有最大有效期。
* **OptionsPassthrough** `bool`:指示预检请求让其他潜在的后续 handler 去处理 `OPTIONS` 方法。如果你的应用程序需要处理 `OPTIONS`,请开启此项。
* **OptionsSuccessStatus** `int`:提供用于成功 OPTIONS 请求的状态码。默认值为 `http.StatusNoContent` (`204`)。
* **Debug** `bool`:调试标志,会添加额外的输出来调试服务器端 CORS 问题。
有关更多信息,请参阅 [API 文档](http://godoc.org/github.com/rs/cors)。
## 基准测试
```
goos: darwin
goarch: arm64
pkg: github.com/rs/cors
BenchmarkWithout-10 135325480 8.124 ns/op 0 B/op 0 allocs/op
BenchmarkDefault-10 24082140 51.40 ns/op 0 B/op 0 allocs/op
BenchmarkAllowedOrigin-10 16424518 88.25 ns/op 0 B/op 0 allocs/op
BenchmarkPreflight-10 8010259 147.3 ns/op 0 B/op 0 allocs/op
BenchmarkPreflightHeader-10 6850962 175.0 ns/op 0 B/op 0 allocs/op
BenchmarkWildcard/match-10 253275342 4.714 ns/op 0 B/op 0 allocs/op
BenchmarkWildcard/too_short-10 1000000000 0.6235 ns/op 0 B/op 0 allocs/op
PASS
ok github.com/rs/cors 99.131s
```
## 许可证
所有源代码均基于 [MIT License](https://raw.github.com/rs/cors/master/LICENSE) 授权。
标签:CORS, EVTX分析, Go, net/http, Ruby工具, Syscall, Web开发, 中间件, 日志审计