Tuesday, October 8, 2024
HomeGolangAm I utilizing the context accurately to maintain monitor of the connection?...

Am I utilizing the context accurately to maintain monitor of the connection? – Getting Assist


For every http request that my server receives I create a context by including as worth the pointer of a struct:

sort BaseKey string
sort Tracker struct{ 
	Log []string
}
[...]
ctx := context.WithValue(r.Context(), BaseKey("someUniqueKey"), *Tracker{})
r = r.WithContext(ctx)

// (Truly I take advantage of http.Server.BaseContext however
// let's put it like this for simplicity's sake)

Then each time I run a operate it reads the context and will get the Tracker struct then writes in it the motion to execute contained in the Tracker.Log slice, that’s, in the entire tree of calls wanted to meet the request a helpful string is added for debugging, when there may be an error the entire Tracker.Log slice is joined and concatenated with the error and saved regionally within the server log.

This sounds nice however I used to be pondering, doesn’t this devour a whole lot of reminiscence per request? Suppose I’ve 1000 requests and so they all work and if that’s the case the Tracker.Log slice can be completely ignored as it is just wanted when there may be an error, then this interprets into ineffective reminiscence consumption.

Ought to I be involved in regards to the quantity of reminiscence for use within the Tracker.Log slice? What different various do I’ve to realize this?

An possibility that occurred to me (however actually I see sophisticated to implement it), is that the Tracker.Log slice ought to solely be written when there may be an error, that’s to say we’d go from backside to prime and after we arrive to the start line we’d register the error.

If I didn’t clarify nicely think about this tree:

-origin
	-somefunction
		-anotherfunction
		-childfunction

If childfunction fails it is going to log the error within the Tracker.Log slice, then anotherfunction will know that there was an error so it is going to log within the slice what it was attempting to do, and once more it is going to return an error to somefunction and it’ll repeat the method, and so forth till we get to origin the place we lastly shut the connection and log the error within the server, this fashion the slice would solely be crammed when there may be an error.

Which of the 2 strategies is extra frequent?, in actual fact is even legitimate the primary possibility how I’m initially doing it?, do you assume that the reminiscence consumption of the primary possibility is just not very severe?

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments