I'm writing a small webserver program, and it does a lot of JSON decoding from POST requests coming in.
Initially I thought that instead of initializing a new json.Decoder
every time a request comes in, I have it as a global variable that gets called on every time and decodes concurrently with goroutines.
As a newcomer to Go, is this okay? Are there times when I shouldn't be doing this and classes will freak out due to not being thread safe (I guess "goroutine" safe would be better)?
In Go, json.NewDecoder takes an io.Reader as an input parameter and returns a *json.Decoder. Hence it is not possible to reuse the same Decoder since we have a different http.Request.Body (which implements io.Reader) for each POST request.
And as mentioned by Paul Hankin, you can't use go objects concurrently unless they're documented to be safe to use concurrently.
Examples :
http.Client & http.Transport
Clients and Transports are safe for concurrent use by multiple goroutines and for efficiency should only be created once and re-used.
Source
Maps
After long discussion it was decided that the typical use of maps did not require safe access from multiple goroutines.
Source
If you asked about reusing JSON decoder to avoid the duplication of code you could look at frameworks like Tigertonic and Go-Json-Rest.
On a side note you could look at ffjson to speed up JSON Decoding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With