2 Commits

Author SHA1 Message Date
f4a2452a94 removed proxy func, need to revist it again 2024-11-03 22:33:56 +05:30
eda7c79ab6 test correction and Proxy func addition 2024-11-03 22:24:28 +05:30
2 changed files with 33 additions and 38 deletions

View File

@@ -1,6 +1,7 @@
package middleware
import (
"io"
"net/http"
"net/http/httptest"
"testing"
@@ -10,41 +11,42 @@ import (
func TestHelmet(t *testing.T) {
r := mux.NewRouter()
r.Use(Helmet(HelmetOption{}))
r.Get("/hello", func(writer http.ResponseWriter, request *http.Request) {
_, _ = writer.Write([]byte("hello there"))
})
endpoint := httptest.NewRequest(http.MethodGet, "/hello", nil)
srv := httptest.NewServer(r)
defer srv.Close()
w, _ := testRequest(t, srv, "GET", "/hello", nil)
// test endpoint registered/reachable
w := httptest.NewRecorder()
r.ServeHTTP(w, endpoint)
if w.Code != http.StatusOK {
t.Error("not expecting status", w.Code)
return
}
// no header test
w = httptest.NewRecorder()
r.ServeHTTP(w, endpoint)
csp := w.Header().Get("Content-Security-Policy")
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 not expected")
}
// introduce helmet middleware
r.Use(Helmet(HelmetOption{}))
// header tests..
w = httptest.NewRecorder()
r.ServeHTTP(w, endpoint)
// csp and other headers are expected
csp = w.Header().Get("Content-Security-Policy")
// fmt.Printf("csp %s", csp)
if csp == "" {
t.Error("csp header missing")
t.Error("csp header is expected")
}
// TODO need more tests
}
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, ""
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
return nil, ""
}
respBody, err := io.ReadAll(io.Reader(resp.Body))
if err != nil {
t.Fatal(err)
return nil, ""
}
defer resp.Body.Close()
return resp, string(respBody)
}

View File

@@ -141,18 +141,11 @@ func (r *Router) ServeHTTP(w http.ResponseWriter, req *http.Request) {
panic("mux: method ServeHTTP called on nil")
}
h, pattern := r.mux.Handler(req)
if pattern == "" {
http.Error(w, "Not Found", http.StatusNotFound)
return
}
// ensure we run all the middlewares
h = stack(r.middlewares, h)
// serve
h.ServeHTTP(w, req)
r.mux.ServeHTTP(w, req)
}
// TODO: proxy for aws lambda
// stack middlewares(http handler) in order they are passed (FIFO)
func stack(middlewares []func(http.Handler) http.Handler, endpoint http.Handler) http.Handler {
// Return ahead of time if there aren't any middlewares for the chain