I had the day off from work today, so I decided to do something different.
I built an HTTP server from scratch in Go to understand what really happens under the hood before a framework returns a fancy response.
In this first iteration, I managed to set up a TCP listener, handle clients in parallel, and manually return a valid JSON response.
The most interesting part of this exercise was tackling the framing problem. TCP is just a stream of bytes; it doesn’t know what a message is. I had to use
bufio to read line by line until I reached \r\n\r\n and then rely on the Content-Length header to know exactly how many bytes to read from the body.
Obviously, right now it’s very basic. It has no timeouts, a header without a colon throws a panic, and the status codes are hardcoded. But I don’t plan on becoming the next Caddy 🦖, Seeing how raw bytes turn into a functional web request is totally worth it.
Check it out in my repository:
https://github.com/Petox03/malport
P.S.: Yes, I built my project with Keim 🌱GitHubGitHub - Petox03/malport: An attempt to build an HTTP server “from scratch” using the net library in GoAn attempt to build an HTTP server “from scratch” using the net library in Go - Petox03/malport
commit f690b3a
Welp, I just completed a second iteration of the HTTP server. I moved on to modeling actual structs and responses.
- I implemented safe parsing of the Request Line (Method, Route, HTTP Version).
- I handled errors defensively for malformed headers, and corrupt Content-Length…