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

Commit 989725a

Browse files
committed
FIX: Missing HSTS-header
1 parent daffe1f commit 989725a

File tree

3 files changed

+40
-2
lines changed

3 files changed

+40
-2
lines changed

gddo-server/main.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1016,8 +1016,9 @@ func main() {
10161016
}
10171017
}
10181018
}()
1019-
http.Handle("/", s)
1020-
log.Fatal(http.ListenAndServe(s.v.GetString(ConfigBindAddress), s))
1019+
ss := httputil.HSTS(s)
1020+
http.Handle("/", ss)
1021+
log.Fatal(http.ListenAndServe(s.v.GetString(ConfigBindAddress), ss))
10211022
}
10221023

10231024
// removeInternal removes the internal packages from the given package

httputil/middleware.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
package httputil
2+
3+
import "net/http"
4+
5+
func HSTS(next http.Handler) http.Handler {
6+
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
7+
// This enforces the use of HTTPS for 1 year, including present and future subdomains.
8+
// Chrome and Mozilla Firefox maintain an HSTS preload list
9+
// that automatically informs the browser that the website can only be accessed through HTTPS.
10+
// issue : https://github.com/golang/go/issues/26162
11+
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains; preload")
12+
next.ServeHTTP(w, r)
13+
})
14+
}

httputil/middleware_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package httputil
2+
3+
import (
4+
"io"
5+
"net/http"
6+
"net/http/httptest"
7+
"testing"
8+
)
9+
10+
func TestHSTS(t *testing.T) {
11+
req := httptest.NewRequest(http.MethodGet, "/", nil)
12+
respRecorder := httptest.NewRecorder()
13+
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
14+
io.WriteString(w, "")
15+
})
16+
handlerWithMiddlewareHSTS := HSTS(handler)
17+
handlerWithMiddlewareHSTS.ServeHTTP(respRecorder, req)
18+
want := "max-age=31536000; includeSubDomains; preload"
19+
got := respRecorder.Header().Get("Strict-Transport-Security")
20+
if got != want {
21+
t.Error("middlewareHSTS do not add HSTS header")
22+
}
23+
}

0 commit comments

Comments
 (0)