about summary refs log tree commit diff stats
path: root/internal/server/logging.go
blob: 372972f46676e5551ca8daa99c1ec1861010a4b2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package server

import (
	"fmt"
	"io"
	"net/http"

	"github.com/pkg/errors"
)

type LoggingResponseWriter struct {
	wroteHeader bool
	http.ResponseWriter
	statusCode int
}

func (lrw *LoggingResponseWriter) WriteHeader(code int) {
	lrw.statusCode = code
	if !lrw.wroteHeader {
		lrw.ResponseWriter.WriteHeader(code)
		lrw.wroteHeader = true
	}
}

func (lrw *LoggingResponseWriter) Write(b []byte) (int, error) {
	if !lrw.wroteHeader {
		lrw.statusCode = http.StatusOK
		lrw.wroteHeader = true
	}

	count, err := lrw.ResponseWriter.Write(b)
	if err != nil {
		return count, errors.Wrap(err, "failed to write response")
	}

	return count, nil
}

func NewLoggingResponseWriter(w http.ResponseWriter) *LoggingResponseWriter {
	return &LoggingResponseWriter{false, w, http.StatusOK}
}

type wrappedHandlerOptions struct {
	defaultHostname string
	logger          io.Writer
}

func wrapHandlerWithLogging(wrappedHandler http.Handler, opts wrappedHandlerOptions) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		scheme := r.Header.Get("X-Forwarded-Proto")
		if scheme == "" {
			scheme = "http"
		}
		lw := NewLoggingResponseWriter(w)
		wrappedHandler.ServeHTTP(lw, r)
		statusCode := lw.statusCode
		fmt.Fprintf(
			opts.logger,
			"%s %s %d %s %s\n",
			scheme,
			r.Method,
			statusCode,
			r.URL.Path,
			lw.Header().Get("Location"),
		)
	})
}