Last active
August 6, 2019 14:42
-
-
Save luza/61ce3876291e4a16686d2d7ed658bbba to your computer and use it in GitHub Desktop.
First untested(!) implementation of traffic-lights-demo
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"encoding/json" | |
"fmt" | |
"io/ioutil" | |
"log" | |
"net/http" | |
) | |
// возможные состояния светофора | |
const ( | |
lightRed = "red" | |
lightYellow = "yellow" | |
lightGreen = "green" | |
) | |
// структура для хранения состояния светофора | |
type trafficLights struct { | |
currentLight string `json:"currentLight"` | |
mutex sync.RWMutex `json:"-"` | |
} | |
// экземпляр светофора | |
var lights = trafficLights{ | |
currentLight: lightRed, | |
} | |
func main() { | |
// метод для получения текущего состояния светофора | |
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.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) | |
} | |
var newTrafficLights trafficLights | |
if err := json.Unmarshal(request, &newTrafficLights); err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
if err := validateRequest(&newTrafficLights); err != nil { | |
http.Error(w, err.Error(), http.StatusBadRequest) | |
return | |
} | |
lights = newTrafficLights | |
}) | |
// запуск сервера (блокирующий) | |
log.Fatal(http.ListenAndServe(":8080", nil)) | |
} | |
func validateRequest(lights *trafficLights) error { | |
if lights.currentLight != lightRed && | |
lights.currentLight != lightYellow && | |
lights.currentLight != lightGreen { | |
return fmt.Errorf("incorrect current light: %s", lights.currentLight) | |
} | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment