STASH
Stash is container for loading resources on demand.
Example
package main
import (
"fmt"
"github.com/noodlehaus/stash"
)
// our fake db connection
type mockDatabase struct{ id int }
// our demo custom resource
type customResource struct{ id int }
func main() {
sharedDemo()
factoryDemo()
protectedDemo()
}
func sharedDemo() {
// fake changing state
id := 0
// db connection loader is shared (ala singleton)
database, _ := stash.Shared(func() *mockDatabase {
// trigger state change
id++
return &mockDatabase{id: id}
})
// create stash and put in loader
resources := stash.New()
resources.Store("database", database)
res1, _ := resources.Fetch("database")
con1 := res1.(*mockDatabase)
res2, _ := resources.Fetch("database")
con2 := res2.(*mockDatabase)
// these 2 should have the same values because of stash.Shared()
fmt.Printf("db id: %d\n", con1.id)
fmt.Printf("db id: %d\n", con2.id)
}
func factoryDemo() {
// fake changing state
id := 0
// create our resource factory
factory, _ := stash.Factory(func() *customResource {
id++
return &customResource{id: id}
})
// create stash and inject resource
resources := stash.New()
resources.Store("resource", factory)
res1, _ := resources.Fetch("resource")
obj1 := res1.(*customResource)
res2, _ := resources.Fetch("resource")
obj2 := res2.(*customResource)
// these 2 should NOT have the same values because of stash.Factory()
fmt.Printf("resource id: %d\n", obj1.id)
fmt.Printf("resource id: %d\n", obj2.id)
}
func protectedDemo() {
// let's store a func() value
foo, _ := stash.Protected(func() {
fmt.Println("Hello, world!")
})
// store our func in stash
resources := stash.New()
resources.Store("foo", foo)
// fetch and use it
res, _ := resources.Fetch("foo")
res.(func())()
}