I’ve a semi-static menu that ought to load from a database.
To make the load of menu quicker I ponder if there’s a technique to retailer this menus as some sort of world variables? Persistent or not.
You solely have to create a struct to map your knowledge. Additionally you should utilize a common cache library like GitHub – patrickmn/go-cache: An in-memory key:worth retailer/cache (much like Memcached) library for Go, appropriate for single-machine functions.
I don’t suppose you want an exterior dependency for one thing this easy. Create a worldwide variable of some type, guard it with a mutex so it’s thread-safe, then replace it primarily based on some form of interval. One thing like:
// AppMenu shops the worldwide app menu gadgets
sort AppMenu struct {
Objects []string
}
var (
muAppMenu = &sync.RWMutex{} // Guards `appMenu`.
appMenu AppMenu
)
// GetAppMenu returns the present app menu.
func GetAppMenu() AppMenu {
muAppMenu.RLock()
menu := appMenu
muAppMenu.RUnlock()
return menu
}
// SetAppMenu units the app menu.
func SetAppMenu(menu AppMenu) {
muAppMenu.Lock()
appMenu = menu
muAppMenu.Unlock()
}
You might then someplace in your predominant operate spin up a goroutine to replace your menu merchandise property periodically:
// Context for our goroutine
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
// Spin up goroutine to replace app menu gadgets each 30 seconds
go func() {
t := time.NewTicker(30 * time.Second)
defer t.Cease()
for {
choose {
case <-ctx.Carried out():
return // exit goroutine
case <-t.C:
menuItems := getMenuItemsFromDBOrWhatever()
SetAppMenu(menuItems)
}
}
}()
Once more, you COULD add a dependency, however I don’t suppose you want one. Additionally observe that you’d presumably have to populate the menu as soon as earlier than the ticker’s first tick. For extra particulars as to why:
I do hope I can keep away from dependencies. However there isn’t any want for redraw AFIAK. The menu must be static and tailor-made dynamically for every person. My aim is to interchange this Javascript code with Go if potential. Transfer this menu creation from browser to Go (Go templates) as a substitute