this is my initial golang code :
package main
import (
"net/http"
"io"
)
const hello = `hello world`
func helloHandler(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, hello)
}
func main() {
http.HandleFunc("/", helloHandler)
http.ListenAndServe(":1088", nil)
}
it is a simple http server, i need add new function, every get request print in linux terminal ip, METHOD, /request.
example output in terminal need:
95.250.33.36 GET /
95.250.33.36 GET /favicon.ico
95.250.33.36 GET /robots.txt
how i can do this ?
The best thing about Golang is interfaces. Your helloHandler
actually implements the HandlerFunc
interface. Using the Open/Close Principle we can take helloHandler
and extend it for logging the request in the following way:
func wrapHandlerWithLogging(wrappedHandler http.Handler) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
log.Printf("--> %s %s", req.Method, req.URL.Path)
wrappedHandler.ServeHTTP(w, req)
})
}
func main() {
...
http.HandleFunc("/", wrapHandlerWithLogging(http.HandlerFunc(helloHandler)))
...
}
So basically, we wrap helloHandler
which implements HandlerFunc
with another HandlerFunc
.
In this example, we only log the request method (GET, POST, PUT and etc) and the request path (e.g. '/'). However, you can log other data:
req.RemoteAddr
network address that sent the requestreq.Proto
the protocol versionreq.Host
specifies the host on which URL is sought