LamerAlert/sources/generic_rest.go

51 lines
918 B
Go
Raw Normal View History

2019-12-24 12:20:27 +00:00
package sources
import (
"io/ioutil"
"net/http"
"time"
pubsub "github.com/alash3al/go-pubsub"
"github.com/gorilla/mux"
"code.chrissexton.org/cws/lameralert/event"
)
type GenericRest struct {
broker *pubsub.Broker
router *mux.Router
}
func (gr *GenericRest) GetTopics() []string {
return []string{"REST"}
}
func NewGenericRest(r *mux.Router) *GenericRest {
gr := &GenericRest{
router: r,
broker: pubsub.NewBroker(),
}
go gr.serve()
return gr
}
func (gr *GenericRest) GetSender() *pubsub.Broker {
return gr.broker
}
func (gr *GenericRest) ping(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body)
defer r.Body.Close()
payload := map[string]string{"body": string(body)}
ev := event.Event{
Time: time.Now(),
Error: nil,
Payload: payload,
}
gr.broker.Broadcast(ev, gr.GetTopics()[0])
}
func (gr *GenericRest) serve() {
gr.router.HandleFunc("", gr.ping)
}