2024-11-03 10:03:50 +00:00
|
|
|
package middleware
|
|
|
|
|
|
|
|
import (
|
2024-11-03 16:54:28 +00:00
|
|
|
"io"
|
2024-11-03 10:03:50 +00:00
|
|
|
"net/http"
|
|
|
|
"net/http/httptest"
|
|
|
|
"testing"
|
|
|
|
|
|
|
|
"gitserver.in/patialtech/mux"
|
|
|
|
)
|
|
|
|
|
|
|
|
func TestHelmet(t *testing.T) {
|
|
|
|
r := mux.NewRouter()
|
2024-11-03 16:54:28 +00:00
|
|
|
r.Use(Helmet(HelmetOption{}))
|
2024-11-03 10:03:50 +00:00
|
|
|
r.Get("/hello", func(writer http.ResponseWriter, request *http.Request) {
|
|
|
|
_, _ = writer.Write([]byte("hello there"))
|
|
|
|
})
|
|
|
|
|
2024-11-03 16:54:28 +00:00
|
|
|
srv := httptest.NewServer(r)
|
|
|
|
defer srv.Close()
|
|
|
|
w, _ := testRequest(t, srv, "GET", "/hello", nil)
|
2024-11-03 10:03:50 +00:00
|
|
|
|
2024-11-03 16:54:28 +00:00
|
|
|
csp := w.Header.Get("Content-Security-Policy")
|
|
|
|
// must not have a csp header, technically no header related to helmet but lets test with one.
|
|
|
|
if csp == "" {
|
|
|
|
t.Error("csp header is expected")
|
2024-11-03 10:03:50 +00:00
|
|
|
}
|
|
|
|
|
2024-11-03 16:54:28 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func testRequest(t *testing.T, ts *httptest.Server, method, path string, body io.Reader) (*http.Response, string) {
|
|
|
|
req, err := http.NewRequest(method, ts.URL+path, body)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
return nil, ""
|
2024-11-03 10:03:50 +00:00
|
|
|
}
|
|
|
|
|
2024-11-03 16:54:28 +00:00
|
|
|
resp, err := http.DefaultClient.Do(req)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
return nil, ""
|
|
|
|
}
|
2024-11-03 10:03:50 +00:00
|
|
|
|
2024-11-03 16:54:28 +00:00
|
|
|
respBody, err := io.ReadAll(io.Reader(resp.Body))
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
return nil, ""
|
2024-11-03 10:03:50 +00:00
|
|
|
}
|
2024-11-03 16:54:28 +00:00
|
|
|
defer resp.Body.Close()
|
2024-11-03 10:03:50 +00:00
|
|
|
|
2024-11-03 16:54:28 +00:00
|
|
|
return resp, string(respBody)
|
2024-11-03 10:03:50 +00:00
|
|
|
}
|