kas/conn/twilio/handler.go

51 lines
1.2 KiB
Go

package twilio
import (
"context"
"log"
"net/http"
"kas/cps"
)
func handler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
log.Printf("twilio receive hook: received %s request; only %s requests are supported",
r.Method, http.MethodPost)
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
err := r.ParseForm()
if err != nil {
log.Printf("twilio receive hook: couldn't parse form contents: %s", err)
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
message, err := MessageFromValues(r.Form)
if err != nil {
log.Printf("twilio receive hook: received an invalid message: %s", err)
http.Error(w, "invalid request", http.StatusBadRequest)
return
}
if !config.NumberAuthorized(message.Source) {
log.Printf("twilio receive hook: received message from unknown sender %v", message)
http.Error(w, "not authorized", http.StatusUnauthorized)
return
}
w.Write([]byte("accepted"))
response, err := cps.Handle(context.Background(), message.Body)
if err != nil {
log.Printf("twilio receive hook: %s", err)
}
err = Send(message.Source, response.String())
if err != nil {
log.Printf("twilio receive hook: %s", err)
}
}