0

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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
Mohd Mujtaba
  • 169
  • 1
  • 2
  • 8
  • 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 Answers1

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:

  1. https://www.alexedwards.net/blog/making-and-using-middleware
  2. https://en.wikipedia.org/wiki/Decorator_pattern
barthr
  • 430
  • 7
  • 15