I'm working on a simple Go REST API, using Mux. Most of the tutorials I've found suggested creating the router as follows:
- A
routes.go
file which contains a global array of all routes and all route handlers. - A
router.go
file which creates a router object and loops over the global array and registers everything to the router.
I'd rather use a different model:
- A
router.go
file instantiates a router object and has aRegisterRoute
function - Each file, representing a different object or component of the API, can call
RegisterRoute
and add additional routes to the router.
I have no idea how to do this, because it seems to require creating an initialization function for each file and calling it from main()
(which defeats the purpose). Is there any accepted way to do this?
You can use
func init()
. It is a special function which is called right before program execution, during package initialization.Here is an example of how to achieve what you want using gorilla/mux router, though it can be achieved with any other mux library.
This pattern is used by golang for example by
database/sql
andimage
packages. You can read a little bit more about this here: https://www.calhoun.io/why-we-import-packages-we-dont-actually-use-in-golang/