Skip to content

Instantly share code, notes, and snippets.

@maisieccino
Created August 22, 2019 16:28
Show Gist options
  • Save maisieccino/e419480b5ab3483c83562740a03b1c80 to your computer and use it in GitHub Desktop.
Save maisieccino/e419480b5ab3483c83562740a03b1c80 to your computer and use it in GitHub Desktop.
Go is a beautiful language
λ go run cmd/releaser/main.go
API: 2019/08/22 16:27:51 Starting API server on 0.0.0.0:8080
Metrics: 2019/08/22 16:27:51 Starting metrics server on 0.0.0.0:8090
2019/08/22 17:27:53 'GET /' 404 from localhost:8080, User-Agent: curl/7.54.0
2019/08/22 17:27:53 'GET /' 404 from localhost:8080, User-Agent: curl/7.54.0
package api
import (
"net/http"
)
// loggedResponseWriter is a wrapper around
// http.ResponseWriter that adds some useful logging metrics,
// namely capturing the final status code of the request.
// It itself implements http.ResponseWriter so it can be passed
// straight into, e.g. ServeHTTP() methods.
type loggedResponseWriter struct {
w http.ResponseWriter
statusCode int
}
func (lw *loggedResponseWriter) Header() http.Header {
return lw.w.Header()
}
func (lw *loggedResponseWriter) Write(body []byte) (int, error) {
return lw.w.Write(body)
}
func (lw *loggedResponseWriter) WriteHeader(statusCode int) {
lw.w.WriteHeader(statusCode)
lw.statusCode = statusCode
}
// LoggerMiddleware creates a wrapper function for adding a logging middleware.
func LoggerMiddleware(server *Server) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
lw := &loggedResponseWriter{w: w}
next.ServeHTTP(lw, r)
server.Logger.Printf(
"'%s %s' %d from %s, User-Agent: %s",
r.Method,
r.RequestURI,
lw.statusCode,
r.Host,
r.UserAgent(),
)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment