HTTP handler
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 way is to implement the handler interface of the http
package. This interface has one pretty self-explanatory method, 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 that includes this method and we can use it to handle an HTTP request. Here’s an 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 like so:
http.ListenAndServe(":8080", MyHandler{})
Here, ListenAndServe()
is a function that will use our handler to serve the requests; any struct that implements the handler interface will be fine. However, we need to let our server do something.
As...