原点
包origin提供了简单的工具和方法来比较和验证服务器端请求的Origin header,特别是在跨源资源共享(CORS)的背景下。
它支持简单的通配符模式匹配,并为最常见的网络协议处理省略的端口号。
使用方法
import (
"io"
"github.com/posterity/origin"
)
// Trusted origins:
// - example.com and its subdomains over HTTPS on port 443 (implicit);
// - localhost on any scheme and any port.
var patterns = origin.Patterns{
"https://example.com",
"https://*.example.com",
"*://localhost:*",
}
func handler(w http.ResponseWriter, r *http.Request) {
ok, err := patterns.Match(origin.Get(r))
if err != nil {
panic(err) // Either the origin or the pattern is mis-formatted.
}
if !ok {
w.WriteHeader(401)
io.WriteString(w, "This request is not from a trusted origin")
return
}
io.WriteString(w, "Hello, World!")
}