#1 Understanding net/http package
So far we learned how the web works, in this article, we will see how Go support the web, which package to support to work with go and networking and how to use it.
Package http
Accepting HTTP requests is the primary goal of a web server.
System-level package net/http helps create servers and clients.
ServeMux - A basic router in Go
- Is an HTTP request Multiplexer.
- Using ServeMux can handle multiple routes
we can also create our own multiplexer.
A multiplexer handles the logic of separating routes with a function called ServeHTTP. so if we create a Go struct with the ServeHTTP method, it can do the job as the in-build multiplexer.
Handlers - The Handler is the struct that is responsible for responding to individual requests, for a struct to be considered a handler, it has to satisfy the interface:
Eg. If we were to pass a handler directly to the server we created the above code.
we create a customHandler Handler and pass it on to the server to be used to handle responses.
so the question is how our earlier code get the server to handle our request initially without explicitly passing a handler?
DefaultServeMux
When there is no handler explicitly passed to the handler, the DefaultServeMux ( which is a ServeMux ) declared in the net/http is used.
ServeMux - ServeMux is an HTTP request multiplexer.
It matches the URL of each incoming request against a list of registered patterns and calls the handler for the pattern that most closely matches the URL.
- mu is a mutex lock and prevents race conditions
- m holds a map of patterns to a muxEntry. A muxEntry is essentially a handler and pattern.
- es is the sorted lists of muxEntries from longest to shortest
Every call to HandleFunc of the ServeMux calls.Handle on the mux while passing the pattern and a HandleFunc.
The mux checks if the m map has been initialized ( it initializes if it hasn't)
Then adds a muxEntry to the map for that pattern.
HandleFunc : The HandleFunc is an Adapter that converts a
func ( ResponseWriter, *Request) into a Handler.
mux.Handle(pattern, HandlerFunc(handler))
It covers the second parameter of ServeMux.HandleFunc, which is a function that accepts a ResponseWriter and Request.
func ( ResponseWriter, *Request) into a Handler
Server.serve(net.Listener) This is the method responsible for accepting connections via the listener and responding to request via the handler.