Object-commander
is an easy manager for the objects’ initialization and release. In addition, you can access the them with a global container mechanism everywhere without introducing ohter library dependencies.
In golang, we mainly rely on the init
function to handle the object’s initialization and maybe other things to run when importing the package. Indeed, it’s a powerful feature but it introduces a side effect
! Try to imagine that you get a slow startup of your application by just importing a package. When digging into the package, you find there is a time-consuming function in the init
function. Surprised! Can you imagine if the situations appear everywhere?
Implicity makes codes hard to maintain. Explicity is the rescue. I want the initialization to be clear as I command. For example, you can clearly describe the procedure to initialize the resources(ex. db connection, redis connection, etc.) before running your service. I will show the example usage below.
go get -u github.com/jgebang/object-commander
- no external dependencies
- make your initialization explicity
- reduce the opportunity of circular import
Bootstrap relies on the a minimum container which stores or creates the instance from the resources have been registered.
Define a Manager
structure to handle the resource’s initialization and release and put it the Boot
function. This will ensure the setup is run before starting the main procedure.
var dbManager = Manager {
ID: Identity("db"),
Start: func() string {
return "db"
}
Close: func(c *Container) error {
// release the resource
return nil
}
}
// in your main.go
b := NewBootstrap(nil)
steps := []Manager{
dbManager,
}
b.Boot(steps, false).Run(func() {
// do something for you main application
// ex.
// run server
})