使用go写了一个简单的http接口
package main
import (
"fmt"
"net/http"
"os/exec"
"sync"
"time"
)
var (
requestCount int
lastTimestamp time.Time
mu sync.Mutex
)
const (
maxRequests = 30
resetDuration = time.Minute
)
// 假设 metricsData 是一个全局变量
var metricsData string
func ExecMatrixcmd(opera, ip string) string {
exec_matrixcmd := "/home/work/matrix/matrix-cli/matrix"
var execcmd string
if opera == "add" {
execcmd = "props_add"
cmd := exec.Command(exec_matrixcmd, "host", execcmd, ip, `{"EKS_CLUSTER_SYMBOL": "k8s-1"}`)
fmt.Println(cmd)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Sprintf("发生错误:%v", err)
}
return string(output)
} else if opera == "remove" {
execcmd = "props_remove"
cmd := exec.Command(exec_matrixcmd, "host", execcmd, ip, "EKS_CLUSTER_SYMBOL")
fmt.Println(cmd)
output, err := cmd.CombinedOutput()
if err != nil {
return fmt.Sprintf("发生错误:%v", err)
}
return string(output)
} else {
return "Invalid operation"
}
// cmd := exec.Command(exec_matrixcmd, "host", execcmd, ip, `{"EKS_CLUSTER_SYMBOL": "k8s-1"}`)
}
func matrixcmdHandler(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
now := time.Now()
if now.Sub(lastTimestamp) > resetDuration {
requestCount = 0
lastTimestamp = now
}
if requestCount >= maxRequests {
http.Error(w, "请求频率过高", http.StatusTooManyRequests)
return
}
requestCount++
// 获取名为 "opera" 的 URL 参数
opera := r.URL.Query().Get("opera")
// 获取名为 "ip" 的 URL 参数
ip := r.URL.Query().Get("ip")
if opera == "add" {
// 执行相关操作
result := ExecMatrixcmd("add", ip)
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, result)
} else if opera == "remove" {
// 执行相关操作
result := ExecMatrixcmd("remove", ip)
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, result)
} else {
http.Error(w, "无效的操作类型", http.StatusBadRequest)
}
}
func main() {
http.HandleFunc("/api/v1/matrix/", matrixcmdHandler)
port := 5119
fmt.Printf("服务器正在运行,地址:http://0.0.0.0:%d\n", port)
err := http.ListenAndServe(fmt.Sprintf(":%d", port), nil)
if err != nil {
fmt.Printf("启动服务器时发生错误:%v\n", err)
}
}
接口访问:
curl "http://xxxxxxxxxxxx:5119/api/v1/matrix/?opera=${add|remove}&ip=xx.xx.xx.xx"
标签:http,err,exec,opera,ip,fmt,接口,go From: https://www.cnblogs.com/Direction-of-efforts/p/18061150