auth/server/middleware.go

45 lines
1.1 KiB
Go
Raw Normal View History

2023-10-21 08:26:15 +00:00
package server
import (
2023-10-23 12:23:19 +00:00
"fmt"
2023-10-21 08:26:15 +00:00
"net/http"
"time"
"github.com/go-chi/chi/v5/middleware"
2023-10-23 12:23:19 +00:00
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
"go.opentelemetry.io/otel/trace"
2023-10-21 08:26:15 +00:00
)
func (s *Server) MiddlewareLogging(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
reqID := middleware.GetReqID(r.Context())
t1 := time.Now()
defer func(ww middleware.WrapResponseWriter) {
s.Logger.Info("Served request.",
"status", ww.Status(),
"path", r.URL.Path,
"duration", time.Since(t1),
"remote", r.RemoteAddr,
"written", ww.BytesWritten(),
"req", reqID,
)
}(ww)
next.ServeHTTP(ww, r)
}
return http.HandlerFunc(fn)
}
2023-10-23 12:23:19 +00:00
func (s *Server) MiddlewareTracing(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
span := trace.SpanFromContext(r.Context())
span.AddEvent("event")
h := otelhttp.NewHandler(next, fmt.Sprintf("%s %s", r.Method, r.URL.Path))
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}