vendredi 23 novembre 2018

Registry design pattern in Golang

I'm looking for some kind of registry design pattern were the consumers can register themselves at a registry and the caller does not need to know about concrete types. I'm sure this can be done with some of the existing dependency injection frameworks. But maybe someone knows a way to do it in vanilla Golang?

Scenario

Let's assume we're writing a web service with n endpoints. Each endpoint is represented by a Controller.

type Controller interface {
    Register(router *mux.Router)
}

The concrete controllers will implement the Register method to bind their URLs to the router. To initialize the HTTP server we will do something like the pseudo code below.

controller1 := Controller1{}
controller1.Register(router)
controller2 := Controller2{}
controller2.Register(router)
controller3 := Controller3{}
...
http.Server{router}.Listen()

The problem

To register the controllers I need some central place that has to know every single concrete controller. There is an explicit dependency and every time I implement a new controller, I have to add it there.

Question

I'm looking for a way to register new controllers dynamically at some sort of registry. The controller itself should be responsible to make this happen. So when I'm starting the web server I want to do it like below.

for _, controller := range registry.AllControllers() {
    controller.Register(router)
}
http.Server{router}.Listen()

What would be an elegant way to implement this pattern in Golang?

Aucun commentaire:

Enregistrer un commentaire