cscsysbot/utils/uptimerobot/uptimerobot.go

122 lines
2.5 KiB
Go

package uptimerobot
import (
"fmt"
"net/http"
"strings"
"io/ioutil"
"encoding/json"
"time"
"net"
"os"
)
// Really basic, no pagination support
type Monitors struct {
Monitors []Monitor `json:"monitors"`
}
type Monitor struct {
ID int `json:"id"`
FriendlyName string `json:"friendly_name"`
URL string `json:"url"`
Type MonitorType `json:"type"`
Status MonitorStatus `json:"status"`
// Type specifc properties
Port interface{} `json:"port"`
}
type MonitorType int
const (
_ MonitorType = iota
MonitorTypeHTTP
MonitorTypeKeyword
MonitorTypePing
MonitorTypePort
)
func (t MonitorType) String() string {
switch t {
case MonitorTypeHTTP:
return "HTTP"
case MonitorTypeKeyword:
return "HTTP Keyword"
case MonitorTypePing:
return "Ping"
case MonitorTypePort:
return "Port"
}
return "Invalid"
}
type MonitorStatus int
const (
MonitorStatusPaused MonitorStatus = 0
MonitorStatusNotCheckedYet = 1
MonitorStatusUp = 2
MonitorStatusSeemsDown = 8
MonitorStatusDown = 9
)
func (s MonitorStatus) String() string {
switch s {
case MonitorStatusPaused:
return "Paused"
case MonitorStatusNotCheckedYet:
return "Not Checked Yet"
case MonitorStatusUp:
return "Up"
case MonitorStatusSeemsDown:
return "Seems Down"
case MonitorStatusDown:
return "Down"
}
return "Invalid"
}
func GetMonitors() (Monitors, error) {
var monitors Monitors
transport := &http.Transport{
Dial: (&net.Dialer{
Timeout: time.Second * 10,
}).Dial,
TLSHandshakeTimeout: time.Second * 10,
DisableKeepAlives: true,
}
net := http.Client{
Timeout: time.Second * 10,
Transport: transport,
}
url := "https://api.uptimerobot.com/v2/getMonitors"
payload := strings.NewReader(fmt.Sprintf("api_key=%s&format=json", os.Getenv("UPTIME_ROBOT_API_KEY")))
req, err := http.NewRequest("POST", url, payload)
if err != nil {
return monitors, err
}
req.Header.Add("content-type", "application/x-www-form-urlencoded")
req.Header.Add("cache-control", "no-cache")
res, err := net.Do(req)
if err != nil {
return monitors, err
}
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)
if err != nil {
return monitors, err
}
err = json.Unmarshal(body, &monitors)
if err != nil {
return monitors, err
}
return monitors, nil
}