Skip to content
This repository has been archived by the owner on Jan 16, 2021. It is now read-only.

Commit

Permalink
FIX: Missing HSTS-header
Browse files Browse the repository at this point in the history
  • Loading branch information
AlphaWong committed Jul 4, 2018
1 parent daffe1f commit 989725a
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 2 deletions.
5 changes: 3 additions & 2 deletions gddo-server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -1016,8 +1016,9 @@ func main() {
}
}
}()
http.Handle("/", s)
log.Fatal(http.ListenAndServe(s.v.GetString(ConfigBindAddress), s))
ss := httputil.HSTS(s)
http.Handle("/", ss)
log.Fatal(http.ListenAndServe(s.v.GetString(ConfigBindAddress), ss))
}

// removeInternal removes the internal packages from the given package
Expand Down
14 changes: 14 additions & 0 deletions httputil/middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package httputil

import "net/http"

func HSTS(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// This enforces the use of HTTPS for 1 year, including present and future subdomains.
// Chrome and Mozilla Firefox maintain an HSTS preload list
// that automatically informs the browser that the website can only be accessed through HTTPS.
// issue : https://github.com/golang/go/issues/26162
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload")
next.ServeHTTP(w, r)
})
}
23 changes: 23 additions & 0 deletions httputil/middleware_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package httputil

import (
"io"
"net/http"
"net/http/httptest"
"testing"
)

func TestHSTS(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/", nil)
respRecorder := httptest.NewRecorder()
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, "")
})
handlerWithMiddlewareHSTS := HSTS(handler)
handlerWithMiddlewareHSTS.ServeHTTP(respRecorder, req)
want := "max-age=31536000; includeSubDomains; preload"
got := respRecorder.Header().Get("Strict-Transport-Security")
if got != want {
t.Error("middlewareHSTS do not add HSTS header")
}
}

0 comments on commit 989725a

Please sign in to comment.