+ 实现基础 web 服务,提供 /ping、/list、/stop 路由

This commit is contained in:
2024-07-03 23:39:17 +08:00
parent a5688e3426
commit 245fba4ed0
7 changed files with 422 additions and 0 deletions

74
src/services.go Normal file
View File

@@ -0,0 +1,74 @@
package main
import (
"net/http"
"strconv"
"github.com/gin-gonic/gin"
)
type Service struct {
Port int
}
func (s Service) Run() {
r := gin.Default()
r.GET("/", func(c *gin.Context) {
// 重定向到 /ping
c.Redirect(http.StatusMovedPermanently, "/ping")
})
r.GET("/ping", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"code": 0,
"data": gin.H{
"message": "pong",
},
})
})
r.GET("/list", func(c *gin.Context) {
name := c.Query("name")
ps := ListProcess(name)
c.JSON(http.StatusOK, gin.H{
"code": 0,
"data": ps,
})
})
r.GET("/listps", func(c *gin.Context) {
name := c.Query("name")
ps := ListProcessesUsingPowerShell(name)
c.JSON(http.StatusOK, gin.H{
"code": 0,
"data": ps,
})
})
r.POST("/stop", func(c *gin.Context) {
var p Process
if err := c.ShouldBindJSON(&p); err == nil {
ps, err := StopProcess(p.Pid)
if err == nil {
c.JSON(http.StatusOK, gin.H{
"code": 0,
"data": gin.H{
"message": "A termination signal has been sent",
"process": ps,
},
})
} else {
c.JSON(http.StatusBadRequest, gin.H{
"code": 1,
"data": gin.H{
"message": "An unknown error occurred, see error for details",
"error": err.Error(),
},
})
}
}
})
r.Run(":" + strconv.Itoa(s.Port))
}