package main import ( "encoding/json" "flag" "fmt" "io" "log" "net/http" "os" ) const ( OPENED uint = 1 CLOSED uint = 2 CLOSING uint = 3 OPENING uint = 4 ) type gate struct { State uint `json:"state"` OpenTime uint `json:"open_time"` CloseTime uint `json:"close_time"` } type config struct { InnerGate gate `json:"inner_gate"` OuterGate gate `json:"outer_gate"` } var ( logger log.Logger = *log.Default() config_path string cache_inner_gate = gate{ State: 1, OpenTime: 2, CloseTime: 2, } cache_outer_gate = gate{ State: 1, OpenTime: 4, CloseTime: 2, } config_cache = config{ InnerGate: cache_inner_gate, OuterGate: cache_outer_gate, } ) func read_config() { data, err := os.ReadFile(config_path) if err != nil { logger.Printf("Unable to read %s", config_path) return } err = json.Unmarshal(data, &config_cache) if err != nil { logger.Print("Unable to evaluate config data") return } } func api_handler_gates(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-type", "application/json; charset=utf-8;") if r.Method == "GET" { res, err := json.Marshal(config_cache) if err != nil { res = json.RawMessage(`{"error": "` + err.Error() + `"}`) w.WriteHeader(http.StatusInternalServerError) w.Write(res) return } w.WriteHeader(http.StatusOK) w.Write(res) } else if r.Method == "PATCH" { var tmp config payload, _ := io.ReadAll(r.Body) err := json.Unmarshal(payload, &tmp) if err != nil { logger.Print(err) } logger.Print(r.Body) } else { w.WriteHeader(http.StatusMethodNotAllowed) } } func api_handler_gates_outer(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { res, err := json.Marshal(map[string]uint{"state": config_cache.OuterGate.State}) if err != nil { res = json.RawMessage(`{"error": "` + err.Error() + `"}`) w.WriteHeader(http.StatusInternalServerError) w.Write(res) return } w.WriteHeader(http.StatusOK) w.Write(res) } else if r.Method == "PATCH" { var tmp config payload, _ := io.ReadAll(r.Body) err := json.Unmarshal(payload, &tmp) if err != nil { res := json.RawMessage(`{"error": "` + err.Error() + `"}`) w.WriteHeader(http.StatusInternalServerError) w.Write(res) return } if tmp.OuterGate.State == 1 { config_cache.OuterGate.State = 3 // Schliessen => Schliesst } else if tmp.OuterGate.State == 2 { config_cache.OuterGate.State = 4 // Oeffnen => Oeffnet } // FIXME: add real gate handling w.WriteHeader(http.StatusOK) } else { w.WriteHeader(http.StatusMethodNotAllowed) } } func main() { flag.StringVar(&config_path, "c", "./config/config.json", "Specify path to find the config file. Default is ./config/config.json") flag.Parse() read_config() // API routes // Serve files from static folder http.Handle("/", http.FileServer(http.Dir("./svelte/build"))) // Serve api http.HandleFunc("/gates", api_handler_gates) http.HandleFunc("/gates/outer", api_handler_gates_outer) port := ":5000" fmt.Println("Server is running on port" + port) // Start server on port specified above log.Fatal(http.ListenAndServe(port, nil)) }