go-route-gen
A tool I built to get type-safe routes between my Go backends and TypeScript frontends.
I built this tool during my internship to save myself from the repetitive task of syncing my backend routes with my frontend. I was tired of manually writing endpoint strings and making typos in path parameters.
Why I made this
I wanted a simple way to have the Go compiler tell the frontend what's available without having to switch to a heavy framework like tRPC.
How it works
- The Go Scraper: Written in Go, it uses the
go/astandgo/parserpackages to read my code and find where I've definednet/httproutes. It looks for strings likeMETHOD /pathand finds the path parameters. - The Frontend Client: This is a small TypeScript package I published to NPM that takes the map of routes and provides an Axios wrapper. It's strictly typed, so I can't request a route that doesn't exist.
Using Go's AST
The core part of this is how it reads the Go code. I originally tried using regex, but it broke on complicated Go formatting. Switching to the AST (Abstract Syntax Tree) made it much more reliable.
// A small part of the AST visitor I built
func (v *Visitor) Visit(node ast.Node) ast.Visitor {
call, ok := node.(*ast.CallExpr)
if !ok { return v }
sel, ok := call.Fun.(*ast.SelectorExpr)
if !ok { return v }
if sel.Sel.Name == "HandleFunc" || sel.Sel.Name == "Handle" {
if len(call.Args) > 0 {
if lit, ok := call.Args[0].(*ast.BasicLit); ok {
v.Routes = append(v.Routes, lit.Value)
}
}
}
return v
}
Installation
# Go CLI
go install github.com/Abdallemo/go-route-gen@latest
# Frontend Client
npm install @abdallemo/routegen-client
What's next
I want to try adding support for generating body schemas as well, so the request and response objects are typed too. I'm also thinking about better integration for custom authentication headers.