Merge pull request #86 from lbryio/cors

Cors
This commit is contained in:
Mark 2021-03-10 21:04:16 -05:00 committed by GitHub
commit 3c99b84721
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -17,6 +17,12 @@ import (
// ResponseHeaders are returned with each response // ResponseHeaders are returned with each response
var ResponseHeaders map[string]string var ResponseHeaders map[string]string
// CorsDomains Allowed domains for CORS Policy
var CorsDomains []string
// CorsAllowLocalhost if true localhost connections are always allowed
var CorsAllowLocalhost bool
// Log allows logging of events and errors // Log allows logging of events and errors
var Log = func(*http.Request, *Response, error) {} var Log = func(*http.Request, *Response, error) {}
@ -77,6 +83,32 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set(key, value) w.Header().Set(key, value)
} }
} }
origin := r.Header.Get("origin")
for _, d := range CorsDomains {
if d == origin {
w.Header().Set("Access-Control-Allow-Origin", d)
vary := w.Header().Get("Vary")
if vary != "*" {
if vary != "" {
vary += ", "
}
vary += "Origin"
}
w.Header().Set("Vary", vary)
}
}
if CorsAllowLocalhost && strings.HasPrefix(origin, "http://localhost:") {
w.Header().Set("Access-Control-Allow-Origin", origin)
vary := w.Header().Get("Vary")
if vary != "*" {
if vary != "" {
vary += ", "
}
vary += "Origin"
}
w.Header().Set("Vary", vary)
}
// Stop here if its a preflighted OPTIONS request // Stop here if its a preflighted OPTIONS request
if r.Method == "OPTIONS" { if r.Method == "OPTIONS" {