Skip to content

Commit

Permalink
feat: add security headers middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
hugosandelius committed May 22, 2023
1 parent 85338e0 commit 48e2a8f
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 9 deletions.
18 changes: 18 additions & 0 deletions cloudserver/security_headers.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package cloudserver

import (
"net/http"
)

// SecurityHeadersMiddleware adds security headers to responses.
type SecurityHeadersMiddleware struct{}

// HTTPServer provides HTTP server middleware.
func (i *SecurityHeadersMiddleware) HTTPServer(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
next.ServeHTTP(w, r)
})
}
1 change: 1 addition & 0 deletions httpserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ func NewHTTPServer(ctx context.Context, handler http.Handler, middlewares ...HTT
run.loggerMiddleware.HTTPServer,
run.traceMiddleware.HTTPServer,
run.requestLoggerMiddleware.HTTPServer,
run.securityHeadersMiddleware.HTTPServer,
run.serverMiddleware.HTTPServer,
}
return &http.Server{
Expand Down
19 changes: 10 additions & 9 deletions run.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,15 +152,16 @@ func Run(fn func(context.Context) error, options ...Option) (err error) {
}

type runContext struct {
config runConfig
configOptions []cloudconfig.Option
grpcServerOptions []grpc.ServerOption
loggerMiddleware cloudzap.Middleware
serverMiddleware cloudserver.Middleware
clientMiddleware cloudclient.Middleware
requestLoggerMiddleware cloudrequestlog.Middleware
traceMiddleware cloudtrace.Middleware
metricMiddleware cloudmonitoring.MetricMiddleware
config runConfig
configOptions []cloudconfig.Option
grpcServerOptions []grpc.ServerOption
loggerMiddleware cloudzap.Middleware
serverMiddleware cloudserver.Middleware
clientMiddleware cloudclient.Middleware
requestLoggerMiddleware cloudrequestlog.Middleware
traceMiddleware cloudtrace.Middleware
metricMiddleware cloudmonitoring.MetricMiddleware
securityHeadersMiddleware cloudserver.SecurityHeadersMiddleware
}

type runContextKey struct{}
Expand Down

0 comments on commit 48e2a8f

Please sign in to comment.