-
Notifications
You must be signed in to change notification settings - Fork 4
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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
1 parent
c08f775
commit eef1416
Showing
1 changed file
with
41 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |