Overview
I took some notes while reading the internal code of an HTTP server in Go when I created a router.
Code Reading of HTTP Server
Basic Form
This is the form of code you often see when starting with Go.
Various components are omitted to achieve this form.
Detailed Form Without Omissions
This is the detailed form of the basic example above, without any omissions. We will check step by step how the basic form is implemented.
Replacing the Handler
First, replacing the Handler.
ServeHTTP can be replaced with HandlerFunc, which is an alias for a function type.
cf.
Using DefaultServeMux
Replace mux with DefaultServeMux.
DefaultServeMux contains a structure of type ServeMux.
It implements a function called HandlerFunc to register routing to the mux.
cf.
- DefaultServeMux
- func (mux *ServeMux) HandlerFunc(pattern string, handler func(ResponseWriter, *Request))
Using ListenAndServe()
You can use ListenAndServe() without creating a Server structure (http.Server{}).
cf.
This brings us back to the initial basic form.
Summary
When creating an API server, you might not usually think about these details, but knowing them can be helpful when you want to extend functionality.
When creating a router, you just need to be aware of the http.Handler interface and create a mux accordingly.