79 lines
1.8 KiB
Go
79 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/rs/cors"
|
|
)
|
|
|
|
const PORT = "8080"
|
|
|
|
func main() {
|
|
sseBroker := NewSSEBroker()
|
|
checker := NewHealthChecker(sseBroker)
|
|
|
|
corsHandler := cors.New(cors.Options{
|
|
AllowedOrigins: []string{"*"},
|
|
AllowedMethods: []string{"GET"},
|
|
AllowedHeaders: []string{"Content-Type"},
|
|
AllowCredentials: false,
|
|
}).Handler(http.DefaultServeMux)
|
|
|
|
go func() {
|
|
ticker := time.NewTicker(30 * time.Second)
|
|
defer ticker.Stop()
|
|
for {
|
|
checker.CheckAll()
|
|
<-ticker.C
|
|
}
|
|
}()
|
|
|
|
http.HandleFunc("/status", func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path == "/status" {
|
|
statuses := checker.GetStatuses()
|
|
w.Header().Set("Content-Type", "application/json")
|
|
err := json.NewEncoder(w).Encode(statuses)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
}
|
|
} else if strings.HasPrefix(r.URL.Path, "/status/") {
|
|
url := strings.TrimPrefix(r.URL.Path, "/status/")
|
|
status, ok := checker.GetStatus(url)
|
|
if !ok {
|
|
http.Error(w, "Not found", http.StatusNotFound)
|
|
return
|
|
}
|
|
w.Header().Set("Content-Type", "application/json")
|
|
err := json.NewEncoder(w).Encode(status)
|
|
if err != nil {
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
}
|
|
}
|
|
|
|
})
|
|
|
|
http.HandleFunc("/events", func(w http.ResponseWriter, r *http.Request) {
|
|
sseBroker.Handler(w, r)
|
|
})
|
|
|
|
log.Println("Serving on port " + PORT)
|
|
log.Fatal(http.ListenAndServe(":"+PORT, corsHandler))
|
|
|
|
//quit := make(chan os.Signal, 1)
|
|
//signal.Notify(quit, os.Interrupt)
|
|
//<-quit
|
|
//
|
|
//log.Println("Shutdown Server ...")
|
|
//
|
|
//ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
|
//defer cancel()
|
|
//if err := httpServer.Shutdown(ctx); err != nil {
|
|
// log.Fatal("Server Shutdown:", err)
|
|
//}
|
|
|
|
}
|