diff --git a/web/api/v1/api.go b/web/api/v1/api.go index 9a13e09d98..e700f71205 100644 --- a/web/api/v1/api.go +++ b/web/api/v1/api.go @@ -1309,7 +1309,7 @@ func (api *API) rules(r *http.Request) apiFuncResult { fSet := queryFormToSet(r.Form["file[]"]) ruleGroups := api.rulesRetriever(r.Context()).RuleGroups() - res := &RuleDiscovery{RuleGroups: make([]*RuleGroup, len(ruleGroups))} + res := &RuleDiscovery{RuleGroups: make([]*RuleGroup, 0, len(ruleGroups))} typ := strings.ToLower(r.URL.Query().Get("type")) if typ != "" && typ != "alert" && typ != "record" { @@ -1319,7 +1319,8 @@ func (api *API) rules(r *http.Request) apiFuncResult { returnAlerts := typ == "" || typ == "alert" returnRecording := typ == "" || typ == "record" - for i, grp := range ruleGroups { + rgs := make([]*RuleGroup, 0, len(ruleGroups)) + for _, grp := range ruleGroups { if len(rgSet) > 0 { if _, ok := rgSet[grp.Name()]; !ok { continue @@ -1400,9 +1401,10 @@ func (api *API) rules(r *http.Request) apiFuncResult { // If the rule group response has no rules, skip it - this means we filtered all the rules of this group. if len(apiRuleGroup.Rules) > 0 { - res.RuleGroups[i] = apiRuleGroup + rgs = append(rgs, apiRuleGroup) } } + res.RuleGroups = rgs return apiFuncResult{res, nil, nil, nil} } diff --git a/web/api/v1/api_test.go b/web/api/v1/api_test.go index c3e1bf59d7..53ea21182d 100644 --- a/web/api/v1/api_test.go +++ b/web/api/v1/api_test.go @@ -2003,7 +2003,7 @@ func testEndpoints(t *testing.T, api *API, tr *testTargetRetriever, es storage.E { endpoint: api.rules, query: url.Values{"rule_group[]": []string{"respond-with-nothing"}}, - response: &RuleDiscovery{RuleGroups: []*RuleGroup{nil}}, + response: &RuleDiscovery{RuleGroups: []*RuleGroup{}}, }, { endpoint: api.rules,