Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix concurrent read/write of map #55

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
21 changes: 16 additions & 5 deletions cookbook/google-app-engine/users.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"net/http"
"sync"

"github.com/labstack/echo"
"github.com/labstack/echo/middleware"
Expand All @@ -12,14 +13,18 @@ type (
ID string `json:"id"`
Name string `json:"name"`
}
usersMap struct {
sync.RWMutex
users map[string]user
}
)

var (
users map[string]user
usersStore usersMap
)

func init() {
users = map[string]user{
usersStore.users = map[string]user{
"1": user{
ID: "1",
Name: "Wreck-It Ralph",
Expand All @@ -41,14 +46,20 @@ func createUser(c echo.Context) error {
if err := c.Bind(u); err != nil {
return err
}
users[u.ID] = *u
usersStore.Lock()
defer usersStore.Unlock()
usersStore.users[u.ID] = *u
return c.JSON(http.StatusCreated, u)
}

func getUsers(c echo.Context) error {
return c.JSON(http.StatusOK, users)
usersStore.RLock()
defer usersStore.RUnlock()
return c.JSON(http.StatusOK, usersStore.users)
}

func getUser(c echo.Context) error {
return c.JSON(http.StatusOK, users[c.Param("id")])
usersStore.RLock()
defer usersStore.RUnlock()
return c.JSON(http.StatusOK, usersStore.users[c.Param("id")])
}