Skip to content

Instantly share code, notes, and snippets.

@luza

luza/main.go

Last active Aug 6, 2019
Embed
What would you like to do?
First untested(!) implementation of traffic-lights-demo
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
You can’t perform that action at this time.