From 227e5e1d692b3178d5d39d57193da1376b87e654 Mon Sep 17 00:00:00 2001 From: keitosuwahara Date: Sat, 5 Jul 2025 06:57:51 +0900 Subject: [PATCH] Further improve readability and maintainability of middleware/secure.go~ --- middleware/secure.go | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/middleware/secure.go b/middleware/secure.go index c904abf1a..1c3709082 100644 --- a/middleware/secure.go +++ b/middleware/secure.go @@ -5,6 +5,7 @@ package middleware import ( "fmt" + "strings" "github.com/labstack/echo/v4" ) @@ -16,6 +17,9 @@ type SecureConfig struct { // XSSProtection provides protection against cross-site scripting attack (XSS) // by setting the `X-XSS-Protection` header. + // Note: This header is deprecated in modern browsers. For more information, see + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-XSS-Protection + // and consider using Content-Security-Policy instead. // Optional. Default value "1; mode=block". XSSProtection string `yaml:"xss_protection"` @@ -118,15 +122,15 @@ func SecureWithConfig(config SecureConfig) echo.MiddlewareFunc { if config.XFrameOptions != "" { res.Header().Set(echo.HeaderXFrameOptions, config.XFrameOptions) } - if (c.IsTLS() || (req.Header.Get(echo.HeaderXForwardedProto) == "https")) && config.HSTSMaxAge != 0 { - subdomains := "" + if (c.IsTLS() || (req.Header.Get(echo.HeaderXForwardedProto) == "https")) && config.HSTSMaxAge > 0 { + hsts := []string{fmt.Sprintf("max-age=%d", config.HSTSMaxAge)} if !config.HSTSExcludeSubdomains { - subdomains = "; includeSubdomains" + hsts = append(hsts, "includeSubdomains") } if config.HSTSPreloadEnabled { - subdomains = fmt.Sprintf("%s; preload", subdomains) + hsts = append(hsts, "preload") } - res.Header().Set(echo.HeaderStrictTransportSecurity, fmt.Sprintf("max-age=%d%s", config.HSTSMaxAge, subdomains)) + res.Header().Set(echo.HeaderStrictTransportSecurity, strings.Join(hsts, "; ")) } if config.ContentSecurityPolicy != "" { if config.CSPReportOnly {