package controller import ( "github.com/gofiber/fiber/v2" "github.com/shirou/gopsutil/net" response "iptables-helper/pkg/resp" "iptables-helper/pkg/resp/errorx" "iptables-helper/pkg/utils/command" "iptables-helper/pkg/utils/iptables" ) func SetupController(r fiber.Router) { api := r.Group("/") getRuleInfo(api) addRule(api) delRule(api) getIfInfo(api) } // 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{} result, _ := cmder.ExecuteWithResult("sudo iptables -S") return ctx.JSON(response.NewResponse(iptables.Parse(result))) }) } // 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("")) } }) } // 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)) }) }