Skip to content

Commit

Permalink
Hadr demo (#14)
Browse files Browse the repository at this point in the history
* Added Habr demo project

* Added mutex (#13)
  • Loading branch information
luza authored Aug 13, 2019
1 parent e05dfce commit c14cadf
Showing 1 changed file with 10 additions and 1 deletion.
11 changes: 10 additions & 1 deletion examples/traffic-lights-demo/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"io/ioutil"
"log"
"net/http"
"sync"
)

// возможные состояния светофора
Expand All @@ -17,7 +18,8 @@ const (

// структура для хранения состояния светофора
type trafficLights struct {
CurrentLight string `json:"currentLight"`
CurrentLight string `json:"currentLight"`
mutex sync.RWMutex `json:"-"`
}

// экземпляр светофора
Expand All @@ -35,16 +37,23 @@ func main() {
func initServer() {
// метод для получения текущего состояния светофора
http.HandleFunc("/light/get", func(w http.ResponseWriter, r *http.Request) {
lights.mutex.RLock()
defer lights.mutex.RUnlock()

resp, err := json.Marshal(lights)
if err != nil {
log.Fatal(err)
}

w.Header().Add("Content-Type", "application/json")
w.Write(resp)
})

// метод для установки нового состояния светофора
http.HandleFunc("/light/set", func(w http.ResponseWriter, r *http.Request) {
lights.mutex.Lock()
defer lights.mutex.Unlock()

request, err := ioutil.ReadAll(r.Body)
if err != nil {
log.Fatal(err)
Expand Down

0 comments on commit c14cadf

Please sign in to comment.