Created
July 12, 2016 05:52
-
-
Save elithrar/bcd2180abeafcfbc1240eca6b0e5db23 to your computer and use it in GitHub Desktop.
An example of turning https://github.com/go-kit/kit/tree/master/log into usable HTTP middleware for Go.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package handler | |
import ( | |
"bufio" | |
"io" | |
"net" | |
"net/http" | |
"time" | |
"github.com/go-kit/kit/log" | |
) | |
type logger struct { | |
handler http.Handler | |
output log.Logger | |
// opts options | |
} | |
// NewLogger returns a handler for logging the HTTP request, including status | |
// code, HTTP method, URI (path), duration, bytes written and client address. | |
func NewLogger(output log.Logger) func(http.Handler) http.Handler { | |
return func(h http.Handler) http.Handler { | |
lgr := &logger{ | |
handler: h, | |
output: output, | |
} | |
return lgr | |
} | |
} | |
func (lg *logger) ServeHTTP(w http.ResponseWriter, r *http.Request) { | |
ww := wrapWriter(w) | |
start := time.Now() | |
lg.handler.ServeHTTP(ww, r) | |
end := time.Now() | |
duration := end.Sub(start) | |
lg.output.Log( | |
"ts", time.Now().Format(time.RFC3339), | |
"status", ww.Status(), | |
"method", r.Method, | |
"uri", r.URL.Path, | |
"duration", duration, | |
"bytes", ww.BytesWritten(), | |
"from", r.RemoteAddr, | |
) | |
} | |
// The below writer-wrapping code has been lifted from | |
// https://github.com/zenazn/goji/blob/master/web/middleware/logger.go - because | |
// it does exactly what is needed, and it's unlikely to change in any | |
// significant way that makes copying worse-off than importing. MIT licensed | |
// and (c) Carl Jackson. | |
// writerProxy is a proxy around an http.ResponseWriter that allows you to hook | |
// into various parts of the response process. | |
type writerProxy interface { | |
http.ResponseWriter | |
// Status returns the HTTP status of the request, or 0 if one has not | |
// yet been sent. | |
Status() int | |
// BytesWritten returns the total number of bytes sent to the client. | |
BytesWritten() int | |
// Tee causes the response body to be written to the given io.Writer in | |
// addition to proxying the writes through. Only one io.Writer can be | |
// tee'd to at once: setting a second one will overwrite the first. | |
// Writes will be sent to the proxy before being written to this | |
// io.Writer. It is illegal for the tee'd writer to be modified | |
// concurrently with writes. | |
Tee(io.Writer) | |
// Unwrap returns the original proxied target. | |
Unwrap() http.ResponseWriter | |
} | |
// wrapWriter wraps an http.ResponseWriter, returning a proxy that allows you to | |
// hook into various parts of the response process. | |
func wrapWriter(w http.ResponseWriter) writerProxy { | |
_, cn := w.(http.CloseNotifier) | |
_, fl := w.(http.Flusher) | |
_, hj := w.(http.Hijacker) | |
_, rf := w.(io.ReaderFrom) | |
bw := basicWriter{ResponseWriter: w} | |
if cn && fl && hj && rf { | |
return &fullWriter{bw} | |
} | |
if fl { | |
return &flushWriter{bw} | |
} | |
return &bw | |
} | |
// basicWriter wraps a http.ResponseWriter that implements the minimal | |
// http.ResponseWriter interface. | |
type basicWriter struct { | |
http.ResponseWriter | |
wroteHeader bool | |
code int | |
bytes int | |
tee io.Writer | |
} | |
func (b *basicWriter) WriteHeader(code int) { | |
if !b.wroteHeader { | |
b.code = code | |
b.wroteHeader = true | |
b.ResponseWriter.WriteHeader(code) | |
} | |
} | |
func (b *basicWriter) Write(buf []byte) (int, error) { | |
b.WriteHeader(http.StatusOK) | |
n, err := b.ResponseWriter.Write(buf) | |
if b.tee != nil { | |
_, err2 := b.tee.Write(buf[:n]) | |
// Prefer errors generated by the proxied writer. | |
if err == nil { | |
err = err2 | |
} | |
} | |
b.bytes += n | |
return n, err | |
} | |
func (b *basicWriter) maybeWriteHeader() { | |
if !b.wroteHeader { | |
b.WriteHeader(http.StatusOK) | |
} | |
} | |
func (b *basicWriter) Status() int { | |
return b.code | |
} | |
func (b *basicWriter) BytesWritten() int { | |
return b.bytes | |
} | |
func (b *basicWriter) Tee(w io.Writer) { | |
b.tee = w | |
} | |
func (b *basicWriter) Unwrap() http.ResponseWriter { | |
return b.ResponseWriter | |
} | |
// fullWriter is a writer that additionally satisfies http.CloseNotifier, | |
// http.Flusher, http.Hijacker, and io.ReaderFrom. It exists for the common case | |
// of wrapping the http.ResponseWriter that package http gives you, in order to | |
// make the proxied object support the full method set of the proxied object. | |
type fullWriter struct { | |
basicWriter | |
} | |
func (f *fullWriter) CloseNotify() <-chan bool { | |
cn := f.basicWriter.ResponseWriter.(http.CloseNotifier) | |
return cn.CloseNotify() | |
} | |
func (f *fullWriter) Flush() { | |
fl := f.basicWriter.ResponseWriter.(http.Flusher) | |
fl.Flush() | |
} | |
func (f *fullWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) { | |
hj := f.basicWriter.ResponseWriter.(http.Hijacker) | |
return hj.Hijack() | |
} | |
func (f *fullWriter) ReadFrom(r io.Reader) (int64, error) { | |
if f.basicWriter.tee != nil { | |
return io.Copy(&f.basicWriter, r) | |
} | |
rf := f.basicWriter.ResponseWriter.(io.ReaderFrom) | |
f.basicWriter.maybeWriteHeader() | |
return rf.ReadFrom(r) | |
} | |
var _ http.CloseNotifier = &fullWriter{} | |
var _ http.Flusher = &fullWriter{} | |
var _ http.Hijacker = &fullWriter{} | |
var _ io.ReaderFrom = &fullWriter{} | |
type flushWriter struct { | |
basicWriter | |
} | |
func (f *flushWriter) Flush() { | |
fl := f.basicWriter.ResponseWriter.(http.Flusher) | |
fl.Flush() | |
} | |
var _ http.Flusher = &flushWriter{} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment