Move Logging to Middleware Package (#1070)

* Use a specialized ResponseWriter in middleware

* Track User & Upstream in RequestScope

* Wrap responses in our custom ResponseWriter

* Add tests for logging middleware

* Inject upstream metadata into request scope

* Use custom ResponseWriter only in logging middleware

* Assume RequestScope is never nil
This commit is contained in:
Nick Meves
2021-03-06 17:27:16 +00:00
committed by GitHub
parent 220b3708fc
commit 602dac7852
16 changed files with 337 additions and 266 deletions
+12 -2
View File
@@ -3,6 +3,9 @@ package upstream
import (
"fmt"
"net/http"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/apis/middleware"
"github.com/oauth2-proxy/oauth2-proxy/v7/pkg/logger"
)
const defaultStaticResponseCode = 200
@@ -24,9 +27,16 @@ type staticResponseHandler struct {
// ServeHTTP serves a static response.
func (s *staticResponseHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
rw.Header().Set("GAP-Upstream-Address", s.upstream)
scope := middleware.GetRequestScope(req)
// If scope is nil, this will panic.
// A scope should always be injected before this handler is called.
scope.Upstream = s.upstream
rw.WriteHeader(s.code)
fmt.Fprintf(rw, "Authenticated")
_, err := fmt.Fprintf(rw, "Authenticated")
if err != nil {
logger.Errorf("Error writing static response: %v", err)
}
}
// derefStaticCode returns the derefenced value, or the default if the value is nil