Overview
I created a custom URL router in Golang and documented the process of its implementation.
Preparation
Here’s a summary of the preparations I made before implementing the URL router.
Data Structures and Algorithms
I considered the logic for how URLs should be matched.
Many libraries use tree structures as their data structure, so I explored which type of tree structure to adopt. Among trees optimized for string searches, radix trees seemed to offer the best time and memory efficiency. However, I found the implementation too challenging and decided to use a simpler and more familiar structure: the trie.
Reading the net/http Code
To implement the router as an extension of the multiplexer in net/http, I needed to understand its internal workings to some extent.
Refer to Code Reading of Golang's HTTP Server.
Reading Implementations of Various Routers
I reviewed various router implementations for reference. See the repository links below.
Others
Here’s an article I wrote previously summarizing URL routing.
bmf-tech.com/posts/tags/URLルーティング
Implementation
Refer to github.com - goblin.
The basic idea was to adapt the trie structure into a more user-friendly form. However, I struggled several times with handling path parameters. Supporting regular expressions wasn’t too difficult; it was just a matter of preparing a DSL, but handling the DSL required some finesse.
During the implementation process, I wrote tests in parallel and repeatedly debugged step-by-step. By constantly tracking how the data structure changed, I felt my debugging skills improved over time.
Since I don’t usually write this kind of logic, it was undoubtedly a good coding exercise.
Future tasks are listed as issues in the repository, and I plan to refine the implementation whenever I have free time.
References
Repositories
Repositories that served as references for design and implementation:
- github - importcjj/trie-go
- github - julienschmidt/httprouter
- github - gorilla/mux
- github - xhallix/go-router
- github - gowww/router
- github - go-chi/chi
- github - go-ozzo/ozzo-routing
Articles
Articles I referred to during implementation: