package main import ( "dsWatch/CheckUtil" "encoding/json" "fmt" "github.com/gin-gonic/gin" "net/http" "os" ) type configuration struct { Title string `json:"title"` Description string `json:"description"` Port int `json:"port"` Cmd string `json:"cmd",omitempty` Success bool `json:"success"` Message string `json:"message"` Host string `json:"host",omitempty` } func main() { r := gin.Default() //访问地址 : http://localhost:10000 r.GET("/", func(c *gin.Context) { //以只读方式打开config.json file, _ := os.Open("Config/Watch.json") defer file.Close() decoder := json.NewDecoder(file) var conf []configuration for decoder.More() { err := decoder.Decode(&conf) if err != nil { fmt.Println("Error:", err) } for i := 0; i < len(conf); i++ { //1、检查端口是否存在 if conf[i].Port > 0 { isUse := CheckUtil.PortInUse(conf[i].Host,conf[i].Port) if isUse { conf[i].Success = true //err!=nil表示端口启动正常 conf[i].Message = "GO!" } else { conf[i].Success = false //err==nil表示端口没有启动 conf[i].Message = "端口没有正确启动,请检查!" } } //如果是通过命令进行检查存在性的 if len(conf[i].Cmd) > 0 { result, err := CheckUtil.RunShell(conf[i].Cmd) if err != nil { conf[i].Success = false conf[i].Message = "执行命令时失败,请检查命令的可以用性!" } else { if len(result) > 0 { conf[i].Success = true conf[i].Message = "GO!" } else { conf[i].Success = false conf[i].Message = "服务没有正确启动,请检查!" } } } } //输出json数据 c.JSON(http.StatusOK, gin.H{ "status": 200, "data": conf, }) } }) r.Run(":10000") }