Skip to content

Commit

Permalink
Create profiling.go
Browse files Browse the repository at this point in the history
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
  • Loading branch information
KlassnayaAfrodita authored Oct 22, 2024
1 parent c08f775 commit eef1416
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions internal/core/middleware/profiling.go
Original file line number Diff line number Diff line change
@@ -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
}

0 comments on commit eef1416

Please sign in to comment.