Skip to content

Commit

Permalink
Add mutex in order to avoid data races possibly caused by multiple re…
Browse files Browse the repository at this point in the history
…quests
  • Loading branch information
mrekucci committed May 4, 2016
1 parent 0a74299 commit 80792a3
Showing 1 changed file with 19 additions and 3 deletions.
22 changes: 19 additions & 3 deletions internal/task/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import (
"log"
"net/http"
"strconv"
"sync"
)

// Path specifies the task resource path.
Expand All @@ -32,7 +33,10 @@ func notFoundError(err error) *requestError {
return &requestError{err, http.StatusNotFound}
}

var tasks = NewManager()
var (
mu sync.RWMutex
tasks = NewManager()
)

var filters = map[string]Filter{
"isDone": func(t *Task) bool { return t.Done },
Expand Down Expand Up @@ -97,7 +101,10 @@ func create(w http.ResponseWriter, r *http.Request) error {
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
return badRequestError(err)
}
if _, err := tasks.Create(req.Title); err != nil {
mu.Lock()
_, err := tasks.Create(req.Title)
mu.Unlock()
if err != nil {
return badRequestError(err)
}
return nil
Expand All @@ -109,6 +116,8 @@ func read(w http.ResponseWriter, r *http.Request) error {
if err != nil {
return badRequestError(err)
}
mu.RLock()
defer mu.RUnlock()
t, ok := tasks.Find(id)
if !ok {
return notFoundError(fmt.Errorf("task id: %d doesn't exists", id))
Expand All @@ -118,6 +127,8 @@ func read(w http.ResponseWriter, r *http.Request) error {

// readAll handles requests for the reads of all tasks.
func readAll(w http.ResponseWriter, r *http.Request) error {
mu.RLock()
defer mu.RUnlock()
t := tasks.All()

// Apply filter.
Expand Down Expand Up @@ -151,7 +162,10 @@ func update(w http.ResponseWriter, r *http.Request) error {
if t.ID != id {
return badRequestError(fmt.Errorf("inconsistent task IDs"))
}
if _, ok := tasks.Find(id); !ok {
mu.Lock()
defer mu.Unlock()
_, ok := tasks.Find(id)
if !ok {
return notFoundError(fmt.Errorf("task id: %d doesn't exists", id))
}
return tasks.Update(t)
Expand All @@ -163,6 +177,8 @@ func delete(w http.ResponseWriter, r *http.Request) error {
if err != nil {
return badRequestError(err)
}
mu.Lock()
defer mu.Unlock()
return tasks.Delete(id)
}

Expand Down

0 comments on commit 80792a3

Please sign in to comment.