-
Notifications
You must be signed in to change notification settings - Fork 1
/
helmet.go
64 lines (49 loc) · 1.71 KB
/
helmet.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
package helmet
import (
"strconv"
"github.com/savsgio/atreugo/v11"
gstrconv "github.com/savsgio/gotils/strconv"
)
// New returns a helmet middleware.
func New(cfg Config) atreugo.Middleware {
if cfg.XSSProtection == "" {
cfg.XSSProtection = defaultXSSProtection
}
if cfg.ContentTypeOptions == "" {
cfg.ContentTypeOptions = defaultContentTypeOptions
}
if cfg.XFrameOptions == "" {
cfg.XFrameOptions = defaultXFrameOptions
}
return func(ctx *atreugo.RequestCtx) error {
if cfg.Filter != nil && cfg.Filter(ctx) {
return ctx.Next()
}
ctx.Response.Header.Set(HeaderXXSSProtection, cfg.XSSProtection)
ctx.Response.Header.Set(HeaderXContentTypeOptions, cfg.ContentTypeOptions)
ctx.Response.Header.Set(HeaderXFrameOptions, cfg.XFrameOptions)
isSecure := ctx.IsTLS() || (gstrconv.B2S(ctx.Request.Header.Peek(HeaderXForwardedProto)) == https)
if isSecure && cfg.HSTSMaxAge != 0 {
hstsMaxAgeSeconds := int64(cfg.HSTSMaxAge.Seconds())
headerStrictTransportSecurityValue := "max-age=" + strconv.FormatInt(hstsMaxAgeSeconds, 10)
if cfg.HSTSIncludeSubdomains {
headerStrictTransportSecurityValue += "; includeSubdomains"
}
if cfg.HSTSPreloadEnabled {
headerStrictTransportSecurityValue += "; preload"
}
ctx.Response.Header.Set(HeaderStrictTransportSecurity, headerStrictTransportSecurityValue)
}
if cfg.ContentSecurityPolicy != "" {
if cfg.CSPReportOnly {
ctx.Response.Header.Set(HeaderContentSecurityPolicyReportOnly, cfg.ContentSecurityPolicy)
} else {
ctx.Response.Header.Set(HeaderContentSecurityPolicy, cfg.ContentSecurityPolicy)
}
}
if cfg.ReferrerPolicy != "" {
ctx.Response.Header.Set(HeaderReferrerPolicy, cfg.ReferrerPolicy)
}
return ctx.Next()
}
}