HTTP Handler
In order to react to an HTTP request, we need to write something that, we usually say, handles the request; hence, we call this something a handler. In Go, we have several ways to do that, and one is to implement the handler interface of the http package. This interface has one method that is pretty self-explanatory, and this is as follows:
ServeHTTP(w http.ResponseWriter, r *http.Request)
So, whenever we need to create a handler for HTTP requests, we can create a struct including this method and we can use it to handle an HTTP request. For example:
type MyHandler struct {} func(h MyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {}
This is a valid HTTP handler and you can use it this way:
http.ListenAndServe(":8080", MyHandler{})
Here, ListenAndServe()
is a function that will use our handler to serve the requests; any struct implementing the handler interface will be fine. However, we need to let our server do something.
As you...