go-paste/cmd/paste/cors.go

36 lines
782 B
Go
Raw Normal View History

2020-08-28 16:50:27 -06:00
package main
import (
"net/http"
"sour.is/x/toolbox/httpsrv"
"sour.is/x/toolbox/ident"
)
func init() {
httpsrv.NewMiddleware("cors", doCORS).
Register(httpsrv.EventPreAuth)
}
func doCORS(_ string, w httpsrv.ResponseWriter, r *http.Request, _ ident.Ident) bool {
origin := r.Header.Get("origin")
headers := r.Header.Get("access-control-request-headers")
if origin != "" {
w.Header().Add("access-control-allow-origin", origin)
}
w.Header().Add("access-control-allow-methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Add("access-control-allow-credentials", "true")
w.Header().Add("access-control-max-age", "3600")
if headers != "" {
w.Header().Add("access-control-allow-headers", headers)
}
if r.Method == "OPTIONS" {
return false
}
return true
}