There is a test service with 2 requests. Those requests use a shared resource in the form of the ActualOrders
variable. Suppose that hundreds of parallel queries are running, there is a chance that a data conflict will occur in the ActualOrders variable. Especially when I'm looping through an array. To prevent this, will it be enough to use a Mutex
, as I did in the example below?
main.go:
package main
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"os"
"time"
)
type Order struct {
Room string `json:"room"`
UserEmail string `json:"email"`
From time.Time `json:"from"`
To time.Time `json:"to"`
}
var ActualOrders = []Order{}
var mutex sync.Mutex
func getOrders(responseWriter http.ResponseWriter, request *http.Request) {
userEmail := request.URL.Query().Get("email")
results := []Order{}
mutex.Lock()
for _, item := range ActualOrders {
if item.UserEmail == userEmail {
results = append(results, item)
}
}
mutex.Unlock()
bytes, err := json.Marshal(results)
if err != nil {
http.Error(responseWriter, err.Error(), http.StatusInternalServerError)
return
}
responseWriter.Header().Set("Content-type", "application/json")
responseWriter.WriteHeader(http.StatusOK)
responseWriter.Write(bytes)
}
func createOrder(responseWriter http.ResponseWriter, request *http.Request) {
var newOrder Order
requestBody := request.Body
defer request.Body.Close()
err := json.NewDecoder(requestBody).Decode(&newOrder)
if err != nil {
http.Error(responseWriter, err.Error(), http.StatusBadRequest)
return
}
mutex.Lock()
for _, order := range ActualOrders {
if !(newOrder.To.Before(order.From) || newOrder.From.After(order.To)) {
http.Error(responseWriter, http.StatusText(http.StatusConflict), http.StatusConflict)
return
}
}
ActualOrders = append(ActualOrders, newOrder)
mutex.Unlock()
responseWriter.WriteHeader(http.StatusCreated)
}
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/orders", getOrders)
mux.HandleFunc("/order", createOrder)
err := http.ListenAndServe(":8080", mux)
if errors.Is(err, http.ErrServerClosed) {
fmt.Printf("server closed\n")
} else if err != nil {
fmt.Printf("error starting server: %s\n", err)
os.Exit(1)
}
}
CodePudding user response:
Using a mutex as you did will protect from data races. Your implementation can be improved though.
You can use a RWMutex
, use a read-lock for the getOrders
function, and a lock for the createOrder
function. This will allow exclusive access to the ActualOrders
variable when you are writing to it, but shared reads will be allowed:
var mutex sync.RWMutex
func getOrders(responseWriter http.ResponseWriter, request *http.Request) {
...
mutex.RLock()
...
mutex.RUnlock()
}
func createOrder(responseWriter http.ResponseWriter, request *http.Request) {
...
mutex.Lock()
for _, order := range ActualOrders {
...
}
ActualOrders = append(ActualOrders, newOrder)
mutex.Unlock()
}