iptables-helper/internel/controller/controller.go

95 lines
2.7 KiB
Go
Raw Normal View History

2023-11-02 23:35:05 +08:00
package controller
import (
"github.com/gofiber/fiber/v2"
2023-11-03 00:01:00 +08:00
"github.com/shirou/gopsutil/net"
2023-11-02 23:35:05 +08:00
response "iptables-helper/pkg/resp"
2023-11-03 10:31:11 +08:00
"iptables-helper/pkg/resp/errorx"
2023-11-02 23:35:05 +08:00
"iptables-helper/pkg/utils/command"
"iptables-helper/pkg/utils/iptables"
)
func SetupController(r fiber.Router) {
api := r.Group("/")
getRuleInfo(api)
2023-11-03 10:31:11 +08:00
addRule(api)
delRule(api)
2023-11-03 00:01:00 +08:00
getIfInfo(api)
2023-11-02 23:35:05 +08:00
}
// getRuleInfo
// @Summary 获取 iptables 规则 信息
// @Description 获取 iptables 规则 信息
// @Tags Info
// @Accept json
// @Produce json
// @Success 200 {object} response.Response{data=iptables.Info}
// @Failure default {object} errorx.CodeErrorResponse
// @Router /info [get]
func getRuleInfo(api fiber.Router) {
api.Get("/info", func(ctx *fiber.Ctx) error {
cmder := command.Commander{}
2023-11-03 10:31:11 +08:00
result, _ := cmder.ExecuteWithResult("sudo iptables -S")
2023-11-02 23:35:05 +08:00
return ctx.JSON(response.NewResponse(iptables.Parse(result)))
})
}
2023-11-03 00:01:00 +08:00
2023-11-03 10:31:11 +08:00
// addRule
// @Summary 添加 iptables 规则
// @Description 添加 iptables 规则
// @Tags Info
// @Accept json
// @Produce json
// @Param vo body iptables.Rule true "规则"
// @Success 200 {object} response.Response{data=string}
// @Failure default {object} errorx.CodeErrorResponse
// @Router /rule/add [post]
func addRule(api fiber.Router) {
api.Post("/rule/add", func(ctx *fiber.Ctx) error {
rule := &iptables.Rule{}
_ = ctx.BodyParser(rule)
if err := errorx.ParseError(iptables.AddRule(*rule)); err != nil {
return ctx.JSON(err)
} else {
return ctx.JSON(response.NewResponse(""))
}
})
}
// delRule
// @Summary 删除 iptables 规则
// @Description 删除 iptables 规则
// @Tags Info
// @Accept json
// @Produce json
// @Param cmd query string true "根据 cmd 命令参数 删除指定规则"
// @Success 200 {object} response.Response{data=string}
// @Failure default {object} errorx.CodeErrorResponse
// @Router /rule/del/cmd [delete]
func delRule(api fiber.Router) {
api.Delete("/rule/del/cmd", func(ctx *fiber.Ctx) error {
cmd := ctx.Query("cmd")
if err := errorx.ParseError(iptables.DelRuleByCmd(cmd)); err != nil {
return ctx.JSON(err)
} else {
return ctx.JSON(response.NewResponse(""))
}
})
}
2023-11-03 00:01:00 +08:00
// getIfInfo
// @Summary 获取 网卡 信息
// @Description 获取 网卡 信息
// @Tags Info
// @Accept json
// @Produce json
// @Success 200 {object} response.Response{data=[]net.InterfaceStat}
// @Failure default {object} errorx.CodeErrorResponse
// @Router /if/info [get]
func getIfInfo(api fiber.Router) {
api.Get("/if/info", func(ctx *fiber.Ctx) error {
stat, _ := net.Interfaces()
return ctx.JSON(response.NewResponse(stat))
})
}