From eef1416de3a21486a1d3b0ce091aba97f9c1b549 Mon Sep 17 00:00:00 2001 From: Evgeny <113383200+KlassnayaAfrodita@users.noreply.github.com> Date: Wed, 23 Oct 2024 01:05:52 +0300 Subject: [PATCH] Create profiling.go this middleware can be useful when analyzing errors, it collects information about which request took how long (time, method, path, IP). I wrote middleweir in your style, so there is an empty structure there --- internal/core/middleware/profiling.go | 41 +++++++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 internal/core/middleware/profiling.go diff --git a/internal/core/middleware/profiling.go b/internal/core/middleware/profiling.go new file mode 100644 index 0000000..da98ab1 --- /dev/null +++ b/internal/core/middleware/profiling.go @@ -0,0 +1,41 @@ +package middleware + +import ( + "log" + "net/http" + "time" +) + +// ProfilingMiddleware represents a structure for profiling requests +type ProfilingMiddleware struct { +} + +// NewProfilingMiddleware creates a new instance of ProfilingMiddleware +func NewProfilingMiddleware() *ProfilingMiddleware { + return &ProfilingMiddleware{} +} + +// Handle processes the requests and measures their execution time +func (pm *ProfilingMiddleware) Handle(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + start := time.Now() // Record the start time of the request + + // Pass the request to the next handler in the middleware chain + next.ServeHTTP(w, r) + + // After the request is completed, measure the execution time + duration := time.Since(start) + + // Log information about the request and its execution time + log.Printf("Request: %s %s | Time: %v | From IP: %s", r.Method, r.URL.Path, duration, getClientIP(r)) + }) +} + +// getClientIP extracts the client's IP address from the request +func getClientIP(r *http.Request) string { + ip, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return r.RemoteAddr + } + return ip +}