optimize filterByStateAndGroup to handle array "group" values

This commit is contained in:
dickens7
2024-04-25 23:55:22 +08:00
parent 1e2af18dd0
commit 8be9037ad9
2 changed files with 19 additions and 3 deletions

View File

@@ -235,8 +235,18 @@ func filterByStateAndGroup(group string, servers map[string]string) {
if state := values.Get("state"); state == "inactive" {
delete(servers, k)
}
if group != "" && group != values.Get("group") {
delete(servers, k)
groups := values["group"] // Directly access the map to get all values associated with "group" as a slice
if group != "" {
found := false
for _, g := range groups {
if group == g {
found = true
break // A matching group is found, stop the search
}
}
if !found {
delete(servers, k) // If no matching group is found, delete the corresponding server from the map
}
}
}
}

View File

@@ -93,7 +93,7 @@ func TestXClient_IT(t *testing.T) {
}
func TestXClient_filterByStateAndGroup(t *testing.T) {
servers := map[string]string{"a": "", "b": "state=inactive&ops=10", "c": "ops=20", "d": "group=test&ops=20"}
servers := map[string]string{"a": "", "b": "state=inactive&ops=10", "c": "ops=20", "d": "group=test1&group=test&ops=20"}
filterByStateAndGroup("test", servers)
if _, ok := servers["b"]; ok {
t.Error("has not remove inactive node")
@@ -107,6 +107,12 @@ func TestXClient_filterByStateAndGroup(t *testing.T) {
if _, ok := servers["d"]; !ok {
t.Error("node must be removed")
}
filterByStateAndGroup("test1", servers)
if _, ok := servers["d"]; !ok {
t.Error("node must be removed")
}
}
func TestUncoverError(t *testing.T) {