Golang: storing/caching values to be served in following http requests -


i writing go webservices (also implementing webserver in go http.listenandserve). have map of structs keep in memory (with approximate data size of 100kb) used different http requests.

which best way achieve in go? in experience, better use global package variables or caching systems (like memcache/groupcache)?

in addition answers you've received, consider making use of receiver-curried method values , http.handlerfunc.

if data data loaded before process starts, go this:

type common struct {     data map[string]*data }  func newcommon() (*common, error) {     // load data     return c, err }  func (c *common) root(w http.responsewriter, r *http.request) {     // handler }  func (c *common) page(w http.responsewriter, r *http.request) {     // handler }  func main() {     common, err := newcommon()     if err != nil { ... }      http.handlefunc("/", common.root)     http.handlefunc("/page", common.page)      http.listenandserve(...) } 

this works nicely if of common data read-only. if common data read/write, you'll want have more like:

type common struct {     lock sync.rwmutex     data map[string]data // data should not have reference fields }  func (c *common) get(key string) (*data, bool) {     c.lock.rlock()     defer c.lock.runlock()     d, ok := c.data[key]     return &d, ok }  func (c *common) set(key string, d *data) {     c.lock.lock()     defer c.lock.unlock()     c.data[key] = *d } 

the rest same, except instead of accessing data through receiver's fields directly, you'd access them through getters , setters. in webserver of data being read, want rwmutex, reads can executed concurrently 1 another. advantage of second approach you've encapsulated data, can add in transparent writes and/or reads memcache or groupcache or of nature in future if application grows such need.

one thing defining handlers methods on object makes easier unit test them: can define table driven test includes values want , output expect without having muck around global variables.


Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -