forked from ZizzyDizzyMC/linx-server
-
Notifications
You must be signed in to change notification settings - Fork 1
/
csp.go
45 lines (36 loc) · 946 Bytes
/
csp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main
import (
"net/http"
)
const (
cspHeader = "Content-Security-Policy"
rpHeader = "Referrer-Policy"
frameOptionsHeader = "X-Frame-Options"
)
type csp struct {
h http.Handler
opts CSPOptions
}
type CSPOptions struct {
policy string
referrerPolicy string
frame string
}
func (c csp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
// only add a CSP if one is not already set
if existing := w.Header().Get(cspHeader); existing == "" {
w.Header().Add(cspHeader, c.opts.policy)
}
// only add a Referrer Policy if one is not already set
if existing := w.Header().Get(rpHeader); existing == "" {
w.Header().Add(rpHeader, c.opts.referrerPolicy)
}
w.Header().Set(frameOptionsHeader, c.opts.frame)
c.h.ServeHTTP(w, r)
}
func ContentSecurityPolicy(o CSPOptions) func(http.Handler) http.Handler {
fn := func(h http.Handler) http.Handler {
return csp{h, o}
}
return fn
}