Explorar o código

Implement DeleteIfExists

Add a conventient wrapper around Exists() and Delete().
Phil Sutter %!s(int64=4) %!d(string=hai) anos
pai
achega
406f90a0f5
Modificáronse 2 ficheiros con 17 adicións e 0 borrados
  1. 8 0
      iptables/iptables.go
  2. 9 0
      iptables/iptables_test.go

+ 8 - 0
iptables/iptables.go

@@ -183,6 +183,14 @@ func (ipt *IPTables) Delete(table, chain string, rulespec ...string) error {
 	return ipt.run(cmd...)
 }
 
+func (ipt *IPTables) DeleteIfExists(table, chain string, rulespec ...string) error {
+	exists, err := ipt.Exists(table, chain, rulespec...)
+	if err == nil && exists {
+		err = ipt.Delete(table, chain, rulespec...)
+	}
+	return err
+}
+
 // List rules in specified table/chain
 func (ipt *IPTables) List(table, chain string) ([]string, error) {
 	args := []string{"-t", table, "-S", chain}

+ 9 - 0
iptables/iptables_test.go

@@ -343,6 +343,15 @@ func runRulesTests(t *testing.T, ipt *IPTables) {
 		}
 	}
 
+	err = ipt.DeleteIfExists("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT")
+	if err != nil {
+		t.Fatalf("DeleteIfExists failed for existing rule: %v", err)
+	}
+	err = ipt.DeleteIfExists("filter", chain, "-s", address1, "-d", subnet2, "-j", "ACCEPT")
+	if err != nil {
+		t.Fatalf("DeleteIfExists failed for non-existing rule: %v", err)
+	}
+
 	// Clear the chain that was created.
 	err = ipt.ClearChain("filter", chain)
 	if err != nil {