﻿# V8044\. Writing to a shared variable from an HTTP handler without synchronization may lead to a data race\. HTTP handlers are executed concurrently\.

The analyzer has detected an unsynchronized write to a global variable in the HTTP handler\. Each request is executed in a separate goroutines, so the same handler runs concurrently\. Writing to the shared variable from the handler without synchronization leads to a race condition\.

The handler is defined as a function, method, or function literal with two parameters: `http.ResponseWriter` and `*http.Request`\.

The example:

```cpp
var visits = map[string]int{}

func visitHandler(w http.ResponseWriter, r *http.Request) {
  page := r.URL.Query().Get("page")
  visits[page]++
  fmt.Fprintf(w, "visits: %d", visits[page])
}
```

Each request increments the visit counter in the global `visits` map\. When processing multiple requests simultaneously, several goroutines write to the shared `map`\. This can cause the entire server to crash with the error `fatal error: concurrent map writes`, which cannot be handled using `recover`\.

There are two ways to fix the problem\.

**Option N1\.** Use a thread\-safe [`sync.Map`](https://pkg.go.dev/sync#Map) with an atomic counter of the [`atomic.Int32`](https://pkg.go.dev/sync/atomic#Int32) type:

```cpp
var visits sync.Map

func visitHandler(w http.ResponseWriter, r *http.Request) {
  page := r.URL.Query().Get("page")

  actual, _ := visits.LoadOrStore(page, new(atomic.Int32))
  counter := actual.(*atomic.Int32)
  value := counter.Add(1)

  fmt.Fprintf(w, "visits: %d", value)
}
```

**Option N2\.** Use [`sync.Mutex`](https://pkg.go.dev/sync#Mutex):

```cpp
var (
  visitsMu sync.Mutex
  visits   = map[string]int{}
)

func visitHandler(w http.ResponseWriter, r *http.Request) {
  page := r.URL.Query().Get("page")

  visitsMu.Lock()
  visits[page]++
  value := visits[page]
  visitsMu.Unlock()

  fmt.Fprintf(w, "visits: %d", value)
}
```

For variables of other types, the race condition results in the loss of updates or the reading of inconsistent data\. A specific example is lazy initialization of the global variable in the handler:

```cpp
var service *Service

func serviceHandler(w http.ResponseWriter, r *http.Request) {
  if service == nil {
    service = NewService()
  }
  service.Handle(w, r)
}
```

Multiple requests may simultaneously encounter `service == nil` and create multiple instances of the service\.

For lazy initialization, use [`sync.Once`](https://pkg.go.dev/sync#Once):

```cpp
var (
  serviceOnce sync.Once
  service     *Service
)

func serviceHandler(w http.ResponseWriter, r *http.Request) {
  serviceOnce.Do(func() { 
    service = NewService()
  })
  service.Handle(w, r)
}
```