kogia/notify.go

76 lines
1.5 KiB
Go

package main
import (
"encoding/json"
"encoding/xml"
"fmt"
"io"
"net/http"
)
type MessagePart struct {
XMLName xml.Name `xml:"s"`
Message string `json:"msg" xml:",chardata"`
Lang string `json:"lang" xml:"xml:lang,attr"`
}
type Notify struct {
Content []MessagePart `json:"content"`
Alert string `json:"alert"`
}
type NotifyHandler struct{}
func (n NotifyHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method != "POST" {
http.Error(w, "{\"errmsg\":\"Requête invalide.\"}", http.StatusBadRequest)
return
} else if r.ContentLength < 0 || r.ContentLength > 65536 {
http.Error(w, "{\"errmsg\":\"Requête trop longue ou de taille inconnue\"}", http.StatusRequestEntityTooLarge)
return
}
var body []byte
if r.ContentLength > 0 {
tmp := make([]byte, 1024)
for {
n, err := r.Body.Read(tmp)
for j := 0; j < n; j++ {
body = append(body, tmp[j])
}
if err != nil || n <= 0 {
break
}
}
}
var notif Notify
err := json.Unmarshal(body, &notif)
if err != nil {
http.Error(w, fmt.Sprintf("{\"errmsg\":\"%s\"}", err), http.StatusBadRequest)
return
}
if notif.Alert != "" {
fmt.Println(notif.Alert)
}
for _, cnt := range notif.Content {
if cnt.Lang == "" {
cnt.Lang = DefaultLang
}
output, err := xml.Marshal(cnt)
if err != nil {
fmt.Printf("error: %v\n", err)
} else {
//os.Stdout.Write(output)
SpeakerPipe.Write(output)
}
}
io.WriteString(SpeakerPipe, "\r\n")
}