diff --git a/internal/gatewayapi/backend.go b/internal/gatewayapi/backend.go index d1772428a0..c3c1c82204 100644 --- a/internal/gatewayapi/backend.go +++ b/internal/gatewayapi/backend.go @@ -20,7 +20,7 @@ import ( ) func (t *Translator) ProcessBackends(backends []*egv1a1.Backend, backendTLSPolicies []*gwapiv1a3.BackendTLSPolicy) []*egv1a1.Backend { - var res []*egv1a1.Backend + res := make([]*egv1a1.Backend, 0, len(backends)) for _, backend := range backends { // Ensure Backends are enabled if !t.BackendEnabled { diff --git a/internal/gatewayapi/backendtlspolicy.go b/internal/gatewayapi/backendtlspolicy.go index 2d37278e3e..45fc188394 100644 --- a/internal/gatewayapi/backendtlspolicy.go +++ b/internal/gatewayapi/backendtlspolicy.go @@ -257,7 +257,7 @@ func getBackendTLSPolicy( func getBackendTLSBundle(backendTLSPolicy *gwapiv1a3.BackendTLSPolicy, resources *resource.Resources) (*ir.TLSUpstreamConfig, error) { // Translate SubjectAltNames from gwapiv1a3 to ir - var subjectAltNames []ir.SubjectAltName + subjectAltNames := make([]ir.SubjectAltName, 0, len(backendTLSPolicy.Spec.Validation.SubjectAltNames)) for _, san := range backendTLSPolicy.Spec.Validation.SubjectAltNames { var subjectAltName ir.SubjectAltName switch san.Type { diff --git a/internal/gatewayapi/envoyextensionpolicy.go b/internal/gatewayapi/envoyextensionpolicy.go index 607e09b972..33a995c951 100644 --- a/internal/gatewayapi/envoyextensionpolicy.go +++ b/internal/gatewayapi/envoyextensionpolicy.go @@ -609,12 +609,12 @@ func (t *Translator) translateEnvoyExtensionPolicyForGateway( } func (t *Translator) buildLuas(policy *egv1a1.EnvoyExtensionPolicy, resources *resource.Resources, envoyProxy *egv1a1.EnvoyProxy) ([]ir.Lua, error) { - var luaIRList []ir.Lua - if policy == nil { return nil, nil } + luaIRList := make([]ir.Lua, 0, len(policy.Spec.Lua)) + for idx, ep := range policy.Spec.Lua { name := irConfigNameForLua(policy, idx) luaIR, err := t.buildLua(name, policy, ep, resources, envoyProxy) @@ -678,15 +678,16 @@ func getLuaBodyFromLocalObjectReference(valueRef *gwapiv1.LocalObjectReference, func (t *Translator) buildExtProcs(policy *egv1a1.EnvoyExtensionPolicy, resources *resource.Resources, envoyProxy *egv1a1.EnvoyProxy) ([]ir.ExtProc, error, bool) { var ( - extProcIRList []ir.ExtProc - failOpen bool - errs error + failOpen bool + errs error ) if policy == nil { return nil, nil, failOpen } + extProcIRList := make([]ir.ExtProc, 0, len(policy.Spec.ExtProc)) + hasFailClose := false for idx, ep := range policy.Spec.ExtProc { name := irConfigNameForExtProc(policy, idx) @@ -822,15 +823,16 @@ func (t *Translator) buildWasms( resources *resource.Resources, ) ([]ir.Wasm, error, bool) { var ( - wasmIRList []ir.Wasm - failOpen bool - errs error + failOpen bool + errs error ) if len(policy.Spec.Wasm) == 0 { - return wasmIRList, nil, failOpen + return nil, nil, failOpen } + wasmIRList := make([]ir.Wasm, 0, len(policy.Spec.Wasm)) + if t.WasmCache == nil { return nil, fmt.Errorf("wasm cache is not initialized"), failOpen } diff --git a/internal/gatewayapi/ext_service.go b/internal/gatewayapi/ext_service.go index 7e56c2f452..82e6f7369c 100644 --- a/internal/gatewayapi/ext_service.go +++ b/internal/gatewayapi/ext_service.go @@ -34,7 +34,6 @@ func (t *Translator) translateExtServiceBackendRefs( ) (*ir.RouteDestination, error) { var ( rs *ir.RouteDestination - ds []*ir.DestinationSetting err error ) @@ -42,6 +41,8 @@ func (t *Translator) translateExtServiceBackendRefs( return nil, errors.New("no backendRefs found for external service") } + ds := make([]*ir.DestinationSetting, 0, len(backendRefs)) + pnn := utils.NamespacedName(policy) destName := irIndexedExtServiceDestinationName(pnn, policy.GetObjectKind().GroupVersionKind().Kind, configType, index) for i, backendRef := range backendRefs { diff --git a/internal/gatewayapi/filters.go b/internal/gatewayapi/filters.go index 946225048c..722cb8b557 100644 --- a/internal/gatewayapi/filters.go +++ b/internal/gatewayapi/filters.go @@ -1033,17 +1033,17 @@ func (t *Translator) processCORSFilter( } } - var allowMethods []string + allowMethods := make([]string, 0, len(corsFilter.AllowMethods)) for _, method := range corsFilter.AllowMethods { allowMethods = append(allowMethods, string(method)) } - var allowHeaders []string + allowHeaders := make([]string, 0, len(corsFilter.AllowHeaders)) for _, header := range corsFilter.AllowHeaders { allowHeaders = append(allowHeaders, string(header)) } - var exposeHeaders []string + exposeHeaders := make([]string, 0, len(corsFilter.ExposeHeaders)) for _, header := range corsFilter.ExposeHeaders { exposeHeaders = append(exposeHeaders, string(header)) } diff --git a/internal/gatewayapi/helpers.go b/internal/gatewayapi/helpers.go index 3ff008eced..aa0eeaa875 100644 --- a/internal/gatewayapi/helpers.go +++ b/internal/gatewayapi/helpers.go @@ -460,7 +460,7 @@ func IsMergeGatewaysEnabled(resources *resource.Resources) bool { } func protocolSliceToStringSlice(protocols []gwapiv1.ProtocolType) []string { - var protocolStrings []string + protocolStrings := make([]string, 0, len(protocols)) for _, protocol := range protocols { protocolStrings = append(protocolStrings, string(protocol)) } diff --git a/internal/gatewayapi/route.go b/internal/gatewayapi/route.go index ff837a3e5d..3ef0456d0f 100644 --- a/internal/gatewayapi/route.go +++ b/internal/gatewayapi/route.go @@ -52,7 +52,7 @@ type RoutesTranslator interface { } func (t *Translator) ProcessHTTPRoutes(httpRoutes []*gwapiv1.HTTPRoute, gateways []*GatewayContext, resources *resource.Resources, xdsIR resource.XdsIRMap) []*HTTPRouteContext { - var relevantHTTPRoutes []*HTTPRouteContext + relevantHTTPRoutes := make([]*HTTPRouteContext, 0, len(httpRoutes)) // HTTPRoutes are already sorted by the provider layer @@ -79,7 +79,7 @@ func (t *Translator) ProcessHTTPRoutes(httpRoutes []*gwapiv1.HTTPRoute, gateways } func (t *Translator) ProcessGRPCRoutes(grpcRoutes []*gwapiv1.GRPCRoute, gateways []*GatewayContext, resources *resource.Resources, xdsIR resource.XdsIRMap) []*GRPCRouteContext { - var relevantGRPCRoutes []*GRPCRouteContext + relevantGRPCRoutes := make([]*GRPCRouteContext, 0, len(grpcRoutes)) // GRPCRoutes are already sorted by the provider layer @@ -387,7 +387,11 @@ func (t *Translator) processHTTPRouteRule( rule *gwapiv1.HTTPRouteRule, routeRuleMetadata *ir.ResourceMetadata, ) ([]*ir.HTTPRoute, status.Error) { - var ruleRoutes []*ir.HTTPRoute + capacity := len(rule.Matches) + if capacity == 0 { + capacity = 1 + } + ruleRoutes := make([]*ir.HTTPRoute, 0, capacity) // If no matches are specified, the implementation MUST match every HTTP request. if len(rule.Matches) == 0 { @@ -642,7 +646,8 @@ func (t *Translator) processGRPCRouteRules(grpcRoute *GRPCRouteContext, parentRe pattern := getStatPattern(grpcRoute, parentRef, t.GatewayControllerName) // compute matches, filters, backends - for ruleIdx, rule := range grpcRoute.Spec.Rules { + for ruleIdx := range grpcRoute.Spec.Rules { + rule := &grpcRoute.Spec.Rules[ruleIdx] httpFiltersContext, err := t.ProcessGRPCFilters(parentRef, grpcRoute, rule.Filters, resources) if err != nil { errs.Add(status.NewRouteStatusError( @@ -654,7 +659,7 @@ func (t *Translator) processGRPCRouteRules(grpcRoute *GRPCRouteContext, parentRe // A rule is matched if any one of its matches // is satisfied (i.e. a logical "OR"), so generate // a unique Xds IR HTTPRoute per match. - ruleRoutes, err := t.processGRPCRouteRule(grpcRoute, ruleIdx, httpFiltersContext, &rule) + ruleRoutes, err := t.processGRPCRouteRule(grpcRoute, ruleIdx, httpFiltersContext, rule) if err != nil { errs.Add(status.NewRouteStatusError( fmt.Errorf("failed to process route rule %d: %w", ruleIdx, err), @@ -740,7 +745,11 @@ func (t *Translator) processGRPCRouteRules(grpcRoute *GRPCRouteContext, parentRe } func (t *Translator) processGRPCRouteRule(grpcRoute *GRPCRouteContext, ruleIdx int, httpFiltersContext *HTTPFiltersContext, rule *gwapiv1.GRPCRouteRule) ([]*ir.HTTPRoute, status.Error) { - var ruleRoutes []*ir.HTTPRoute + capacity := len(rule.Matches) + if capacity == 0 { + capacity = 1 + } + ruleRoutes := make([]*ir.HTTPRoute, 0, capacity) // If no matches are specified, the implementation MUST match every gRPC request. if len(rule.Matches) == 0 { @@ -924,7 +933,7 @@ func filterEGPrefix(in map[string]string) map[string]string { } func (t *Translator) ProcessTLSRoutes(tlsRoutes []*gwapiv1a2.TLSRoute, gateways []*GatewayContext, resources *resource.Resources, xdsIR resource.XdsIRMap) []*TLSRouteContext { - var relevantTLSRoutes []*TLSRouteContext + relevantTLSRoutes := make([]*TLSRouteContext, 0, len(tlsRoutes)) // TLSRoutes are already sorted by the provider layer for _, tls := range tlsRoutes { @@ -1069,7 +1078,7 @@ func (t *Translator) processTLSRouteParentRefs(tlsRoute *TLSRouteContext, resour func (t *Translator) ProcessUDPRoutes(udpRoutes []*gwapiv1a2.UDPRoute, gateways []*GatewayContext, resources *resource.Resources, xdsIR resource.XdsIRMap, ) []*UDPRouteContext { - var relevantUDPRoutes []*UDPRouteContext + relevantUDPRoutes := make([]*UDPRouteContext, 0, len(udpRoutes)) // UDPRoutes are already sorted by the provider layer for _, u := range udpRoutes { @@ -1219,7 +1228,7 @@ func (t *Translator) processUDPRouteParentRefs(udpRoute *UDPRouteContext, resour func (t *Translator) ProcessTCPRoutes(tcpRoutes []*gwapiv1a2.TCPRoute, gateways []*GatewayContext, resources *resource.Resources, xdsIR resource.XdsIRMap, ) []*TCPRouteContext { - var relevantTCPRoutes []*TCPRouteContext + relevantTCPRoutes := make([]*TCPRouteContext, 0, len(tcpRoutes)) // TCPRoutes are already sorted by the provider layer for _, tcp := range tcpRoutes { @@ -1978,10 +1987,7 @@ func (t *Translator) processBackendDestinationSetting( protocol ir.AppProtocol, resources *resource.Resources, ) *ir.DestinationSetting { - var ( - dstEndpoints []*ir.DestinationEndpoint - dstAddrType *ir.DestinationAddressType - ) + var dstAddrType *ir.DestinationAddressType addrTypeMap := make(map[ir.DestinationAddressType]int) backend := resources.GetBackend(backendNamespace, string(backendRef.Name)) @@ -1998,6 +2004,8 @@ func (t *Translator) processBackendDestinationSetting( return ds } + dstEndpoints := make([]*ir.DestinationEndpoint, 0, len(backend.Spec.Endpoints)) + for _, bep := range backend.Spec.Endpoints { var irde *ir.DestinationEndpoint switch { diff --git a/internal/gatewayapi/securitypolicy.go b/internal/gatewayapi/securitypolicy.go index b2930b2701..621c79e337 100644 --- a/internal/gatewayapi/securitypolicy.go +++ b/internal/gatewayapi/securitypolicy.go @@ -883,7 +883,7 @@ func (t *Translator) buildJWT( return nil, err } - var providers []ir.JWTProvider + providers := make([]ir.JWTProvider, 0, len(policy.Spec.JWT.Providers)) for i, p := range policy.Spec.JWT.Providers { provider := ir.JWTProvider{ Name: p.Name, diff --git a/internal/gatewayapi/status/gatewayclass.go b/internal/gatewayapi/status/gatewayclass.go index c09031d211..703c42a120 100644 --- a/internal/gatewayapi/status/gatewayclass.go +++ b/internal/gatewayapi/status/gatewayclass.go @@ -83,7 +83,7 @@ func getSupportedFeatures(gatewaySuite *suite.ConformanceOptions, skippedTests [ }) } - var featureList []gwapiv1.SupportedFeature + featureList := make([]gwapiv1.SupportedFeature, 0, len(ret)) for feature := range ret { featureList = append(featureList, feature) } diff --git a/internal/gatewayapi/tls.go b/internal/gatewayapi/tls.go index 9d7d864fce..20ea5c0cdc 100644 --- a/internal/gatewayapi/tls.go +++ b/internal/gatewayapi/tls.go @@ -18,8 +18,8 @@ import ( // is not malformed and can be properly parsed func validateTLSSecretsData(secrets []*corev1.Secret) ([]*x509.Certificate, error) { var publicKeyAlgorithm string - var certs []*x509.Certificate var parseErr error + certs := make([]*x509.Certificate, 0, len(secrets)) pkaSecretSet := make(map[string]string) for _, secret := range secrets { diff --git a/internal/provider/file/resources.go b/internal/provider/file/resources.go index 576d9665af..8f95243054 100644 --- a/internal/provider/file/resources.go +++ b/internal/provider/file/resources.go @@ -16,7 +16,7 @@ import ( // loadFromFilesAndDirs loads resources from specific files and directories. func loadFromFilesAndDirs(files, dirs []string) ([]*resource.Resources, error) { - var rs []*resource.Resources + rs := make([]*resource.Resources, 0, len(files)+len(dirs)) for _, file := range files { r, err := loadFromFile(file) @@ -61,7 +61,7 @@ func loadFromDir(path string) ([]*resource.Resources, error) { return nil, err } - var rs []*resource.Resources + rs := make([]*resource.Resources, 0, len(entries)) for _, entry := range entries { // Ignoring subdirectories and all hidden files and directories. if entry.IsDir() || strings.HasPrefix(entry.Name(), ".") { diff --git a/internal/provider/kubernetes/controller.go b/internal/provider/kubernetes/controller.go index 8d767f23cd..526e933587 100644 --- a/internal/provider/kubernetes/controller.go +++ b/internal/provider/kubernetes/controller.go @@ -958,7 +958,7 @@ func (r *gatewayAPIReconciler) processSecurityPolicyObjectRefs( } func getBackendRefs(backendCluster egv1a1.BackendCluster) []gwapiv1.BackendObjectReference { - var backendRefs []gwapiv1.BackendObjectReference + backendRefs := make([]gwapiv1.BackendObjectReference, 0, 1+len(backendCluster.BackendRefs)) if backendCluster.BackendRef != nil { backendRefs = append(backendRefs, *backendCluster.BackendRef) } diff --git a/internal/provider/kubernetes/indexers.go b/internal/provider/kubernetes/indexers.go index 2b9b5efdb3..03d4b13f96 100644 --- a/internal/provider/kubernetes/indexers.go +++ b/internal/provider/kubernetes/indexers.go @@ -70,7 +70,7 @@ func addReferenceGrantIndexers(ctx context.Context, mgr manager.Manager) error { func getReferenceGrantIndexerFunc(rawObj client.Object) []string { refGrant := rawObj.(*gwapiv1b1.ReferenceGrant) - var referredServices []string + referredServices := make([]string, 0, len(refGrant.Spec.To)) for _, target := range refGrant.Spec.To { referredServices = append(referredServices, string(target.Kind)) } @@ -587,8 +587,8 @@ func secretSecurityPolicyIndexFunc(rawObj client.Object) []string { securityPolicy := rawObj.(*egv1a1.SecurityPolicy) var ( - secretReferences []gwapiv1.SecretObjectReference - values []string + secretReferences = make([]gwapiv1.SecretObjectReference, 0, 4) // OIDC (2) + APIKeyAuth + BasicAuth + values = make([]string, 0, 4) ) if securityPolicy.Spec.OIDC != nil { @@ -619,8 +619,8 @@ func backendSecurityPolicyIndexFunc(rawObj client.Object) []string { securityPolicy := rawObj.(*egv1a1.SecurityPolicy) var ( - backendRefs []gwapiv1.BackendObjectReference - values []string + backendRefs = make([]gwapiv1.BackendObjectReference, 0, 2) // HTTP + GRPC + values = make([]string, 0, 2) ) if securityPolicy.Spec.ExtAuth != nil { diff --git a/internal/provider/kubernetes/routes.go b/internal/provider/kubernetes/routes.go index 42b83deed0..37dd5b4604 100644 --- a/internal/provider/kubernetes/routes.go +++ b/internal/provider/kubernetes/routes.go @@ -306,7 +306,7 @@ func (r *gatewayAPIReconciler) processHTTPRouteFilter( resourceMap *resourceMappings, resourceTree *resource.Resources, ) error { - var extGKs []schema.GroupKind + extGKs := make([]schema.GroupKind, 0, len(r.extGVKs)) for _, gvk := range r.extGVKs { extGKs = append(extGKs, gvk.GroupKind()) } diff --git a/internal/provider/kubernetes/secrets.go b/internal/provider/kubernetes/secrets.go index e8c0f43118..402147db95 100644 --- a/internal/provider/kubernetes/secrets.go +++ b/internal/provider/kubernetes/secrets.go @@ -91,8 +91,8 @@ func CertsToSecret(namespace string, certs *crypto.Certificates) []corev1.Secret // them if they do. func CreateOrUpdateSecrets(ctx context.Context, client client.Client, secrets []corev1.Secret, update bool) ([]corev1.Secret, error) { var ( - tidySecrets []corev1.Secret - existingSecrets []string + tidySecrets = make([]corev1.Secret, 0, len(secrets)) + existingSecrets = make([]string, 0, len(secrets)) ) for i := range secrets { diff --git a/internal/utils/jsonpatch/jsonpathtopointer.go b/internal/utils/jsonpatch/jsonpathtopointer.go index 3898fb0790..b1c325249f 100644 --- a/internal/utils/jsonpatch/jsonpathtopointer.go +++ b/internal/utils/jsonpatch/jsonpathtopointer.go @@ -15,7 +15,7 @@ import ( ) func ConvertPathToPointers(jsonDoc []byte, jsonPath, path string) ([]string, error) { - var jsonPointers []string + jsonPointers := make([]string, 0, 4) // reasonable default for most json path queries jObj, err := oj.Parse(jsonDoc) if err != nil { diff --git a/internal/utils/slice/slice.go b/internal/utils/slice/slice.go index cc75f9f0e5..68e077d218 100644 --- a/internal/utils/slice/slice.go +++ b/internal/utils/slice/slice.go @@ -18,12 +18,18 @@ func ContainsString(slice []string, s string) bool { // RemoveString returns a newly created []string that contains all items from slice that // are not equal to s. func RemoveString(slice []string, s string) []string { - var newSlice []string + if slice == nil { + return nil + } + newSlice := make([]string, 0, len(slice)) for _, item := range slice { if item == s { continue } newSlice = append(newSlice, item) } + if len(newSlice) == 0 { + return nil + } return newSlice } diff --git a/internal/xds/cache/snapshotcache.go b/internal/xds/cache/snapshotcache.go index 61b923f22c..aa892d79c1 100644 --- a/internal/xds/cache/snapshotcache.go +++ b/internal/xds/cache/snapshotcache.go @@ -407,7 +407,7 @@ func (s *snapshotCache) GetIrKeys() []string { s.mu.Lock() defer s.mu.Unlock() - var irKeys []string + irKeys := make([]string, 0, len(s.lastSnapshot)) for key := range s.lastSnapshot { irKeys = append(irKeys, key) } diff --git a/internal/xds/translator/accesslog.go b/internal/xds/translator/accesslog.go index e51853f275..5cd7ef6116 100644 --- a/internal/xds/translator/accesslog.go +++ b/internal/xds/translator/accesslog.go @@ -373,7 +373,11 @@ func celAccessLogFilter(expr string) (*accesslog.AccessLogFilter, error) { func buildAccessLogFilter(exprs []string, withNoRouteMatchFilter bool) (*accesslog.AccessLogFilter, error) { // add filter for access logs - var filters []*accesslog.AccessLogFilter + capacity := len(exprs) + if withNoRouteMatchFilter { + capacity++ + } + filters := make([]*accesslog.AccessLogFilter, 0, capacity) for _, expr := range exprs { fl, err := celAccessLogFilter(expr) if err != nil { diff --git a/internal/xds/translator/authorization.go b/internal/xds/translator/authorization.go index 7a94453fb3..e2e53f5ea4 100644 --- a/internal/xds/translator/authorization.go +++ b/internal/xds/translator/authorization.go @@ -153,9 +153,9 @@ func buildRBACPerRoute(authorization *ir.Authorization) (*rbacv3.RBACPerRoute, e rbac *rbacv3.RBACPerRoute allowAction *anypb.Any denyAction *anypb.Any - matcherList []*matcherv3.Matcher_MatcherList_FieldMatcher err error ) + matcherList := make([]*matcherv3.Matcher_MatcherList_FieldMatcher, 0, len(authorization.Rules)) allow := &rbacconfigv3.Action{ Name: "ALLOW", @@ -625,7 +625,7 @@ func buildHeaderPredicate(name string, values []string, ignoreCase bool) ([]*mat return nil, err } - var predicates []*matcherv3.Matcher_MatcherList_Predicate + predicates := make([]*matcherv3.Matcher_MatcherList_Predicate, 0, len(values)) for _, value := range values { predicates = append(predicates, &matcherv3.Matcher_MatcherList_Predicate{ MatchType: &matcherv3.Matcher_MatcherList_Predicate_SinglePredicate_{ diff --git a/internal/xds/translator/cluster.go b/internal/xds/translator/cluster.go index 0d3e387c17..48d4c4d86c 100644 --- a/internal/xds/translator/cluster.go +++ b/internal/xds/translator/cluster.go @@ -725,7 +725,6 @@ func buildXdsClusterLoadAssignment(clusterName string, destSettings []*ir.Destin } func buildZonalLocalities(metadata *corev3.Metadata, ds *ir.DestinationSetting) []*endpointv3.LocalityLbEndpoints { - var localities []*endpointv3.LocalityLbEndpoints zonalEndpoints := make(map[string][]*endpointv3.LbEndpoint) for _, irEp := range ds.Endpoints { healthStatus := corev3.HealthStatus_UNKNOWN @@ -748,6 +747,7 @@ func buildZonalLocalities(metadata *corev3.Metadata, ds *ir.DestinationSetting) zonalEndpoints[zone] = append(zonalEndpoints[zone], lbEndpoint) } + localities := make([]*endpointv3.LocalityLbEndpoints, 0, len(zonalEndpoints)) for zone, endPts := range zonalEndpoints { locality := &endpointv3.LocalityLbEndpoints{ Locality: &corev3.Locality{ @@ -1249,7 +1249,7 @@ func buildHTTP2Settings(opts *ir.HTTP2Settings) *corev3.Http2ProtocolOptions { // buildEndpointOverrideLoadBalancingPolicy builds the Envoy LoadBalancingPolicy for EndpointOverride func buildEndpointOverrideLoadBalancingPolicy(loadBalancer *ir.LoadBalancer) (*clusterv3.LoadBalancingPolicy, error) { // Build override host sources from EndpointOverride - var overrideHostSources []*override_hostv3.OverrideHost_OverrideHostSource + overrideHostSources := make([]*override_hostv3.OverrideHost_OverrideHostSource, 0, len(loadBalancer.EndpointOverride.ExtractFrom)) for _, source := range loadBalancer.EndpointOverride.ExtractFrom { overrideSource := &override_hostv3.OverrideHost_OverrideHostSource{} diff --git a/internal/xds/translator/cors.go b/internal/xds/translator/cors.go index b53a120027..5aff0a80e9 100644 --- a/internal/xds/translator/cors.go +++ b/internal/xds/translator/cors.go @@ -125,7 +125,6 @@ func (*cors) patchRoute(route *routev3.Route, irRoute *ir.HTTPRoute, _ *ir.HTTPL } var ( - allowOrigins []*matcherv3.StringMatcher allowMethods string allowHeaders string exposeHeaders string @@ -144,6 +143,7 @@ func (*cors) patchRoute(route *routev3.Route, irRoute *ir.HTTPRoute, _ *ir.HTTPL //nolint:gocritic + allowOrigins := make([]*matcherv3.StringMatcher, 0, len(c.AllowOrigins)) for _, origin := range c.AllowOrigins { allowOrigins = append(allowOrigins, buildXdsStringMatcher(origin)) } diff --git a/internal/xds/translator/extauth.go b/internal/xds/translator/extauth.go index 194999d4ab..3fb3ce4cc0 100644 --- a/internal/xds/translator/extauth.go +++ b/internal/xds/translator/extauth.go @@ -107,7 +107,7 @@ func extAuthConfig(extAuth *ir.ExtAuth) (*extauthv3.ExtAuthz, error) { config.ClearRouteCache = *extAuth.RecomputeRoute } - var headersToExtAuth []*matcherv3.StringMatcher + headersToExtAuth := make([]*matcherv3.StringMatcher, 0, len(extAuth.HeadersToExtAuth)) for _, header := range extAuth.HeadersToExtAuth { headersToExtAuth = append(headersToExtAuth, &matcherv3.StringMatcher{ MatchPattern: &matcherv3.StringMatcher_Exact{ @@ -164,9 +164,8 @@ func extAuthConfig(extAuth *ir.ExtAuth) (*extauthv3.ExtAuthz, error) { func httpService(http *ir.HTTPExtAuthService, timeout *durationpb.Duration) *extauthv3.HttpService { var ( - uri string - headersToBackend []*matcherv3.StringMatcher - service *extauthv3.HttpService + uri string + service *extauthv3.HttpService ) service = &extauthv3.HttpService{ @@ -191,6 +190,7 @@ func httpService(http *ir.HTTPExtAuthService, timeout *durationpb.Duration) *ext Timeout: timeout, } + headersToBackend := make([]*matcherv3.StringMatcher, 0, len(http.HeadersToBackend)) for _, header := range http.HeadersToBackend { headersToBackend = append(headersToBackend, &matcherv3.StringMatcher{ MatchPattern: &matcherv3.StringMatcher_Exact{ diff --git a/internal/xds/translator/header_mutation.go b/internal/xds/translator/header_mutation.go index 2860143395..689c578243 100644 --- a/internal/xds/translator/header_mutation.go +++ b/internal/xds/translator/header_mutation.go @@ -92,7 +92,7 @@ func buildHeaderMutationFilter(headers *ir.HeaderSettings) (*hcmv3.HttpFilter, e } func buildHeaderMutationRules(addHeaders []ir.AddHeader, removeHeaders []string) []*mutation_rulesv3.HeaderMutation { - var mutationRules []*mutation_rulesv3.HeaderMutation + mutationRules := make([]*mutation_rulesv3.HeaderMutation, 0, len(addHeaders)+len(removeHeaders)) for _, header := range addHeaders { var appendAction corev3.HeaderValueOption_HeaderAppendAction diff --git a/internal/xds/translator/local_ratelimit.go b/internal/xds/translator/local_ratelimit.go index e988099284..7a7d16ab10 100644 --- a/internal/xds/translator/local_ratelimit.go +++ b/internal/xds/translator/local_ratelimit.go @@ -198,8 +198,8 @@ func (*localRateLimit) patchRoute(route *routev3.Route, irRoute *ir.HTTPRoute, h func buildRouteLocalRateLimits(local *ir.LocalRateLimit) ( []*routev3.RateLimit, []*rlv3.LocalRateLimitDescriptor, ) { - var rateLimits []*routev3.RateLimit - var descriptors []*rlv3.LocalRateLimitDescriptor + rateLimits := make([]*routev3.RateLimit, 0, len(local.Rules)) + descriptors := make([]*rlv3.LocalRateLimitDescriptor, 0, len(local.Rules)) // Rules are ORed for rIdx, rule := range local.Rules { diff --git a/internal/xds/translator/session_persistence.go b/internal/xds/translator/session_persistence.go index f68a18a80d..8f958d30db 100644 --- a/internal/xds/translator/session_persistence.go +++ b/internal/xds/translator/session_persistence.go @@ -178,7 +178,7 @@ func routePathToCookiePath(path *ir.StringMatch) string { // https://gateway-api.sigs.k8s.io/geps/gep-1619/#path func getLongestNonRegexPrefix(path string) string { parts := strings.Split(path, "/") - var longestNonRegexPrefix []string + longestNonRegexPrefix := make([]string, 0, len(parts)) for _, part := range parts { if part == "*" || strings.Contains(part, "*") { break diff --git a/test/e2e/tests/udproute.go b/test/e2e/tests/udproute.go index a63936256c..6174917d5a 100644 --- a/test/e2e/tests/udproute.go +++ b/test/e2e/tests/udproute.go @@ -75,12 +75,12 @@ type GatewayRef struct { // NewGatewayRef creates a GatewayRef resource. ListenerNames are optional. func NewGatewayRef(nn types.NamespacedName, listenerNames ...string) GatewayRef { - var listeners []*gwapiv1.SectionName - if len(listenerNames) == 0 { listenerNames = append(listenerNames, "") } + listeners := make([]*gwapiv1.SectionName, 0, len(listenerNames)) + for _, listener := range listenerNames { sectionName := gwapiv1.SectionName(listener) listeners = append(listeners, §ionName) diff --git a/tools/linter/golangci-lint/.golangci.yml b/tools/linter/golangci-lint/.golangci.yml index c8c6b82189..416543bd01 100644 --- a/tools/linter/golangci-lint/.golangci.yml +++ b/tools/linter/golangci-lint/.golangci.yml @@ -42,6 +42,7 @@ linters: - gosec - importas - misspell + - prealloc - revive - staticcheck - testifylint