LamerAlert/lameralert.go

93 lines
2.2 KiB
Go

package lameralert
import (
"net/http"
"github.com/gorilla/mux"
"github.com/rs/zerolog/log"
"code.chrissexton.org/cws/lameralert/config"
"code.chrissexton.org/cws/lameralert/mapping"
"code.chrissexton.org/cws/lameralert/sinks"
"code.chrissexton.org/cws/lameralert/sources"
)
type Connection struct {
source sources.Source
sink sinks.Sink
options map[string]interface{}
}
func NewConnection(from sources.Source, to sinks.Sink) Connection {
for _, topic := range from.GetTopics() {
to.Subscribe(from.GetSender(), topic)
}
return Connection{
source: from,
sink: to,
}
}
func logger(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Do stuff here
log.Debug().Msgf("%s - %s", r.Method, r.RequestURI)
// Call the next handler, which can be another middleware in the chain, or the final handler.
next.ServeHTTP(w, r)
})
}
func Setup() chan bool {
r := mux.NewRouter()
r.Use(logger)
c := config.New(r.PathPrefix("/config").Subrouter())
ch := make(chan bool)
mappings := c.GetMapping("mappings", mapping.Example())
//mappings := mapping.Example()
//c.SetMapping("mappings", mappings)
srcs := map[string]sources.Source{}
snks := map[string]sinks.Sink{}
for _, source := range mappings.Sources {
var src sources.Source
// TODO: Move this logic out to the sources package
switch source.Type {
case "GenericRest":
path := source.Config["prefix"]
src = sources.NewGenericRest(r.PathPrefix(path).Subrouter())
case "RSS":
path := source.Config["prefix"]
url := source.Config["URL"]
src = sources.NewRSS(c, r.PathPrefix(path).Subrouter(), source.Name, url)
}
srcs[source.Name] = src
}
for _, sink := range mappings.Sinks {
var snk sinks.Sink
// TODO: Move this logic out to the sinks package
switch sink.Type {
case "Console":
snk = sinks.NewConsoleID(c, sink.Config["ID"])
case "Pushover":
var err error
snk, err = sinks.NewPushover(c, sink.Name)
if err != nil {
log.Fatal().Msgf("Error setting up pushover: %w", err)
}
}
snks[sink.Name] = snk
}
for _, m := range mappings.Mappings {
src := srcs[m.From]
snk := snks[m.To]
NewConnection(src, snk)
}
http.ListenAndServe(":9090", r)
return ch
}