diff --git a/config.go b/config.go index 498e183..e5bf42f 100644 --- a/config.go +++ b/config.go @@ -25,6 +25,7 @@ type Config struct { UsernameHeader string GroupsHeader string Timeout time.Duration + LogRequests bool } func ParseConfig() (*Config, error) { @@ -85,6 +86,7 @@ func ParseConfig() (*Config, error) { c.UsernameHeader = *rc.UsernameHeader c.GroupsHeader = *rc.GroupsHeader c.Timeout = time.Duration(*rc.Timeout) * time.Second + c.LogRequests = *rc.LogRequests c.CookieSecret = uuid.New() @@ -103,6 +105,7 @@ type rawConfig struct { UsernameHeader *string GroupsHeader *string Timeout *int + LogRequests *bool } func parseRawConfig() *rawConfig { @@ -118,6 +121,7 @@ func parseRawConfig() *rawConfig { UsernameHeader: flag.String("username-header", "Discourse-User-Name", "Request header to pass authenticated username into"), GroupsHeader: flag.String("groups-header", "Discourse-User-Groups", "Request header to pass authenticated groups into"), Timeout: flag.Int("timeout", 10, "Read/write timeout"), + LogRequests: flag.Bool("log-requests", false, "log all requests to standard error"), } flag.Parse() return c diff --git a/logging.go b/logging.go new file mode 100644 index 0000000..7593ca5 --- /dev/null +++ b/logging.go @@ -0,0 +1,39 @@ +package main + +import ( + "log" + "net/http" +) + +type loggableResponseWriter struct { + StatusCode int + + next http.ResponseWriter +} + +func (w *loggableResponseWriter) Header() http.Header { + return w.next.Header() +} + +func (w *loggableResponseWriter) Write(b []byte) (int, error) { + return w.next.Write(b) +} + +func (w *loggableResponseWriter) WriteHeader(statusCode int) { + w.StatusCode = statusCode + w.next.WriteHeader(statusCode) +} + +func (w *loggableResponseWriter) Flush() { + if flusher, ok := w.next.(http.Flusher); ok { + flusher.Flush() + } +} + +func logHandler(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + lw := &loggableResponseWriter{next: w} + next.ServeHTTP(lw, r) + log.Printf("%s %s %s %d", r.RemoteAddr, r.Method, r.URL, lw.StatusCode) + }) +} diff --git a/main.go b/main.go index 2cd101d..76d6d0c 100644 --- a/main.go +++ b/main.go @@ -43,6 +43,10 @@ func main() { handler := authProxyHandler(proxy, config) + if config.LogRequests { + handler = logHandler(handler) + } + server := &http.Server{ Addr: config.ListenAddr, Handler: handler,