ToMiddleware converts SecureConfig to middleware or returns an error for invalid configuration
()
| 99 | |
| 100 | // ToMiddleware converts SecureConfig to middleware or returns an error for invalid configuration |
| 101 | func (config SecureConfig) ToMiddleware() (echo.MiddlewareFunc, error) { |
| 102 | // Defaults |
| 103 | if config.Skipper == nil { |
| 104 | config.Skipper = DefaultSecureConfig.Skipper |
| 105 | } |
| 106 | |
| 107 | // Precompute the Strict-Transport-Security header value once: it depends only on immutable config, |
| 108 | // so there is no need to rebuild it with fmt.Sprintf on every HTTPS request. Empty when HSTS is disabled. |
| 109 | hstsValue := "" |
| 110 | if config.HSTSMaxAge != 0 { |
| 111 | subdomains := "" |
| 112 | if !config.HSTSExcludeSubdomains { |
| 113 | subdomains = "; includeSubdomains" |
| 114 | } |
| 115 | if config.HSTSPreloadEnabled { |
| 116 | subdomains += "; preload" |
| 117 | } |
| 118 | hstsValue = fmt.Sprintf("max-age=%d%s", config.HSTSMaxAge, subdomains) |
| 119 | } |
| 120 | |
| 121 | return func(next echo.HandlerFunc) echo.HandlerFunc { |
| 122 | return func(c *echo.Context) error { |
| 123 | if config.Skipper(c) { |
| 124 | return next(c) |
| 125 | } |
| 126 | |
| 127 | req := c.Request() |
| 128 | res := c.Response() |
| 129 | |
| 130 | if config.XSSProtection != "" { |
| 131 | res.Header().Set(echo.HeaderXXSSProtection, config.XSSProtection) |
| 132 | } |
| 133 | if config.ContentTypeNosniff != "" { |
| 134 | res.Header().Set(echo.HeaderXContentTypeOptions, config.ContentTypeNosniff) |
| 135 | } |
| 136 | if config.XFrameOptions != "" { |
| 137 | res.Header().Set(echo.HeaderXFrameOptions, config.XFrameOptions) |
| 138 | } |
| 139 | if hstsValue != "" && (c.IsTLS() || (req.Header.Get(echo.HeaderXForwardedProto) == "https")) { |
| 140 | res.Header().Set(echo.HeaderStrictTransportSecurity, hstsValue) |
| 141 | } |
| 142 | if config.ContentSecurityPolicy != "" { |
| 143 | if config.CSPReportOnly { |
| 144 | res.Header().Set(echo.HeaderContentSecurityPolicyReportOnly, config.ContentSecurityPolicy) |
| 145 | } else { |
| 146 | res.Header().Set(echo.HeaderContentSecurityPolicy, config.ContentSecurityPolicy) |
| 147 | } |
| 148 | } |
| 149 | if config.ReferrerPolicy != "" { |
| 150 | res.Header().Set(echo.HeaderReferrerPolicy, config.ReferrerPolicy) |
| 151 | } |
| 152 | return next(c) |
| 153 | } |
| 154 | }, nil |
| 155 | } |