golang Uptime Robot API v2 命令行客户端与封装插件库uptimerobot的使用
Golang Uptime Robot API v2 命令行客户端与封装插件库uptimerobot的使用
简介
uptimerobot
是一个用于 Uptime Robot 网站监控服务的 Go 库和命令行客户端。它允许您搜索现有监视器、删除监视器、创建新监视器,并检查您的账户详情和警报联系人。
安装命令行客户端
要安装客户端二进制文件,请运行:
go get -u github.com/bitfield/uptimerobot
在Docker中运行命令行客户端
要在Docker容器中使用客户端,请运行:
docker container run bitfield/uptimerobot
使用命令行客户端
要查看客户端的使用帮助,请运行:
uptimerobot -h
设置您的API密钥
要使用客户端与您的Uptime Robot账户,您需要账户的主API密钥。有三种方法可以将API密钥传递给客户端:在配置文件中、在环境变量中或在命令行中。
在配置文件中
uptimerobot
客户端将读取您主目录或当前目录中名为 .uptimerobot.yaml
(或 .uptimerobot.json
,或Viper支持的任何其他扩展名)的配置文件。
例如,您可以将API密钥放在文件 $HOME/.uptimerobot.yaml
中,uptimerobot
将自动找到并读取它(将 XXX
替换为您自己的API密钥):
apiKey: XXX
在环境变量中
uptimerobot
将在名为 UPTIMEROBOT_API_KEY
的环境变量中查找API密钥:
export UPTIMEROBOT_API_KEY=XXX
uptimerobot ...
在命令行中
您还可以使用 --apiKey
标志将API密钥传递给 uptimerobot
客户端,如下所示:
uptimerobot --apiKey XXX ...
测试您的配置
要测试您的API密钥是否正确以及 uptimerobot
是否正确读取它,请运行:
uptimerobot account
您应该看到您的账户详情列出:
Email: j.random@example.com
Monitor limit: 300
Monitor interval: 1
Up monitors: 208
Down monitors: 2
Paused monitors: 0
列出联系人
uptimerobot contacts
命令将按ID号列出您配置的警报联系人:
uptimerobot contacts
ID: 0102759
Name: Jay Random
Type: 2
Status: 2
Value: j.random@example.com
ID: 2053888
Name: Slack
Type: 11
Status: 2
Value: https://hooks.slack.com/services/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
列出或搜索监视器
使用 uptimerobot search
列出所有"友好名称"或检查URL匹配特定字符串的监视器:
uptimerobot search www.example.com
ID: 780689017
Name: Example.com website
URL: https://www.example.com/
Status: Up
Type: HTTP
删除监视器
注意要删除的监视器的ID号,并运行 uptimerobot delete
:
uptimerobot delete 780689017
Monitor ID 780689017 deleted
暂停或启动监视器
注意要暂停的监视器的ID号,并运行 uptimerobot pause
:
uptimerobot pause 780689017
Monitor ID 780689017 paused
要恢复暂停的监视器,请使用监视器ID运行 uptimerobot start
:
uptimerobot start 780689017
Monitor ID 780689017 started
创建新监视器
运行 uptimerobot new URL NAME
创建一个新监视器:
uptimerobot new https://www.example.com/ "Example.com website"
New monitor created with ID 780689018
要创建配置了警报联系人的新监视器,请使用 -c
标志,后跟逗号分隔的联系人ID列表,不带空格:
uptimerobot new -c 0102759,2053888 https://www.example.com/ "Example.com website"
New monitor created with ID 780689019
确保监视器存在
有时您只想在相同URL的监视器尚不存在时创建新监视器。这在自动化中特别有用。为此,请运行 uptimerobot ensure URL NAME
:
uptimerobot ensure https://www.example.com/ "Example.com website"
Monitor ID 780689018 ensured
检查版本号
要查看您使用的命令行客户端版本,请运行 uptimerobot version
。
查看调试输出
当事情没有按预期进行时,您可以在命令行中添加 --debug
标志,以查看来自服务器的HTTP请求和响应的转储。
使用Go库
如果命令行客户端不完全符合您的需求,或者您想在自己的程序中使用Uptime Robot API访问,请使用以下方式导入库:
import "github.com/bitfield/uptimerobot/pkg"
通过调用 uptimerobot.New()
并传入API密钥来创建新的 Client
对象:
client = uptimerobot.New(apiKey)
一旦有了客户端,您就可以使用它来调用各种Uptime Robot API功能:
monitors, err := client.AllMonitors()
if err != nil {
log.Fatal(err)
}
for _, m := range monitors {
fmt.Println(m)
fmt.Println()
}
完整示例
以下是一个完整的Go程序示例,演示如何使用uptimerobot库:
package main
import (
"fmt"
"log"
"os"
"github.com/bitfield/uptimerobot/pkg"
)
func main() {
// 从环境变量获取API密钥
apiKey := os.Getenv("UPTIMEROBOT_API_KEY")
if apiKey == "" {
log.Fatal("请设置UPTIMEROBOT_API_KEY环境变量")
}
// 创建新的客户端
client := uptimerobot.New(apiKey)
// 获取所有监视器
monitors, err := client.AllMonitors()
if err != nil {
log.Fatal(err)
}
// 打印所有监视器信息
fmt.Println("当前监视器列表:")
for _, m := range monitors {
fmt.Printf("ID: %d\n", m.ID)
fmt.Printf("名称: %s\n", m.FriendlyName)
fmt.Printf("URL: %s\n", m.URL)
fmt.Printf("状态: %s\n", m.Status)
fmt.Println("------------------")
}
// 创建一个新监视器
newMonitor := uptimerobot.Monitor{
FriendlyName: "示例网站监控",
URL: "https://example.com",
Type: 1, // HTTP监控
}
createdMonitor, err := client.CreateMonitor(newMonitor)
if err != nil {
log.Fatal(err)
}
fmt.Printf("已创建新监视器,ID: %d\n", createdMonitor.ID)
// 删除监视器(示例,实际使用时请谨慎)
// if err := client.DeleteMonitor(createdMonitor.ID); err != nil {
// log.Fatal(err)
// }
// fmt.Printf("已删除监视器ID: %d\n", createdMonitor.ID)
}
错误和功能请求
如果您在 uptimerobot
客户端或库中发现错误,请打开问题。同样,如果您希望添加或改进功能,请通过问题告知我。
尚未实现Uptime Robot API的所有功能。欢迎提交拉取请求!
更多关于golang Uptime Robot API v2 命令行客户端与封装插件库uptimerobot的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html
更多关于golang Uptime Robot API v2 命令行客户端与封装插件库uptimerobot的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
Golang Uptime Robot API v2 客户端与封装库使用指南
Uptime Robot 是一个流行的网站监控服务,其 API v2 允许开发者以编程方式管理监控项。下面我将介绍如何使用 Golang 与 Uptime Robot API v2 交互,包括直接调用 API 和使用封装库 github.com/bitfield/uptimerobot
。
1. 直接调用 Uptime Robot API v2
首先,我们来看如何直接使用 HTTP 客户端与 API 交互:
package main
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
const (
apiKey = "your_api_key"
apiEndpoint = "https://api.uptimerobot.com/v2/"
)
type Monitor struct {
ID int `json:"id"`
FriendlyName string `json:"friendly_name"`
URL string `json:"url"`
Type int `json:"type"`
Status int `json:"status"`
Interval int `json:"interval"`
CreateDateTime int `json:"create_datetime"`
}
type GetMonitorsResponse struct {
Stat string `json:"stat"`
Pagination struct{} `json:"pagination"`
Monitors []Monitor `json:"monitors"`
}
func getMonitors() ([]Monitor, error) {
url := apiEndpoint + "getMonitors"
payload := map[string]string{
"api_key": apiKey,
"format": "json",
"logs": "1",
"response_times": "1",
}
jsonPayload, _ := json.Marshal(payload)
resp, err := http.Post(url, "application/json", bytes.NewBuffer(jsonPayload))
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
var response GetMonitorsResponse
if err := json.Unmarshal(body, &response); err != nil {
return nil, err
}
if response.Stat != "ok" {
return nil, fmt.Errorf("API request failed")
}
return response.Monitors, nil
}
func main() {
monitors, err := getMonitors()
if err != nil {
fmt.Printf("Error getting monitors: %v\n", err)
return
}
fmt.Println("Your Uptime Robot Monitors:")
for _, m := range monitors {
fmt.Printf("ID: %d, Name: %s, URL: %s, Status: %d\n",
m.ID, m.FriendlyName, m.URL, m.Status)
}
}
2. 使用 uptimerobot 封装库
github.com/bitfield/uptimerobot
是一个第三方库,提供了更简洁的 API 封装。
安装
go get github.com/bitfield/uptimerobot
使用示例
package main
import (
"fmt"
"log"
"github.com/bitfield/uptimerobot"
)
func main() {
// 创建客户端
client := uptimerobot.New("your_api_key")
// 获取所有监控项
monitors, err := client.GetMonitors()
if err != nil {
log.Fatal(err)
}
fmt.Println("Your Uptime Robot Monitors:")
for _, m := range monitors {
fmt.Printf("ID: %d, Name: %s, URL: %s, Status: %s\n",
m.ID, m.FriendlyName, m.URL, m.Status)
}
// 创建新监控项
newMonitor := uptimerobot.Monitor{
FriendlyName: "Example Site",
URL: "https://example.com",
Type: uptimerobot.TypeHTTP,
}
createdMonitor, err := client.CreateMonitor(newMonitor)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Created monitor with ID %d\n", createdMonitor.ID)
// 删除监控项
err = client.DeleteMonitor(createdMonitor.ID)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Deleted monitor with ID %d\n", createdMonitor.ID)
}
3. 命令行客户端实现
下面是一个简单的命令行客户端实现:
package main
import (
"flag"
"fmt"
"log"
"os"
"github.com/bitfield/uptimerobot"
)
var (
apiKey string
action string
name string
url string
monitorID int
)
func init() {
flag.StringVar(&apiKey, "key", "", "Uptime Robot API key")
flag.StringVar(&action, "action", "list", "Action to perform (list|create|delete)")
flag.StringVar(&name, "name", "", "Monitor friendly name (for create)")
flag.StringVar(&url, "url", "", "URL to monitor (for create)")
flag.IntVar(&monitorID, "id", 0, "Monitor ID (for delete)")
}
func main() {
flag.Parse()
if apiKey == "" {
apiKey = os.Getenv("UPTIMEROBOT_API_KEY")
if apiKey == "" {
log.Fatal("API key must be provided via -key flag or UPTIMEROBOT_API_KEY environment variable")
}
}
client := uptimerobot.New(apiKey)
switch action {
case "list":
listMonitors(client)
case "create":
createMonitor(client)
case "delete":
deleteMonitor(client)
default:
log.Fatalf("Unknown action: %s", action)
}
}
func listMonitors(client *uptimerobot.Client) {
monitors, err := client.GetMonitors()
if err != nil {
log.Fatal(err)
}
fmt.Println("Your Uptime Robot Monitors:")
for _, m := range monitors {
fmt.Printf("ID: %d, Name: %s, URL: %s, Status: %s\n",
m.ID, m.FriendlyName, m.URL, m.Status)
}
}
func createMonitor(client *uptimerobot.Client) {
if name == "" || url == "" {
log.Fatal("Both -name and -url are required for create action")
}
newMonitor := uptimerobot.Monitor{
FriendlyName: name,
URL: url,
Type: uptimerobot.TypeHTTP,
}
monitor, err := client.CreateMonitor(newMonitor)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Successfully created monitor with ID %d\n", monitor.ID)
}
func deleteMonitor(client *uptimerobot.Client) {
if monitorID == 0 {
log.Fatal("Monitor ID must be provided with -id flag for delete action")
}
err := client.DeleteMonitor(monitorID)
if err != nil {
log.Fatal(err)
}
fmt.Printf("Successfully deleted monitor with ID %d\n", monitorID)
}
4. 高级功能
监控间隔设置
// 创建每5分钟检查一次的监控
newMonitor := uptimerobot.Monitor{
FriendlyName: "Critical Service",
URL: "https://critical.example.com",
Type: uptimerobot.TypeHTTP,
Interval: 5, // 以分钟为单位
}
获取监控日志
logs, err := client.GetMonitorLogs(monitorID)
if err != nil {
log.Fatal(err)
}
for _, logEntry := range logs {
fmt.Printf("%s: %s (%dms)\n",
logEntry.DateTime, logEntry.Type, logEntry.Duration)
}
总结
本文介绍了三种与 Uptime Robot API v2 交互的方式:
- 直接使用 HTTP 客户端调用原始 API
- 使用
github.com/bitfield/uptimerobot
封装库 - 构建命令行客户端
封装库提供了更简洁的 API 和类型安全,适合大多数用例。对于特殊需求,可以直接调用 API。命令行客户端可以作为日常管理工具使用。
记得妥善保管你的 API 密钥,不要将其硬编码在代码中或提交到版本控制系统。