Skip to content

Commit

Permalink
Merge pull request #92 from dajudge/insert-unique
Browse files Browse the repository at this point in the history
Introduce `InsertUnique()`
  • Loading branch information
squeed authored Aug 31, 2022
2 parents ff76ef3 + d79ecfa commit db049a5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
14 changes: 14 additions & 0 deletions iptables/iptables.go
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,20 @@ func (ipt *IPTables) Insert(table, chain string, pos int, rulespec ...string) er
return ipt.run(cmd...)
}

// InsertUnique acts like Insert except that it won't insert a duplicate (no matter the position in the chain)
func (ipt *IPTables) InsertUnique(table, chain string, pos int, rulespec ...string) error {
exists, err := ipt.Exists(table, chain, rulespec...)
if err != nil {
return err
}

if !exists {
return ipt.Insert(table, chain, pos, rulespec...)
}

return nil
}

// Append appends rulespec to specified table/chain
func (ipt *IPTables) Append(table, chain string, rulespec ...string) error {
cmd := append([]string{"-t", table, "-A", chain}, rulespec...)
Expand Down
5 changes: 5 additions & 0 deletions iptables/iptables_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -293,6 +293,11 @@ func runRulesTests(t *testing.T, ipt *IPTables) {
t.Fatalf("Insert failed: %v", err)
}

err = ipt.InsertUnique("filter", chain, 2, "-s", subnet2, "-d", address2, "-j", "ACCEPT")
if err != nil {
t.Fatalf("Insert failed: %v", err)
}

err = ipt.Insert("filter", chain, 1, "-s", subnet1, "-d", address2, "-j", "ACCEPT")
if err != nil {
t.Fatalf("Insert failed: %v", err)
Expand Down

0 comments on commit db049a5

Please sign in to comment.