Hacker News new | ask | show | jobs
by lazyjones 4443 days ago
The "Countries" example does not look correct to me. Go maps aren't safe for concurrent use (such as parallel REST API requests in this case) and need to be protected with a sync.RWMutex or similar, although it might work safely in some special cases (I'm not sure).
3 comments

You're right, the example does have a glaring bug - and I completely agree with you, examples should not include incorrect code.

Just to clarify, maps can be read concurrently without locking as long as you're not writing to them. As soon as any concurrent operation might make changes to the map (as the example does) you need locking, preferably a sync.RWMutex (a sync.Mutex will also work but will be way less efficient for no good reason).

I'm pretty sure the map here is not the important part. The example demonstrates how to use the rest interface to talk with a store. The actual implementation of the store is up to you.
I think it's important for example code to also be correct. If it needs to gloss over some details, put them in a function call that isn't defined.

Using an unprotected map here is incorrect.

Absolutely! Example code affects programming style and teaches people. It should be correct (and in good style), this is probably very much underrated.
Fair point, examples should be correct even on the part that is not the primary focus of the example. I’ve added a RWMutex to the "users" example, other examples improvements will come soon. https://github.com/ant0ine/go-json-rest-examples/commit/6983...