Code Reading of Golang HTTP Server

Overview

I took some notes while reading the internal code of an HTTP server in Go when I created a router.

github.com - bmf-san/goblin

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.

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.

Reference

Go: A Discussion on Custom Router Implementation