users/server/middleware.go

37 lines
916 B
Go
Raw Permalink Normal View History

2023-10-22 19:57:54 +00:00
package server
import (
2023-10-23 19:25:13 +00:00
"fmt"
2023-10-22 19:57:54 +00:00
"net/http"
"time"
"github.com/go-chi/chi/v5/middleware"
2023-10-23 19:25:13 +00:00
"go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
2023-10-22 19:57:54 +00:00
)
func (s *UserServer) MiddlewareLogging(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
ww := middleware.NewWrapResponseWriter(w, r.ProtoMajor)
t1 := time.Now()
defer func(ww middleware.WrapResponseWriter) {
s.Logger.Info("Served request.",
"status", ww.Status(),
2023-10-22 21:12:12 +00:00
"method", r.Method,
2023-10-22 19:57:54 +00:00
"path", r.URL.Path,
"duration", time.Since(t1),
"written", ww.BytesWritten())
}(ww)
next.ServeHTTP(ww, r)
}
return http.HandlerFunc(fn)
}
2023-10-23 19:25:13 +00:00
func (s *UserServer) MiddlewareTracing(next http.Handler) http.Handler {
fn := func(w http.ResponseWriter, r *http.Request) {
h := otelhttp.NewHandler(next, fmt.Sprintf("%s %s", r.Method, r.URL.Path))
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}