Browse Source

Get RoomID from request

master
Silke 4 years ago
parent
commit
b6b9241e36
  1. 28
      alertmanager-matrix.go
  2. 3
      matrix.go

28
alertmanager-matrix.go

@ -3,6 +3,7 @@ package main
import (
"encoding/json"
"flag"
"github.com/gorilla/mux"
matrix "github.com/matrix-org/gomatrix"
"log"
"net/http"
@ -10,16 +11,27 @@ import (
)
func handler(w http.ResponseWriter, r *http.Request) {
// Get room from request
roomID := mux.Vars(r)["room"]
if roomID[0] != '!' {
log.Print("Invalid room ID: ", roomID)
w.WriteHeader(http.StatusBadRequest)
return
}
// Parse the message
data := new(Message)
if err := json.NewDecoder(r.Body).Decode(data); err != nil {
log.Printf("Error parsing message: %s", err)
w.WriteHeader(http.StatusBadRequest)
return
}
// Create readable messages for Matrix
plain, html := formatAlerts(data.Alerts)
log.Printf("Sending message:\n%s", plain)
log.Printf("Sending message to %s:\n%s", roomID, plain)
if err := sendMessage(plain, html); err != nil {
if err := sendMessage(roomID, plain, html); err != nil {
log.Printf("Error sending message: %s", err)
w.WriteHeader(http.StatusInternalServerError)
}
@ -38,14 +50,12 @@ func main() {
flag.StringVar(&addr, "addr", ":4051", "Address to listen on.")
flag.StringVar(&homeserver, "homeserver", "https://matrix.org", "Homeserver to connect to.")
flag.StringVar(&roomID, "roomID", "", "Room ID to send alerts to.")
flag.StringVar(&userID, "userID", "", "User ID to connect with.")
flag.StringVar(&token, "token", "", "Token to connect with")
flag.StringVar(&token, "token", "", "Token to connect with.")
flag.Parse()
setStringFromEnv(&addr, "ADDR")
setStringFromEnv(&homeserver, "HOMESERVER")
setStringFromEnv(&roomID, "ROOM_ID")
setStringFromEnv(&userID, "USER_ID")
setStringFromEnv(&token, "TOKEN")
@ -53,10 +63,10 @@ func main() {
client, err = matrix.NewClient(homeserver, userID, token)
if err != nil {
log.Fatalf("Error connecting to Matrix: %s", err)
os.Exit(1)
}
log.Printf("Listening on %s", addr)
http.HandleFunc("/", handler)
http.ListenAndServe(addr, nil)
r := mux.NewRouter()
r.HandleFunc("/{room}", handler).Methods("POST")
log.Print("Listening on ", addr)
log.Fatal(http.ListenAndServe(addr, r))
}

3
matrix.go

@ -12,9 +12,8 @@ type MatrixMessage struct {
}
var client *matrix.Client
var roomID string
func sendMessage(plain, html string) error {
func sendMessage(roomID, plain, html string) error {
_, err := client.SendMessageEvent(roomID, "m.room.message",
&MatrixMessage{
MsgType: "m.text",

Loading…
Cancel
Save