forked from jlelse/GoBlog
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpMiddlewares.go
74 lines (67 loc) · 2.11 KB
/
httpMiddlewares.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package main
import (
"net/http"
"net/url"
"strings"
"go.goblog.app/app/pkgs/bufferpool"
)
func noIndexHeader(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Robots-Tag", "noindex")
next.ServeHTTP(w, r)
})
}
func fixHTTPHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.URL.RawPath = ""
next.ServeHTTP(w, r)
})
}
func headAsGetHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodHead {
// Clone request and change method
newReq := new(http.Request)
*newReq = *r
newReq.Method = http.MethodGet
// Serve new request
next.ServeHTTP(w, newReq)
return
}
next.ServeHTTP(w, r)
})
}
func (a *goBlog) securityHeaders(next http.Handler) http.Handler {
// Build CSP domains list
cspBuilder := bufferpool.Get()
if mp := a.cfg.Micropub.MediaStorage; mp != nil && mp.MediaURL != "" {
if u, err := url.Parse(mp.MediaURL); err == nil {
cspBuilder.WriteByte(' ')
cspBuilder.WriteString(u.Hostname())
}
}
if len(a.cfg.Server.CSPDomains) > 0 {
cspBuilder.WriteByte(' ')
cspBuilder.WriteString(strings.Join(a.cfg.Server.CSPDomains, " "))
}
cspDomains := cspBuilder.String()
bufferpool.Put(cspBuilder)
// Return handler
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Strict-Transport-Security", "max-age=31536000;")
w.Header().Set("Referrer-Policy", "no-referrer")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "SAMEORIGIN")
w.Header().Set("X-Xss-Protection", "1; mode=block")
w.Header().Set("Content-Security-Policy", "default-src 'self' blob:"+cspDomains+"; img-src 'self'"+cspDomains+" data:")
next.ServeHTTP(w, r)
})
}
func (a *goBlog) addOnionLocation(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if a.torAddress != "" {
w.Header().Set("Onion-Location", a.torAddress+r.RequestURI)
}
next.ServeHTTP(w, r)
})
}