Globally requesting context mapping

Within a global request to request a context mapping solution, there is a single data structure in which you can look up the context for a request. The most popular implementation of this can be found within the Gorilla web toolkit, which can be found here: https://github.com/gorilla/context.

At a very high level, this code creates a single map[*http.Request]map[interface{}]interface{} global variable, which is available through the helper Get and Set functions. When used, if you 'Set' some contextual variable, the code will create a new map[interface{}]interface{}, and uses the request pointer of the request the contextual information belongs to as a map key in the global map, the value of which would be the newly created map[interface{}]interface{}. Then, the set call would add the key/value pair to the newly created map[interface{}]interface{}:

This design is not optimal due to the memory allocations that need to be performed for every single request. Each request that comes in needs to be inserted into this map. A new map needs to also be allocated to hold the contextual information, too. As we have already discussed, the Go web server creates a new goroutine for every single request that comes into the server. There could be potentially hundreds or thousands of concurrent goroutines handling requests within a web server. With all of these goroutines, there would be a lot of contention to read from and write to this global map. Moreover, within the design, unless you explicitly clear the context map entries, there is a potential memory leak situation, which is clear from the documentation.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.158.32