添加规则支持插入或追加

This commit is contained in:
zxb 2023-11-06 13:30:57 +08:00
parent dbef6669b1
commit 6ba0c8cb20
5 changed files with 29 additions and 3 deletions

View File

@ -130,6 +130,13 @@ const docTemplate = `{
"schema": { "schema": {
"$ref": "#/definitions/iptables.Rule" "$ref": "#/definitions/iptables.Rule"
} }
},
{
"type": "boolean",
"description": "是否插入第一条(高优先级),否则为追加",
"name": "isInsert",
"in": "query",
"required": true
} }
], ],
"responses": { "responses": {

View File

@ -123,6 +123,13 @@
"schema": { "schema": {
"$ref": "#/definitions/iptables.Rule" "$ref": "#/definitions/iptables.Rule"
} }
},
{
"type": "boolean",
"description": "是否插入第一条(高优先级),否则为追加",
"name": "isInsert",
"in": "query",
"required": true
} }
], ],
"responses": { "responses": {

View File

@ -211,6 +211,11 @@ paths:
required: true required: true
schema: schema:
$ref: '#/definitions/iptables.Rule' $ref: '#/definitions/iptables.Rule'
- description: 是否插入第一条(高优先级),否则为追加
in: query
name: isInsert
required: true
type: boolean
produces: produces:
- application/json - application/json
responses: responses:

View File

@ -61,14 +61,16 @@ func getRuleInfo(api fiber.Router) {
// @Accept json // @Accept json
// @Produce json // @Produce json
// @Param vo body iptables.Rule true "规则" // @Param vo body iptables.Rule true "规则"
// @Param isInsert query bool true "是否插入第一条(高优先级),否则为追加"
// @Success 200 {object} response.Response{data=string} // @Success 200 {object} response.Response{data=string}
// @Failure default {object} errorx.CodeErrorResponse // @Failure default {object} errorx.CodeErrorResponse
// @Router /rule/add [post] // @Router /rule/add [post]
func addRule(api fiber.Router) { func addRule(api fiber.Router) {
api.Post("/rule/add", func(ctx *fiber.Ctx) error { api.Post("/rule/add", func(ctx *fiber.Ctx) error {
rule := &iptables.Rule{} rule := &iptables.Rule{}
isInsert := ctx.QueryBool("isInsert", false)
_ = ctx.BodyParser(rule) _ = ctx.BodyParser(rule)
if err := errorx.ParseError(iptables.AddRule(*rule)); err != nil { if err := errorx.ParseError(iptables.AddRule(*rule, isInsert)); err != nil {
return ctx.JSON(err) return ctx.JSON(err)
} else { } else {
return ctx.JSON(response.NewResponse("")) return ctx.JSON(response.NewResponse(""))

View File

@ -24,11 +24,16 @@ func appendArgsWithError[T string | Chain | PolicyTarget | Action](args []string
return args, nil return args, nil
} }
func AddRule(rule Rule) error { func AddRule(rule Rule, isInsert bool) error {
var err error var err error
args := make([]string, 0) args := make([]string, 0)
if args, err = appendArgsWithError(args, "-A", rule.Chain, errorx.NewDefaultError("规则链 Chain 不能为空")); err != nil { actionArg := "-A"
if isInsert {
actionArg = "-I"
}
if args, err = appendArgsWithError(args, actionArg, rule.Chain, errorx.NewDefaultError("规则链 Chain 不能为空")); err != nil {
return err return err
} }