用到的技术:
代码仅供参考,不要直接拿去用,因为需要配合一个服务端去接收。
package main
import (
"bytes"
"encoding/json"
"fmt"
"github.com/urfave/cli"
"io/ioutil"
"log"
"net/http"
"os"
"time"
)
var (
alert_url = os.Getenv("ALERT_URL")
alert_receiver = os.Getenv("ALERT_RECEIVER")
alert_subject = "系统报警"
)
type MsgBody struct {
Receiver string `json:"receiver"`
Message [1]MessageBody `json:"message"`
Subject string `json:"subject"`
}
type MessageBody struct {
Level string `json:"level"`
Msg string `json:"msg"`
Time string `json:"start_time"`
}
func send(msg string) {
var msg_body [1]MessageBody
msg_body[0] = MessageBody{
Level: "INFO",
Time: time.Now().Format("2006-01-02 15:04:05"),
Msg: msg,
}
request := MsgBody{
Receiver: alert_receiver,
Message: msg_body,
Subject: alert_subject,
}
requestBody := new(bytes.Buffer)
json.NewEncoder(requestBody).Encode(request)
req, err := http.NewRequest("POST", alert_url, requestBody)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
panic(err)
}
fmt.Println()
defer resp.Body.Close()
fmt.Println("response Status:", resp.Status)
fmt.Println("response Headers:", resp.Header)
body, _ := ioutil.ReadAll(resp.Body)
fmt.Println("response Body:", string(body))
}
func main() {
app := cli.NewApp()
app.Name = "报警客户端"
app.Version = "1.0"
app.Usage = "设置环境变量"
app.Action = func(c *cli.Context) error {
if alert_url == "" || alert_receiver == "" {
panic("没有设置报警地址或者接受者")
os.Exit(1)
}
if len(c.Args()) == 0 {
panic("请输入告警消息")
os.Exit(1)
}
send(c.Args()[0])
return nil
}
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "url, u",
Usage: "报警的URL地址",
Value: os.Getenv("ALERT_URL"),
Destination: &alert_url,
}, cli.StringFlag{
Name: "receiver, r",
Usage: "报警的接受者",
Value: os.Getenv("ALERT_RECEIVER"),
Destination: &alert_receiver,
}, cli.StringFlag{
Name: "subjuect, s",
Usage: "报警主题",
Value: "系统报警",
Destination: &alert_subject,
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal(err)
}
}