Re:A quick and easy way to setup a RESTful JSON API in Go
by lazyjones on Saturday April 26, 2014 @06:42AM
(#7650961)
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).
[ Parent
| on HN ]
Re:A quick and easy way to setup a RESTful JSON API in Go
by hierro on Saturday April 26, 2014 @11:11AM
(#7651622)
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).
Re:A quick and easy way to setup a RESTful JSON API in Go
by rakoo on Saturday April 26, 2014 @07:21AM
(#7651046)
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.
Re:A quick and easy way to setup a RESTful JSON API in Go
by skj on Saturday April 26, 2014 @09:38AM
(#7651328)
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.
Re:A quick and easy way to setup a RESTful JSON API in Go
by lazyjones on Saturday April 26, 2014 @05:17PM
(#7652783)
Absolutely! Example code affects programming style and teaches people. It should be correct (and in good style), this is probably very much underrated.
Re:A quick and easy way to setup a RESTful JSON API in Go
by ant0ine on Saturday April 26, 2014 @12:40PM
(#7651967)
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...