This tutorial https://go.dev/doc/tutorial/web-service-gin uses package variable album
to read and write from http handlers.
However there is no synchronization applied to avoid race condition.
// postAlbums adds an album from JSON received in the request body.
func postAlbums(c *gin.Context) {
var newAlbum album
// Call BindJSON to bind the received JSON to
// newAlbum.
if err := c.BindJSON(&newAlbum); err != nil {
return
}
// Add the new album to the slice.
albums = append(albums, newAlbum) // <-- DATA RACE.
c.IndentedJSON(http.StatusCreated, newAlbum)
}
If this is intentional to keep the tutorial simple I think it makes sense to warn the reader about code limitations, because high level of concurrency is natural for http servers.
Or maybe it would be even better to avoid race with a different design.
Thanks.
Comment From: mvdan
This was brought up by @benhoyt in https://groups.google.com/g/golang-dev/c/kC7YZsHTw4Y/m/u0_d9lQoAwAJ; it seems like the response from @rsc was that they want to leave the tutorial as-is. I personally tend to agree with Ben, in that I don't particularly like that the tutorial is racy and that it arbitrarily chooses gin without any reasoning.
Comment From: giorgiozoppi
A better approach will be just using just standard HTTP or gorilla/mux that it has a wider usage in the community, Agreed about the data race. We mandate a correct approch in learning.
Comment From: cherrymui
This may be working as intended. But leave to @rsc @dmitshur to decide. Thanks.