git.iko.soy/typeable/oauth2-proxy
on v6.0.0 help sign in
typeable/oauth2-proxy/logging_handler.go
108 lines 2.7 kB history raw
1// largely adapted from https://github.com/gorilla/handlers/blob/master/handlers.go
2// to add logging of request duration as last value (and drop referrer)
4package main
6import (
7 "bufio"
8 "errors"
9 "net"
10 "net/http"
11 "time"
13 "github.com/oauth2-proxy/oauth2-proxy/pkg/logger"
16// responseLogger is wrapper of http.ResponseWriter that keeps track of its HTTP status
17// code and body size
18type responseLogger struct {
19 w http.ResponseWriter
20 status int
21 size int
22 upstream string
23 authInfo string
26// Header returns the ResponseWriter's Header
27func (l *responseLogger) Header() http.Header {
28 return l.w.Header()
31// Support Websocket
32func (l *responseLogger) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
33 if hj, ok := l.w.(http.Hijacker); ok {
34 return hj.Hijack()
35 }
36 return nil, nil, errors.New("http.Hijacker is not available on writer")
39// ExtractGAPMetadata extracts and removes GAP headers from the ResponseWriter's
40// Header
41func (l *responseLogger) ExtractGAPMetadata() {
42 upstream := l.w.Header().Get("GAP-Upstream-Address")
43 if upstream != "" {
44 l.upstream = upstream
45 l.w.Header().Del("GAP-Upstream-Address")
46 }
47 authInfo := l.w.Header().Get("GAP-Auth")
48 if authInfo != "" {
49 l.authInfo = authInfo
50 l.w.Header().Del("GAP-Auth")
51 }
54// Write writes the response using the ResponseWriter
55func (l *responseLogger) Write(b []byte) (int, error) {
56 if l.status == 0 {
57 // The status will be StatusOK if WriteHeader has not been called yet
58 l.status = http.StatusOK
59 }
60 l.ExtractGAPMetadata()
61 size, err := l.w.Write(b)
62 l.size += size
63 return size, err
66// WriteHeader writes the status code for the Response
67func (l *responseLogger) WriteHeader(s int) {
68 l.ExtractGAPMetadata()
69 l.w.WriteHeader(s)
70 l.status = s
73// Status returns the response status code
74func (l *responseLogger) Status() int {
75 return l.status
78// Size returns the response size
79func (l *responseLogger) Size() int {
80 return l.size
83// Flush sends any buffered data to the client
84func (l *responseLogger) Flush() {
85 if flusher, ok := l.w.(http.Flusher); ok {
86 flusher.Flush()
87 }
90// loggingHandler is the http.Handler implementation for LoggingHandler
91type loggingHandler struct {
92 handler http.Handler
95// LoggingHandler provides an http.Handler which logs requests to the HTTP server
96func LoggingHandler(h http.Handler) http.Handler {
97 return loggingHandler{
98 handler: h,
99 }
102func (h loggingHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
103 t := time.Now()
104 url := *req.URL
105 responseLogger := &responseLogger{w: w}
106 h.handler.ServeHTTP(responseLogger, req)
107 logger.PrintReq(responseLogger.authInfo, responseLogger.upstream, req, url, t, responseLogger.Status(), responseLogger.Size())