Overview
This article is the 20th entry in the Qiita - Go6 Advent Calendar 2019.
We will conduct a detailed code reading of setting up an HTTP server in Golang.
Reference Implementation
Here is the implementation we will analyze:
We will go through this verbose code line by line, simplifying it while reading.
ServeHttp(w ResponseWriter, r *Request)
First, let’s look at this part:
ServeHTTP(w ResponseWriter, r *Request) is an implementation of the Handler interface.
In the reference implementation, the HelloHandler struct is prepared for ServeHTTP(w ResponseWriter, r *Request). However, it can be rewritten more concisely using HandlerFunc.
Rewriting the reference implementation:
We successfully rewrote the part using ServeHTTP(w ResponseWriter, r *Request).
By the way, the implementation of mux.Handle looks like this:
ServeMux
Let’s dive deeper into the shortened part:
The part mux.Handle("/", http.HandlerFunc(hello)) can be further simplified using HandleFunc, which internally handles some of the processing.
Considering the above, the rewritten code looks like this:
DefaultServeMux is essentially a variable that holds a pointer to a ServeMux struct. HandleFunc is a method that allows registering URL pattern matches to DefaultServeMux.
Server
Finally, let’s look at this part:
The content of s.ListenAndServe():
When no specific settings are needed for the Server, you can write it more concisely using ListenAndServe(). For details on Server settings, refer to golang.org - server.go.
Here’s the shorter version:
Using an anonymous function:
Thoughts
I was planning to create my own HTTP router package in Golang, so I did some research on the internal implementation of net/http. It seems to be quite extensible, making it relatively easy to create custom implementations.
Addendum
I implemented a URL router.