Writing HTTP handlers
When an HTTP request arrives at a server, the server looks at the HTTP method (GET, POST, etc), the hostname the client used (the Host
header), and the URL to decide how to handle the request. The mechanism that determines which handler should handle such a request is called a request multiplexer. The Go standard library comes with one, and there are many third-party open source multiplexers. In this section, we will look at the standard library multiplexer and how it can be used.
How to do it...
- You can use an anonymous function for simple cases, such as a health-check endpoint:
mux := http.NewServeMux() mux.HandleFunc("GET /health",func(w http.ResponseWriter, req *http.Request) { w.Write([]byte("Ok") }) ... server := http.Server { Handler: mux, Addr: ":8080", ... } server.ListenAndServe()
The preceding handler will respond to
GET /health
endpoint requests with anOk
andHTTP...