pidgin/carrier

change the package to the new host and run go mod tidy
draft default tip
2020-05-04, Gary Kramlich
599c20fd7100
change the package to the new host and run go mod tidy
package uptimerobot
import (
"fmt"
"net/http"
"bitbucket.org/ckvist/twilio/twirest"
log "github.com/sirupsen/logrus"
"keep.imfreedom.org/pidgin/carrier/config"
)
var (
client *twirest.TwilioClient
)
func validate(r *http.Request) int {
cfg := config.Get()
if r.Method != http.MethodGet {
return http.StatusMethodNotAllowed
}
err := r.ParseForm()
if err != nil {
return http.StatusBadRequest
}
// check that we have a token
tokens, found := r.Form["token"]
if !found || len(tokens) == 0 {
return http.StatusBadRequest
}
// verify the first token
if tokens[0] != cfg.TwilioWebhookToken {
return http.StatusBadRequest
}
return 0
}
func sendSMS(content string) (twirest.TwilioResponse, error) {
cfg := config.Get()
if client == nil {
client = twirest.NewClient(cfg.TwilioAccountSID, cfg.TwilioAuthToken)
}
// create the sms
msg := twirest.SendMessage{
Text: content,
To: cfg.TwilioRecipient,
From: cfg.TwilioPhoneNumber,
}
return client.Request(msg)
}
func Handler(w http.ResponseWriter, r *http.Request) {
// validate that the request has everything we need/want
if status := validate(r); status != 0 {
log.Debugf("status returned: %d", status)
w.WriteHeader(status)
return
}
// build the content of our sms
content := fmt.Sprintf(
"%s is %s",
r.Form["monitorFriendlyName"][0],
r.Form["alertTypeFriendlyName"][0],
)
// now send the sms
resp, err := sendSMS(content)
if err != nil {
log.Warnf("failed to send SMS: %v", err)
w.WriteHeader(resp.Status.Http)
fmt.Fprintf(w, "%s", err)
return
}
log.Debugf("status: %#v", resp.Status)
w.WriteHeader(http.StatusOK)
}