Add support for optional request logging

This is a debugging aid only.  The log format is not stable (and thus
not documented).
This commit is contained in:
Saj Goonatilleke 2019-05-15 19:28:22 +10:00
parent c7a9ad814b
commit ec51e302f5
3 changed files with 47 additions and 0 deletions

View File

@ -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

39
logging.go Normal file
View File

@ -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)
})
}

View File

@ -43,6 +43,10 @@ func main() {
handler := authProxyHandler(proxy, config)
if config.LogRequests {
handler = logHandler(handler)
}
server := &http.Server{
Addr: config.ListenAddr,
Handler: handler,