I want to know can I create a kind of middleware which automatically gives me the IP address of user who hitted any url of my website and can print into logs?
Asked
Active
Viewed 273 times
0
-
1[This](https://stackoverflow.com/questions/27234861/correct-way-of-getting-clients-ip-addresses-from-http-request) may help you ! – Arun Jun 24 '20 at 14:54
1 Answers
2
To implement middleware you have to create a function that satisfies the http.Handler
interface.
One way to achieve this is to use decorator function which acts as the middleware:
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// middleware code for example logging
log.Println(r.RemoteAddr)
next.ServeHTTP(w, r)
})
}
the next
argument is your actual http.Handler
.
Following is a more complete example:
func main() {
var handler http.HandlerFunc = testHandler
// Here the handler is wrapped with the middleware
http.Handle("/test", middleware(handler))
}
func middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// middleware code for example logging
log.Println(r.RemoteAddr)
next.ServeHTTP(w, r)
})
}
func testHandler(w http.ResponseWriter, r *http.Request) {
// your handler code
}
This pattern is sometimes referred to as the decorator pattern, for more information see the following links:

barthr
- 430
- 7
- 15