diff options
| author | Jeroen Wijenbergh <jeroenwijenbergh@protonmail.com> | 2024-05-06 14:47:43 +0200 |
|---|---|---|
| committer | Jeroen Wijenbergh <46386452+jwijenbergh@users.noreply.github.com> | 2024-05-24 13:25:11 +0200 |
| commit | 921b7f6449c32c5788e43c128ab9f46683dba8e8 (patch) | |
| tree | 6260046a537f45579e568d7d8f251ff1efda7800 /internal/test | |
| parent | a2ee44b700d6f094bbf887c8cfb4734da3e3cb3f (diff) | |
Test Server: Add helpers for response handlers
Diffstat (limited to 'internal/test')
| -rw-r--r-- | internal/test/server.go | 45 |
1 files changed, 43 insertions, 2 deletions
diff --git a/internal/test/server.go b/internal/test/server.go index 6c1b418..ee00656 100644 --- a/internal/test/server.go +++ b/internal/test/server.go @@ -4,6 +4,7 @@ package test import ( "crypto/tls" "crypto/x509" + "net" "net/http" "net/http/httptest" @@ -16,11 +17,51 @@ type Server struct { } // NewServer creates a new test server -func NewServer(handler http.Handler) *Server { - s := httptest.NewTLSServer(handler) +func NewServer(handler http.Handler, listener net.Listener) *Server { + if listener == nil { + s := httptest.NewTLSServer(handler) + return &Server{s} + } + + s := httptest.NewUnstartedServer(handler) + s.Listener.Close() + s.Listener = listener + s.StartTLS() return &Server{s} } +type HandlerPath struct { + Method string + Path string + Response string + ResponseHandler func(http.ResponseWriter, *http.Request) + ResponseCode int +} + +func (hp *HandlerPath) HandlerFunc() func(http.ResponseWriter, *http.Request) { + if hp.ResponseHandler != nil { + return hp.ResponseHandler + } + return func(w http.ResponseWriter, r *http.Request) { + if r.Method != hp.Method { + http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) + return + } + w.WriteHeader(hp.ResponseCode) + w.Write([]byte(hp.Response)) + } +} + +// NewServerWithHandles creates a new test servers with path and responses +func NewServerWithHandles(hps []HandlerPath, listener net.Listener) *Server { + mux := http.NewServeMux() + for _, hp := range hps { + hp := hp + mux.HandleFunc(hp.Path, hp.HandlerFunc()) + } + return NewServer(mux, listener) +} + // Client returns a test client that trusts the HTTPS certificates func (srv *Server) Client() (*httpw.Client, error) { // Get the certs from the test server |
