git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/httpx/middlewarex/strict_transport_security.go (about)

     1  package middlewarex
     2  
     3  import (
     4  	"net/http"
     5  
     6  	"git.sr.ht/~pingoo/stdx/httpx"
     7  )
     8  
     9  // StrictTransportSecurity sets the Strict-Transport-Security header to maxAge
    10  // if maxAge is empty, it's set to 63072000
    11  func StrictTransportSecurity(maxAge *string, includeSubDomains bool) func(next http.Handler) http.Handler {
    12  	maxAgeKey := "max-age="
    13  	headerValue := maxAgeKey
    14  
    15  	if maxAge != nil {
    16  		headerValue += *maxAge
    17  	} else {
    18  		headerValue += "63072000"
    19  	}
    20  
    21  	if includeSubDomains {
    22  		headerValue += "; includeSubDomains"
    23  	}
    24  
    25  	return func(next http.Handler) http.Handler {
    26  		fn := func(w http.ResponseWriter, r *http.Request) {
    27  			w.Header().Set(httpx.HeaderStrictTransportSecurity, headerValue)
    28  			next.ServeHTTP(w, r)
    29  		}
    30  		return http.HandlerFunc(fn)
    31  	}
    32  }