spacepanel_aggregator/main.go

82 lines
1.6 KiB
Go

package main
import (
"encoding/json"
"fmt"
io "io/ioutil"
"net/http"
"os"
"github.com/sirupsen/logrus"
flag "github.com/spf13/pflag"
"gopkg.in/yaml.v2"
)
var (
configFile string
addr string
)
func init() {
flag.StringVar(&configFile, "config", "conf.yml", "")
flag.StringVar(&addr, "addr", ":8080", "")
}
func main() {
flag.Parse()
if _, err := os.Stat(configFile); err == os.ErrNotExist {
logrus.Fatal("Config file not found")
flag.PrintDefaults()
return
}
logrus.Println("Welcome to Spacepanel Aggregator!")
logrus.Println()
logrus.Printf("Listen Address: %s", addr)
logrus.Printf("Config-File: %s", configFile)
bytes, err := io.ReadFile(configFile)
if err != nil {
logrus.Fatal(err)
}
var ledSpaceMap map[int][]string
err = yaml.Unmarshal(bytes, &ledSpaceMap)
if err != nil {
logrus.Fatalf("Error loading config file: %v", err)
}
spaceCount := 0
for _, spaces := range ledSpaceMap {
spaceCount += len(spaces)
}
fmt.Println("Loaded", len(ledSpaceMap), "LED-configs and", spaceCount, "spaces.")
aggregator := NewStateAggregator(ledSpaceMap)
server := http.Server{
Addr: addr,
}
http.HandleFunc("/leds", func(writer http.ResponseWriter, request *http.Request) {
data, err := json.Marshal(aggregator.GetLedStates())
if err != nil {
logrus.Error(err)
writer.WriteHeader(501)
return
}
writer.Header().Add("Content-Type", "application/json")
writer.Write(data)
})
server.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logrus.Infof("Request: %s %s %s", r.RemoteAddr, r.Method, r.URL)
http.DefaultServeMux.ServeHTTP(w, r)
})
logrus.Fatal(server.ListenAndServe())
}