MCPcopy Index your code
hub / github.com/labstack/echo / ToMiddleware

Method ToMiddleware

middleware/secure.go:101–155  ·  view source on GitHub ↗

ToMiddleware converts SecureConfig to middleware or returns an error for invalid configuration

()

Source from the content-addressed store, hash-verified

99
100// ToMiddleware converts SecureConfig to middleware or returns an error for invalid configuration
101func (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}

Callers

nothing calls this directly

Calls 6

RequestMethod · 0.80
ResponseMethod · 0.80
SetMethod · 0.80
IsTLSMethod · 0.80
HeaderMethod · 0.45
GetMethod · 0.45

Tested by

no test coverage detected