gohttpserver/httpserver/middlewares.go
sneak 2a45cb3a5b
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing
now does integrated metrics! fixes #5.
thanks to @slok for setting me straight with my dumb question
on how to use his cool package:

https://github.com/slok/go-http-metrics/issues/41
2020-10-03 00:22:23 -07:00

93 lines
2.4 KiB
Go

package httpserver
import (
"net"
"net/http"
"time"
"github.com/go-chi/chi/middleware"
metrics "github.com/slok/go-http-metrics/metrics/prometheus"
ghmm "github.com/slok/go-http-metrics/middleware"
"github.com/slok/go-http-metrics/middleware/std"
)
// the following is from
// https://learning-cloud-native-go.github.io/docs/a6.adding_zerolog_logger/
func ipFromHostPort(hp string) string {
h, _, err := net.SplitHostPort(hp)
if err != nil {
return ""
}
if len(h) > 0 && h[0] == '[' {
return h[1 : len(h)-1]
}
return h
}
type loggingResponseWriter struct {
http.ResponseWriter
statusCode int
}
func NewLoggingResponseWriter(w http.ResponseWriter) *loggingResponseWriter {
return &loggingResponseWriter{w, http.StatusOK}
}
func (lrw *loggingResponseWriter) WriteHeader(code int) {
lrw.statusCode = code
lrw.ResponseWriter.WriteHeader(code)
}
// type Middleware func(http.Handler) http.Handler
// this returns a Middleware that is designed to do every request through the
// mux, note the signature:
func (s *server) LoggingMiddleware() func(http.Handler) http.Handler {
// FIXME this should use https://github.com/google/go-cloud/blob/master/server/requestlog/requestlog.go
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
lrw := NewLoggingResponseWriter(w)
ctx := r.Context()
defer func() {
latency := time.Since(start)
s.log.Info().
Time("request_start", start).
Str("method", r.Method).
Str("url", r.URL.String()).
Str("useragent", r.UserAgent()).
Str("request_id", ctx.Value(middleware.RequestIDKey).(string)).
Str("referer", r.Referer()).
Str("proto", r.Proto).
Str("remoteIP", ipFromHostPort(r.RemoteAddr)).
Int("status", lrw.statusCode).
Int("latency_ms", int(latency.Milliseconds())).
Send()
}()
next.ServeHTTP(lrw, r)
})
}
}
func (s *server) AuthMiddleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// FIXME you'll want to change this to do stuff.
s.log.Info().Msg("AUTH: before request")
next.ServeHTTP(w, r)
})
}
}
func (s *server) MetricsMiddleware() func(http.Handler) http.Handler {
mdlw := ghmm.New(ghmm.Config{
Recorder: metrics.NewRecorder(metrics.Config{}),
})
return func(next http.Handler) http.Handler {
return std.Handler("", mdlw, next)
}
}