From 88a2020817e97de53b324198346e4e02773c9444 Mon Sep 17 00:00:00 2001 From: Ludovic Fernandez Date: Mon, 19 Feb 2024 15:44:03 +0100 Subject: [PATCH] chore: update linter --- .github/workflows/validate.yaml | 2 +- .golangci.yml | 2 +- .semaphore/semaphore.yml | 2 +- cmd/internal/gen/centrifuge.go | 2 +- integration/conf_throttling_test.go | 2 +- integration/healthcheck_test.go | 14 ++++++------ integration/integration_test.go | 2 +- integration/simple_test.go | 16 +++++++------- integration/tcp_test.go | 2 +- integration/udp_test.go | 2 +- internal/gendoc.go | 2 +- pkg/api/criterion.go | 11 ++++------ pkg/api/handler.go | 2 +- pkg/api/handler_entrypoint_test.go | 2 +- pkg/api/handler_http_test.go | 2 +- pkg/api/handler_overview.go | 6 ++--- pkg/collector/hydratation/hydration.go | 6 ++--- pkg/config/kv/kv.go | 2 +- pkg/middlewares/accesslog/logger_test.go | 2 +- pkg/middlewares/capture/capture_test.go | 4 ++-- pkg/middlewares/compress/compress_test.go | 4 ++-- .../empty_backend_handler_test.go | 2 +- pkg/middlewares/metrics/metrics.go | 11 +++++----- .../requestdecorator/hostresolver.go | 2 +- pkg/middlewares/retry/retry_test.go | 2 +- pkg/muxer/http/mux.go | 10 +++------ pkg/muxer/tcp/mux.go | 15 +++++-------- pkg/provider/acme/challenge_tls.go | 13 ++--------- pkg/provider/acme/provider.go | 4 ++-- pkg/provider/constraints/constraints_tags.go | 18 +++++---------- pkg/provider/consulcatalog/config_test.go | 4 ++-- pkg/provider/docker/config_test.go | 4 ++-- pkg/provider/ecs/config_test.go | 4 ++-- pkg/provider/ecs/ecs.go | 12 +++++----- pkg/provider/ecs/ecs_test.go | 2 +- pkg/provider/kubernetes/crd/client.go | 9 +++----- pkg/provider/kubernetes/gateway/client.go | 9 +++----- pkg/provider/kubernetes/ingress/client.go | 9 +++----- pkg/provider/kubernetes/ingress/kubernetes.go | 11 ++++------ pkg/provider/rancher/config_test.go | 2 +- pkg/redactor/redactor.go | 6 ++--- pkg/server/aggregator.go | 14 +++--------- pkg/server/configurationwatcher_test.go | 2 +- pkg/server/middleware/middlewares.go | 12 ++-------- pkg/server/middleware/tcp/middlewares.go | 12 ++-------- pkg/server/router/router_test.go | 4 ++-- pkg/server/server_entrypoint_tcp_test.go | 4 ++-- .../loadbalancer/mirror/mirror_test.go | 6 ++--- .../service/loadbalancer/wrr/wrr_test.go | 22 +++++++++---------- pkg/server/service/proxy_test.go | 2 +- pkg/server/service/roundtripper.go | 10 ++++----- pkg/server/service/roundtripper_test.go | 2 +- pkg/server/service/service.go | 2 +- pkg/tcp/wrr_load_balancer_test.go | 2 +- pkg/tls/tlsmanager.go | 13 ++--------- pkg/types/http_code_range.go | 10 ++++----- pkg/udp/conn_test.go | 2 +- 57 files changed, 139 insertions(+), 218 deletions(-) diff --git a/.github/workflows/validate.yaml b/.github/workflows/validate.yaml index 82570d790..076a36b64 100644 --- a/.github/workflows/validate.yaml +++ b/.github/workflows/validate.yaml @@ -7,7 +7,7 @@ on: env: GO_VERSION: '1.22' - GOLANGCI_LINT_VERSION: v1.56.0 + GOLANGCI_LINT_VERSION: v1.56.2 MISSSPELL_VERSION: v0.4.1 jobs: diff --git a/.golangci.yml b/.golangci.yml index b8a1ceaaa..1a7860b91 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -225,7 +225,7 @@ issues: - 'SA1019: c.Providers.ConsulCatalog.Namespace is deprecated' - 'SA1019: c.Providers.Consul.Namespace is deprecated' - 'SA1019: c.Providers.Nomad.Namespace is deprecated' - - 'fmt.Sprintf can be replaced with string addition' + - 'fmt.Sprintf can be replaced with string' exclude-rules: - path: '(.+)_test.go' linters: diff --git a/.semaphore/semaphore.yml b/.semaphore/semaphore.yml index 5bbb5bf57..e45bca92c 100644 --- a/.semaphore/semaphore.yml +++ b/.semaphore/semaphore.yml @@ -25,7 +25,7 @@ global_job_config: - export "PATH=${GOPATH}/bin:${PATH}" - mkdir -vp "${SEMAPHORE_GIT_DIR}" "${GOPATH}/bin" - export GOPROXY=https://proxy.golang.org,direct - - curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b "${GOPATH}/bin" v1.56.0 + - curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b "${GOPATH}/bin" v1.56.2 - curl -sSfL https://gist.githubusercontent.com/traefiker/6d7ac019c11d011e4f131bb2cca8900e/raw/goreleaser.sh | bash -s -- -b "${GOPATH}/bin" - checkout - cache restore traefik-$(checksum go.sum) diff --git a/cmd/internal/gen/centrifuge.go b/cmd/internal/gen/centrifuge.go index df5d46fd8..2c0f6e634 100644 --- a/cmd/internal/gen/centrifuge.go +++ b/cmd/internal/gen/centrifuge.go @@ -160,7 +160,7 @@ func (c Centrifuge) writeStruct(name string, obj *types.Struct, rootPkg string, b := strings.Builder{} b.WriteString(fmt.Sprintf("type %s struct {\n", name)) - for i := 0; i < obj.NumFields(); i++ { + for i := range obj.NumFields() { field := obj.Field(i) if !field.Exported() { diff --git a/integration/conf_throttling_test.go b/integration/conf_throttling_test.go index 7e29c039f..162aff5d9 100644 --- a/integration/conf_throttling_test.go +++ b/integration/conf_throttling_test.go @@ -67,7 +67,7 @@ func (s *ThrottlingSuite) TestThrottleConfReload() { confChanges := 10 - for i := 0; i < confChanges; i++ { + for i := range confChanges { config.HTTP.Routers[fmt.Sprintf("routerHTTP%d", i)] = router data, err := json.Marshal(config) require.NoError(s.T(), err) diff --git a/integration/healthcheck_test.go b/integration/healthcheck_test.go index 4e6279c97..6f14b048b 100644 --- a/integration/healthcheck_test.go +++ b/integration/healthcheck_test.go @@ -312,7 +312,7 @@ func (s *HealthCheckSuite) TestPropagate() { // Verify load-balancing on root still works, and that we're getting an alternation between wsp2, and wsp4. reachedServers := make(map[string]int) - for i := 0; i < 4; i++ { + for range 4 { resp, err := client.Do(rootReq) require.NoError(s.T(), err) @@ -352,7 +352,7 @@ func (s *HealthCheckSuite) TestPropagate() { // Verify load-balancing on foo still works, and that we're getting wsp2, wsp2, wsp2, wsp2, etc. want := `IP: ` + s.whoami2IP - for i := 0; i < 4; i++ { + for range 4 { resp, err := client.Do(fooReq) require.NoError(s.T(), err) @@ -368,7 +368,7 @@ func (s *HealthCheckSuite) TestPropagate() { // Verify load-balancing on bar still works, and that we're getting wsp2, wsp2, wsp2, wsp2, etc. want = `IP: ` + s.whoami2IP - for i := 0; i < 4; i++ { + for range 4 { resp, err := client.Do(barReq) require.NoError(s.T(), err) @@ -390,7 +390,7 @@ func (s *HealthCheckSuite) TestPropagate() { try.Sleep(time.Second) // Verify that everything is down, and that we get 503s everywhere. - for i := 0; i < 2; i++ { + for range 2 { resp, err := client.Do(rootReq) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusServiceUnavailable, resp.StatusCode) @@ -417,7 +417,7 @@ func (s *HealthCheckSuite) TestPropagate() { // Verify everything is up on root router. reachedServers = make(map[string]int) - for i := 0; i < 4; i++ { + for range 4 { resp, err := client.Do(rootReq) require.NoError(s.T(), err) @@ -452,7 +452,7 @@ func (s *HealthCheckSuite) TestPropagate() { // Verify everything is up on foo router. reachedServers = make(map[string]int) - for i := 0; i < 4; i++ { + for range 4 { resp, err := client.Do(fooReq) require.NoError(s.T(), err) @@ -487,7 +487,7 @@ func (s *HealthCheckSuite) TestPropagate() { // Verify everything is up on bar router. reachedServers = make(map[string]int) - for i := 0; i < 4; i++ { + for range 4 { resp, err := client.Do(barReq) require.NoError(s.T(), err) diff --git a/integration/integration_test.go b/integration/integration_test.go index 4ce934535..0626724da 100644 --- a/integration/integration_test.go +++ b/integration/integration_test.go @@ -239,7 +239,7 @@ func (s *BaseSuite) createComposeProject(name string) { } if containerConfig.Deploy.Replicas > 0 { - for i := 0; i < containerConfig.Deploy.Replicas; i++ { + for i := range containerConfig.Deploy.Replicas { id = fmt.Sprintf("%s-%d", id, i+1) con, err := s.createContainer(ctx, containerConfig, id, mounts) require.NoError(s.T(), err) diff --git a/integration/simple_test.go b/integration/simple_test.go index 76305bbbc..fc5936069 100644 --- a/integration/simple_test.go +++ b/integration/simple_test.go @@ -307,7 +307,7 @@ func (s *SimpleSuite) TestMetricsPrometheusTwoRoutersOneService() { require.NoError(s.T(), err) // adding a loop to test if metrics are not deleted - for i := 0; i < 10; i++ { + for range 10 { request, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/metrics", nil) require.NoError(s.T(), err) @@ -771,7 +771,7 @@ func (s *SimpleSuite) TestWRR() { require.NoError(s.T(), err) repartition := map[string]int{} - for i := 0; i < 4; i++ { + for range 4 { req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) require.NoError(s.T(), err) @@ -817,7 +817,7 @@ func (s *SimpleSuite) TestWRRSticky() { req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) require.NoError(s.T(), err) - for i := 0; i < 4; i++ { + for range 4 { response, err := http.DefaultClient.Do(req) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusOK, response.StatusCode) @@ -873,7 +873,7 @@ func (s *SimpleSuite) TestMirror() { req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) require.NoError(s.T(), err) - for i := 0; i < 10; i++ { + for range 10 { response, err := http.DefaultClient.Do(req) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusOK, response.StatusCode) @@ -944,7 +944,7 @@ func (s *SimpleSuite) TestMirrorWithBody() { req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", bytes.NewBuffer(body20)) require.NoError(s.T(), err) req.Header.Set("Size", "20") - for i := 0; i < 10; i++ { + for range 10 { response, err := http.DefaultClient.Do(req) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusOK, response.StatusCode) @@ -965,7 +965,7 @@ func (s *SimpleSuite) TestMirrorWithBody() { req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoamiWithMaxBody", bytes.NewBuffer(body5)) require.NoError(s.T(), err) req.Header.Set("Size", "5") - for i := 0; i < 10; i++ { + for range 10 { response, err := http.DefaultClient.Do(req) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusOK, response.StatusCode) @@ -986,7 +986,7 @@ func (s *SimpleSuite) TestMirrorWithBody() { req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoamiWithMaxBody", bytes.NewBuffer(body20)) require.NoError(s.T(), err) req.Header.Set("Size", "20") - for i := 0; i < 10; i++ { + for range 10 { response, err := http.DefaultClient.Do(req) require.NoError(s.T(), err) assert.Equal(s.T(), http.StatusOK, response.StatusCode) @@ -1032,7 +1032,7 @@ func (s *SimpleSuite) TestMirrorCanceled() { err := try.GetRequest("http://127.0.0.1:8080/api/http/services", 1000*time.Millisecond, try.BodyContains("mirror1", "mirror2", "service1")) require.NoError(s.T(), err) - for i := 0; i < 5; i++ { + for range 5 { req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil) require.NoError(s.T(), err) diff --git a/integration/tcp_test.go b/integration/tcp_test.go index b755f8b12..30a6e0bee 100644 --- a/integration/tcp_test.go +++ b/integration/tcp_test.go @@ -263,7 +263,7 @@ func (s *TCPSuite) TestWRR() { require.NoError(s.T(), err) call := map[string]int{} - for i := 0; i < 4; i++ { + for range 4 { // Traefik passes through, termination handled by whoami-b or whoami-bb out, err := guessWhoTLSPassthrough("127.0.0.1:8093", "whoami-b.test") require.NoError(s.T(), err) diff --git a/integration/udp_test.go b/integration/udp_test.go index 58951b78d..770785f99 100644 --- a/integration/udp_test.go +++ b/integration/udp_test.go @@ -82,7 +82,7 @@ func (s *UDPSuite) TestWRR() { stop := make(chan struct{}) go func() { call := map[string]int{} - for i := 0; i < 8; i++ { + for range 8 { out, err := guessWhoUDP("127.0.0.1:8093") require.NoError(s.T(), err) switch { diff --git a/internal/gendoc.go b/internal/gendoc.go index d27c0fe3d..76f650582 100644 --- a/internal/gendoc.go +++ b/internal/gendoc.go @@ -223,7 +223,7 @@ func clean(element any) { valueSvcRoot := valSvcs.MapIndex(key).Elem() var svcFieldNames []string - for i := 0; i < valueSvcRoot.NumField(); i++ { + for i := range valueSvcRoot.NumField() { svcFieldNames = append(svcFieldNames, valueSvcRoot.Type().Field(i).Name) } diff --git a/pkg/api/criterion.go b/pkg/api/criterion.go index d81a9f717..cd173f532 100644 --- a/pkg/api/criterion.go +++ b/pkg/api/criterion.go @@ -4,6 +4,7 @@ import ( "fmt" "net/http" "net/url" + "slices" "strconv" "strings" ) @@ -50,13 +51,9 @@ func (c *searchCriterion) searchIn(values ...string) bool { return true } - for _, v := range values { - if strings.Contains(strings.ToLower(v), strings.ToLower(c.Search)) { - return true - } - } - - return false + return slices.ContainsFunc(values, func(v string) bool { + return strings.Contains(strings.ToLower(v), strings.ToLower(c.Search)) + }) } func pagination(request *http.Request, max int) (pageInfo, error) { diff --git a/pkg/api/handler.go b/pkg/api/handler.go index df4db9f98..18cc7c7ba 100644 --- a/pkg/api/handler.go +++ b/pkg/api/handler.go @@ -149,7 +149,7 @@ func getProviderName(id string) string { func extractType(element interface{}) string { v := reflect.ValueOf(element).Elem() - for i := 0; i < v.NumField(); i++ { + for i := range v.NumField() { field := v.Field(i) if field.Kind() == reflect.Map && field.Type().Elem() == reflect.TypeOf(dynamic.PluginConf{}) { diff --git a/pkg/api/handler_entrypoint_test.go b/pkg/api/handler_entrypoint_test.go index 5172e4689..36010cebe 100644 --- a/pkg/api/handler_entrypoint_test.go +++ b/pkg/api/handler_entrypoint_test.go @@ -256,7 +256,7 @@ func TestHandler_EntryPoints(t *testing.T) { func generateEntryPoints(nb int) map[string]*static.EntryPoint { eps := make(map[string]*static.EntryPoint, nb) - for i := 0; i < nb; i++ { + for i := range nb { eps[fmt.Sprintf("ep%2d", i)] = &static.EntryPoint{ Address: ":" + strconv.Itoa(i), } diff --git a/pkg/api/handler_http_test.go b/pkg/api/handler_http_test.go index d7f905c5d..b814c69ab 100644 --- a/pkg/api/handler_http_test.go +++ b/pkg/api/handler_http_test.go @@ -972,7 +972,7 @@ func TestHandler_HTTP(t *testing.T) { func generateHTTPRouters(nbRouters int) map[string]*runtime.RouterInfo { routers := make(map[string]*runtime.RouterInfo, nbRouters) - for i := 0; i < nbRouters; i++ { + for i := range nbRouters { routers[fmt.Sprintf("bar%2d@myprovider", i)] = &runtime.RouterInfo{ Router: &dynamic.Router{ EntryPoints: []string{"web"}, diff --git a/pkg/api/handler_overview.go b/pkg/api/handler_overview.go index 4e6485e7d..98c350dfb 100644 --- a/pkg/api/handler_overview.go +++ b/pkg/api/handler_overview.go @@ -226,7 +226,7 @@ func getProviders(conf static.Configuration) []string { var providers []string v := reflect.ValueOf(conf.Providers).Elem() - for i := 0; i < v.NumField(); i++ { + for i := range v.NumField() { field := v.Field(i) if field.Kind() == reflect.Ptr && field.Elem().Kind() == reflect.Struct { if !field.IsNil() { @@ -256,7 +256,7 @@ func getMetrics(conf static.Configuration) string { } v := reflect.ValueOf(conf.Metrics).Elem() - for i := 0; i < v.NumField(); i++ { + for i := range v.NumField() { field := v.Field(i) if field.Kind() == reflect.Ptr && field.Elem().Kind() == reflect.Struct { if !field.IsNil() { @@ -274,7 +274,7 @@ func getTracing(conf static.Configuration) string { } v := reflect.ValueOf(conf.Tracing).Elem() - for i := 0; i < v.NumField(); i++ { + for i := range v.NumField() { field := v.Field(i) if field.Kind() == reflect.Ptr && field.Elem().Kind() == reflect.Struct { if !field.IsNil() { diff --git a/pkg/collector/hydratation/hydration.go b/pkg/collector/hydratation/hydration.go index a5ec52dee..40736f046 100644 --- a/pkg/collector/hydratation/hydration.go +++ b/pkg/collector/hydratation/hydration.go @@ -93,7 +93,7 @@ func setTyped(field reflect.Value, i interface{}) { func setMap(field reflect.Value) error { field.Set(reflect.MakeMap(field.Type())) - for i := 0; i < mapItemNumber; i++ { + for i := range mapItemNumber { baseKeyName := makeKeyName(field.Type().Elem()) key := reflect.ValueOf(fmt.Sprintf("%s%d", baseKeyName, i)) @@ -125,7 +125,7 @@ func makeKeyName(typ reflect.Type) string { } func setStruct(field reflect.Value) error { - for i := 0; i < field.NumField(); i++ { + for i := range field.NumField() { fld := field.Field(i) stFld := field.Type().Field(i) @@ -142,7 +142,7 @@ func setStruct(field reflect.Value) error { func setSlice(field reflect.Value) error { field.Set(reflect.MakeSlice(field.Type(), sliceItemNumber, sliceItemNumber)) - for j := 0; j < field.Len(); j++ { + for j := range field.Len() { if err := fill(field.Index(j)); err != nil { return err } diff --git a/pkg/config/kv/kv.go b/pkg/config/kv/kv.go index 8af4855e3..ad467b00d 100644 --- a/pkg/config/kv/kv.go +++ b/pkg/config/kv/kv.go @@ -55,7 +55,7 @@ func getFieldNames(rootName string, rootType reflect.Type) []string { return nil } - for i := 0; i < rootType.NumField(); i++ { + for i := range rootType.NumField() { field := rootType.Field(i) if !parser.IsExported(field) { diff --git a/pkg/middlewares/accesslog/logger_test.go b/pkg/middlewares/accesslog/logger_test.go index a70e2cc6f..b599e3e8d 100644 --- a/pkg/middlewares/accesslog/logger_test.go +++ b/pkg/middlewares/accesslog/logger_test.go @@ -74,7 +74,7 @@ func TestLogRotation(t *testing.T) { halfDone := make(chan bool) writeDone := make(chan bool) go func() { - for i := 0; i < iterations; i++ { + for i := range iterations { handler.ServeHTTP(recorder, req) if i == iterations/2 { halfDone <- true diff --git a/pkg/middlewares/capture/capture_test.go b/pkg/middlewares/capture/capture_test.go index 776dd74d8..2254b0fea 100644 --- a/pkg/middlewares/capture/capture_test.go +++ b/pkg/middlewares/capture/capture_test.go @@ -149,7 +149,7 @@ func BenchmarkCapture(b *testing.B) { b.ReportAllocs() b.SetBytes(int64(test.size)) b.ResetTimer() - for i := 0; i < b.N; i++ { + for range b.N { runBenchmark(b, test.size, req, handlers) } }) @@ -170,7 +170,7 @@ func runBenchmark(b *testing.B, size int, req *http.Request, handler http.Handle func generateBytes(length int) []byte { var value []byte - for i := 0; i < length; i++ { + for i := range length { value = append(value, 0x61+byte(i%26)) } return value diff --git a/pkg/middlewares/compress/compress_test.go b/pkg/middlewares/compress/compress_test.go index 10f07fda0..3bdaf9678 100644 --- a/pkg/middlewares/compress/compress_test.go +++ b/pkg/middlewares/compress/compress_test.go @@ -499,7 +499,7 @@ func BenchmarkCompress(b *testing.B) { } b.ResetTimer() - for i := 0; i < b.N; i++ { + for range b.N { runBenchmark(b, req, handler) } }) @@ -520,7 +520,7 @@ func runBenchmark(b *testing.B, req *http.Request, handler http.Handler) { func generateBytes(length int) []byte { var value []byte - for i := 0; i < length; i++ { + for i := range length { value = append(value, 0x61+byte(i)) } return value diff --git a/pkg/middlewares/emptybackendhandler/empty_backend_handler_test.go b/pkg/middlewares/emptybackendhandler/empty_backend_handler_test.go index 657be8201..fddb9c768 100644 --- a/pkg/middlewares/emptybackendhandler/empty_backend_handler_test.go +++ b/pkg/middlewares/emptybackendhandler/empty_backend_handler_test.go @@ -58,7 +58,7 @@ func (lb *healthCheckLoadBalancer) ServeHTTP(w http.ResponseWriter, r *http.Requ func (lb *healthCheckLoadBalancer) Servers() []*url.URL { servers := make([]*url.URL, lb.amountServer) - for i := 0; i < lb.amountServer; i++ { + for range lb.amountServer { servers = append(servers, testhelpers.MustParseURL("http://localhost")) } return servers diff --git a/pkg/middlewares/metrics/metrics.go b/pkg/middlewares/metrics/metrics.go index c4fc78801..3c278a9d2 100644 --- a/pkg/middlewares/metrics/metrics.go +++ b/pkg/middlewares/metrics/metrics.go @@ -3,6 +3,7 @@ package metrics import ( "context" "net/http" + "slices" "strconv" "strings" "time" @@ -175,12 +176,10 @@ func isSSERequest(req *http.Request) bool { func containsHeader(req *http.Request, name, value string) bool { items := strings.Split(req.Header.Get(name), ",") - for _, item := range items { - if value == strings.ToLower(strings.TrimSpace(item)) { - return true - } - } - return false + + return slices.ContainsFunc(items, func(item string) bool { + return value == strings.ToLower(strings.TrimSpace(item)) + }) } // getMethod returns the request's method. diff --git a/pkg/middlewares/requestdecorator/hostresolver.go b/pkg/middlewares/requestdecorator/hostresolver.go index d08768175..3f6e4f882 100644 --- a/pkg/middlewares/requestdecorator/hostresolver.go +++ b/pkg/middlewares/requestdecorator/hostresolver.go @@ -49,7 +49,7 @@ func (hr *Resolver) CNAMEFlatten(ctx context.Context, host string) string { logger := log.FromContext(ctx) cacheDuration := 0 * time.Second - for depth := 0; depth < hr.ResolvDepth; depth++ { + for depth := range hr.ResolvDepth { resolv, err := cnameResolve(ctx, request, hr.ResolvConfig) if err != nil { logger.Error(err) diff --git a/pkg/middlewares/retry/retry_test.go b/pkg/middlewares/retry/retry_test.go index 8da95f8e1..5645e007c 100644 --- a/pkg/middlewares/retry/retry_test.go +++ b/pkg/middlewares/retry/retry_test.go @@ -203,7 +203,7 @@ func TestMultipleRetriesShouldNotLooseHeaders(t *testing.T) { } // Validate that we don't have headers from previous attempts - for i := 0; i < attempt; i++ { + for i := range attempt { headerName := fmt.Sprintf("X-Foo-Test-%d", i) headerValue = responseRecorder.Header().Get("headerName") if headerValue != "" { diff --git a/pkg/muxer/http/mux.go b/pkg/muxer/http/mux.go index fefab67a9..ca011b79c 100644 --- a/pkg/muxer/http/mux.go +++ b/pkg/muxer/http/mux.go @@ -324,11 +324,7 @@ func addRuleOnRoute(route *mux.Route, rule *rules.Tree) error { // IsASCII checks if the given string contains only ASCII characters. func IsASCII(s string) bool { - for i := 0; i < len(s); i++ { - if s[i] >= utf8.RuneSelf { - return false - } - } - - return true + return !strings.ContainsFunc(s, func(r rune) bool { + return r >= utf8.RuneSelf + }) } diff --git a/pkg/muxer/tcp/mux.go b/pkg/muxer/tcp/mux.go index 592738b24..e50b78899 100644 --- a/pkg/muxer/tcp/mux.go +++ b/pkg/muxer/tcp/mux.go @@ -6,6 +6,7 @@ import ( "fmt" "net" "regexp" + "slices" "sort" "strconv" "strings" @@ -301,15 +302,9 @@ func alpn(tree *matchersTree, protos ...string) error { } tree.matcher = func(meta ConnData) bool { - for _, proto := range meta.alpnProtos { - for _, filter := range protos { - if proto == filter { - return true - } - } - } - - return false + return slices.ContainsFunc(meta.alpnProtos, func(proto string) bool { + return slices.Contains(protos, proto) + }) } return nil @@ -469,7 +464,7 @@ func varGroupName(idx int) string { func braceIndices(s string) ([]int, error) { var level, idx int var idxs []int - for i := 0; i < len(s); i++ { + for i := range len(s) { switch s[i] { case '{': if level++; level == 1 { diff --git a/pkg/provider/acme/challenge_tls.go b/pkg/provider/acme/challenge_tls.go index 6249bc52e..3513d03a3 100644 --- a/pkg/provider/acme/challenge_tls.go +++ b/pkg/provider/acme/challenge_tls.go @@ -2,6 +2,7 @@ package acme import ( "fmt" + "slices" "sync" "time" @@ -118,7 +119,7 @@ func (c *ChallengeTLSALPN) ListenConfiguration(conf dynamic.Configuration) { c.muChans.Lock() for _, certificate := range conf.TLS.Certificates { - if !containsACMETLS1(certificate.Stores) { + if !slices.Contains(certificate.Stores, tlsalpn01.ACMETLS1Protocol) { continue } @@ -161,13 +162,3 @@ func createMessage(certs map[string]*Certificate) dynamic.Message { return conf } - -func containsACMETLS1(stores []string) bool { - for _, store := range stores { - if store == tlsalpn01.ACMETLS1Protocol { - return true - } - } - - return false -} diff --git a/pkg/provider/acme/provider.go b/pkg/provider/acme/provider.go index 451ee83b1..bdb6ea02a 100644 --- a/pkg/provider/acme/provider.go +++ b/pkg/provider/acme/provider.go @@ -424,7 +424,7 @@ func (p *Provider) watchNewDomains(ctx context.Context) { if len(route.TLS.Domains) > 0 { domains := deleteUnnecessaryDomains(ctxRouter, route.TLS.Domains) - for i := 0; i < len(domains); i++ { + for i := range len(domains) { domain := domains[i] safe.Go(func() { dom, cert, err := p.resolveCertificate(ctx, domain, traefiktls.DefaultTLSStoreName) @@ -461,7 +461,7 @@ func (p *Provider) watchNewDomains(ctx context.Context) { if len(route.TLS.Domains) > 0 { domains := deleteUnnecessaryDomains(ctxRouter, route.TLS.Domains) - for i := 0; i < len(domains); i++ { + for i := range len(domains) { domain := domains[i] safe.Go(func() { dom, cert, err := p.resolveCertificate(ctx, domain, traefiktls.DefaultTLSStoreName) diff --git a/pkg/provider/constraints/constraints_tags.go b/pkg/provider/constraints/constraints_tags.go index cb29997a3..b61f43c5d 100644 --- a/pkg/provider/constraints/constraints_tags.go +++ b/pkg/provider/constraints/constraints_tags.go @@ -3,6 +3,7 @@ package constraints import ( "errors" "regexp" + "slices" "github.com/vulcand/predicate" ) @@ -47,12 +48,7 @@ func MatchTags(tags []string, expr string) (bool, error) { func tagFn(name string) constraintTagFunc { return func(tags []string) bool { - for _, tag := range tags { - if tag == name { - return true - } - } - return false + return slices.Contains(tags, name) } } @@ -63,13 +59,9 @@ func tagRegexFn(expr string) constraintTagFunc { return false } - for _, tag := range tags { - if exp.MatchString(tag) { - return true - } - } - - return false + return slices.ContainsFunc(tags, func(tag string) bool { + return exp.MatchString(tag) + }) } } diff --git a/pkg/provider/consulcatalog/config_test.go b/pkg/provider/consulcatalog/config_test.go index 666320404..bb6f41846 100644 --- a/pkg/provider/consulcatalog/config_test.go +++ b/pkg/provider/consulcatalog/config_test.go @@ -274,7 +274,7 @@ func TestDefaultRule(t *testing.T) { err := p.Init() require.NoError(t, err) - for i := 0; i < len(test.items); i++ { + for i := range len(test.items) { var err error test.items[i].ExtraConf, err = p.getExtraConf(test.items[i].Labels) require.NoError(t, err) @@ -2956,7 +2956,7 @@ func Test_buildConfiguration(t *testing.T) { err := p.Init() require.NoError(t, err) - for i := 0; i < len(test.items); i++ { + for i := range len(test.items) { var err error test.items[i].ExtraConf, err = p.getExtraConf(test.items[i].Labels) require.NoError(t, err) diff --git a/pkg/provider/docker/config_test.go b/pkg/provider/docker/config_test.go index cb7877226..a8fd786e1 100644 --- a/pkg/provider/docker/config_test.go +++ b/pkg/provider/docker/config_test.go @@ -361,7 +361,7 @@ func TestDefaultRule(t *testing.T) { err := p.Init() require.NoError(t, err) - for i := 0; i < len(test.containers); i++ { + for i := range len(test.containers) { var err error test.containers[i].ExtraConf, err = p.getConfiguration(test.containers[i]) require.NoError(t, err) @@ -3257,7 +3257,7 @@ func Test_buildConfiguration(t *testing.T) { err := p.Init() require.NoError(t, err) - for i := 0; i < len(test.containers); i++ { + for i := range len(test.containers) { var err error test.containers[i].ExtraConf, err = p.getConfiguration(test.containers[i]) require.NoError(t, err) diff --git a/pkg/provider/ecs/config_test.go b/pkg/provider/ecs/config_test.go index 76b18887f..e6a190213 100644 --- a/pkg/provider/ecs/config_test.go +++ b/pkg/provider/ecs/config_test.go @@ -333,7 +333,7 @@ func TestDefaultRule(t *testing.T) { err := p.Init() require.NoError(t, err) - for i := 0; i < len(test.instances); i++ { + for i := range len(test.instances) { var err error test.instances[i].ExtraConf, err = p.getConfiguration(test.instances[i]) require.NoError(t, err) @@ -2863,7 +2863,7 @@ func Test_buildConfiguration(t *testing.T) { err := p.Init() require.NoError(t, err) - for i := 0; i < len(test.containers); i++ { + for i := range len(test.containers) { var err error test.containers[i].ExtraConf, err = p.getConfiguration(test.containers[i]) require.NoError(t, err) diff --git a/pkg/provider/ecs/ecs.go b/pkg/provider/ecs/ecs.go index 8def19a85..e2edfbbc7 100644 --- a/pkg/provider/ecs/ecs.go +++ b/pkg/provider/ecs/ecs.go @@ -397,7 +397,7 @@ func (p *Provider) listInstances(ctx context.Context, client *awsClient) ([]ecsI } func (p *Provider) lookupMiInstances(ctx context.Context, client *awsClient, clusterName *string, ecsDatas map[string]*ecs.Task) (map[string]*ssm.InstanceInformation, error) { - instanceIds := make(map[string]string) + instanceIDs := make(map[string]string) miInstances := make(map[string]*ssm.InstanceInformation) var containerInstancesArns []*string @@ -419,7 +419,7 @@ func (p *Provider) lookupMiInstances(ctx context.Context, client *awsClient, clu } for _, container := range resp.ContainerInstances { - instanceIds[aws.StringValue(container.Ec2InstanceId)] = aws.StringValue(container.ContainerInstanceArn) + instanceIDs[aws.StringValue(container.Ec2InstanceId)] = aws.StringValue(container.ContainerInstanceArn) // Disallow EC2 Instance IDs // This prevents considering EC2 instances in ECS @@ -447,7 +447,7 @@ func (p *Provider) lookupMiInstances(ctx context.Context, client *awsClient, clu if len(page.InstanceInformationList) > 0 { for _, i := range page.InstanceInformationList { if i.InstanceId != nil { - miInstances[instanceIds[aws.StringValue(i.InstanceId)]] = i + miInstances[instanceIDs[aws.StringValue(i.InstanceId)]] = i } } } @@ -463,7 +463,7 @@ func (p *Provider) lookupMiInstances(ctx context.Context, client *awsClient, clu } func (p *Provider) lookupEc2Instances(ctx context.Context, client *awsClient, clusterName *string, ecsDatas map[string]*ecs.Task) (map[string]*ec2.Instance, error) { - instanceIds := make(map[string]string) + instanceIDs := make(map[string]string) ec2Instances := make(map[string]*ec2.Instance) var containerInstancesArns []*string @@ -485,7 +485,7 @@ func (p *Provider) lookupEc2Instances(ctx context.Context, client *awsClient, cl } for _, container := range resp.ContainerInstances { - instanceIds[aws.StringValue(container.Ec2InstanceId)] = aws.StringValue(container.ContainerInstanceArn) + instanceIDs[aws.StringValue(container.Ec2InstanceId)] = aws.StringValue(container.ContainerInstanceArn) // Disallow Instance IDs of the form mi-* // This prevents considering external instances in ECS Anywhere setups // and getting InvalidInstanceID.Malformed error when calling the describe-instances endpoint. @@ -508,7 +508,7 @@ func (p *Provider) lookupEc2Instances(ctx context.Context, client *awsClient, cl for _, r := range page.Reservations { for _, i := range r.Instances { if i.InstanceId != nil { - ec2Instances[instanceIds[aws.StringValue(i.InstanceId)]] = i + ec2Instances[instanceIDs[aws.StringValue(i.InstanceId)]] = i } } } diff --git a/pkg/provider/ecs/ecs_test.go b/pkg/provider/ecs/ecs_test.go index f55510305..ede115a41 100644 --- a/pkg/provider/ecs/ecs_test.go +++ b/pkg/provider/ecs/ecs_test.go @@ -73,7 +73,7 @@ func TestChunkIDs(t *testing.T) { t.Parallel() var IDs []*string - for v := 0; v < test.count; v++ { + for range test.count { IDs = append(IDs, aws.String("a")) } diff --git a/pkg/provider/kubernetes/crd/client.go b/pkg/provider/kubernetes/crd/client.go index c678db966..97047f138 100644 --- a/pkg/provider/kubernetes/crd/client.go +++ b/pkg/provider/kubernetes/crd/client.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" "runtime" + "slices" "time" "github.com/traefik/traefik/v2/pkg/log" @@ -452,12 +453,8 @@ func (c *clientWrapper) isWatchedNamespace(ns string) bool { if c.isNamespaceAll { return true } - for _, watchedNamespace := range c.watchedNamespaces { - if watchedNamespace == ns { - return true - } - } - return false + + return slices.Contains(c.watchedNamespaces, ns) } // translateNotFoundError will translate a "not found" error to a boolean return diff --git a/pkg/provider/kubernetes/gateway/client.go b/pkg/provider/kubernetes/gateway/client.go index 59f29fbb4..747f2503f 100644 --- a/pkg/provider/kubernetes/gateway/client.go +++ b/pkg/provider/kubernetes/gateway/client.go @@ -5,6 +5,7 @@ import ( "errors" "fmt" "os" + "slices" "time" "github.com/traefik/traefik/v2/pkg/log" @@ -548,10 +549,6 @@ func (c *clientWrapper) isWatchedNamespace(ns string) bool { if c.isNamespaceAll { return true } - for _, watchedNamespace := range c.watchedNamespaces { - if watchedNamespace == ns { - return true - } - } - return false + + return slices.Contains(c.watchedNamespaces, ns) } diff --git a/pkg/provider/kubernetes/ingress/client.go b/pkg/provider/kubernetes/ingress/client.go index 3d2c002f4..a0893b771 100644 --- a/pkg/provider/kubernetes/ingress/client.go +++ b/pkg/provider/kubernetes/ingress/client.go @@ -7,6 +7,7 @@ import ( "os" "path/filepath" "runtime" + "slices" "time" "github.com/hashicorp/go-version" @@ -538,12 +539,8 @@ func (c *clientWrapper) isWatchedNamespace(ns string) bool { if c.isNamespaceAll { return true } - for _, watchedNamespace := range c.watchedNamespaces { - if watchedNamespace == ns { - return true - } - } - return false + + return slices.Contains(c.watchedNamespaces, ns) } // IngressClass objects are supported since Kubernetes v1.18. diff --git a/pkg/provider/kubernetes/ingress/kubernetes.go b/pkg/provider/kubernetes/ingress/kubernetes.go index 7b43ead4f..bc1f9a413 100644 --- a/pkg/provider/kubernetes/ingress/kubernetes.go +++ b/pkg/provider/kubernetes/ingress/kubernetes.go @@ -8,6 +8,7 @@ import ( "math" "net" "os" + "slices" "sort" "strconv" "strings" @@ -412,13 +413,9 @@ func (p *Provider) updateIngressStatus(ing *netv1.Ingress, k8sClient Client) err func (p *Provider) shouldProcessIngress(ingress *netv1.Ingress, ingressClasses []*netv1.IngressClass) bool { // configuration through the new kubernetes ingressClass if ingress.Spec.IngressClassName != nil { - for _, ic := range ingressClasses { - if *ingress.Spec.IngressClassName == ic.ObjectMeta.Name { - return true - } - } - - return false + return slices.ContainsFunc(ingressClasses, func(ic *netv1.IngressClass) bool { + return *ingress.Spec.IngressClassName == ic.ObjectMeta.Name + }) } return p.IngressClass == ingress.Annotations[annotationKubernetesIngressClass] || diff --git a/pkg/provider/rancher/config_test.go b/pkg/provider/rancher/config_test.go index efab43f4a..0db7b955b 100644 --- a/pkg/provider/rancher/config_test.go +++ b/pkg/provider/rancher/config_test.go @@ -1146,7 +1146,7 @@ func Test_buildConfiguration(t *testing.T) { err := p.Init() require.NoError(t, err) - for i := 0; i < len(test.containers); i++ { + for i := range len(test.containers) { var err error test.containers[i].ExtraConf, err = p.getConfiguration(test.containers[i]) require.NoError(t, err) diff --git a/pkg/redactor/redactor.go b/pkg/redactor/redactor.go index d655a673b..ccdcc5b18 100644 --- a/pkg/redactor/redactor.go +++ b/pkg/redactor/redactor.go @@ -83,7 +83,7 @@ func doOnStruct(field reflect.Value, tag string, redactByDefault bool) error { } } case reflect.Struct: - for i := 0; i < field.NumField(); i++ { + for i := range field.NumField() { fld := field.Field(i) stField := field.Type().Field(i) if !isExported(stField) { @@ -138,7 +138,7 @@ func doOnStruct(field reflect.Value, tag string, redactByDefault bool) error { } } case reflect.Slice: - for j := 0; j < field.Len(); j++ { + for j := range field.Len() { if err := doOnStruct(field.Index(j), tag, redactByDefault); err != nil { return err } @@ -179,7 +179,7 @@ func reset(field reflect.Value, name string) error { switch field.Type().Elem().Kind() { case reflect.String: slice := reflect.MakeSlice(field.Type(), field.Len(), field.Len()) - for j := 0; j < field.Len(); j++ { + for j := range field.Len() { slice.Index(j).SetString(maskShort) } field.Set(slice) diff --git a/pkg/server/aggregator.go b/pkg/server/aggregator.go index 4b50829e8..f34e76c00 100644 --- a/pkg/server/aggregator.go +++ b/pkg/server/aggregator.go @@ -1,6 +1,8 @@ package server import ( + "slices" + "github.com/go-acme/lego/v4/challenge/tlsalpn01" "github.com/traefik/traefik/v2/pkg/config/dynamic" "github.com/traefik/traefik/v2/pkg/log" @@ -91,7 +93,7 @@ func mergeConfiguration(configurations dynamic.Configurations, defaultEntryPoint if configuration.TLS != nil { for _, cert := range configuration.TLS.Certificates { - if containsACMETLS1(cert.Stores) && pvd != "tlsalpn.acme" { + if slices.Contains(cert.Stores, tlsalpn01.ACMETLS1Protocol) && pvd != "tlsalpn.acme" { continue } @@ -179,13 +181,3 @@ func applyModel(cfg dynamic.Configuration) dynamic.Configuration { return cfg } - -func containsACMETLS1(stores []string) bool { - for _, store := range stores { - if store == tlsalpn01.ACMETLS1Protocol { - return true - } - } - - return false -} diff --git a/pkg/server/configurationwatcher_test.go b/pkg/server/configurationwatcher_test.go index 7cf68b881..cc909c81d 100644 --- a/pkg/server/configurationwatcher_test.go +++ b/pkg/server/configurationwatcher_test.go @@ -305,7 +305,7 @@ func TestListenProvidersThrottleProviderConfigReload(t *testing.T) { throttleDuration: 30 * time.Millisecond, } - for i := 0; i < 5; i++ { + for i := range 5 { pvd.messages = append(pvd.messages, dynamic.Message{ ProviderName: "mock", Configuration: &dynamic.Configuration{ diff --git a/pkg/server/middleware/middlewares.go b/pkg/server/middleware/middlewares.go index 073843472..05a4229d3 100644 --- a/pkg/server/middleware/middlewares.go +++ b/pkg/server/middleware/middlewares.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "reflect" + "slices" "strings" "github.com/containous/alice" @@ -97,7 +98,7 @@ func checkRecursion(ctx context.Context, middlewareName string) (context.Context if !ok { currentStack = []string{} } - if inSlice(middlewareName, currentStack) { + if slices.Contains(currentStack, middlewareName) { return ctx, fmt.Errorf("could not instantiate middleware %s: recursion detected in %s", middlewareName, strings.Join(append(currentStack, middlewareName), "->")) } return context.WithValue(ctx, middlewareStackKey, append(currentStack, middlewareName)), nil @@ -381,12 +382,3 @@ func (b *Builder) buildConstructor(ctx context.Context, middlewareName string) ( return tracing.Wrap(ctx, middleware), nil } - -func inSlice(element string, stack []string) bool { - for _, value := range stack { - if value == element { - return true - } - } - return false -} diff --git a/pkg/server/middleware/tcp/middlewares.go b/pkg/server/middleware/tcp/middlewares.go index 5599a956c..98a3167aa 100644 --- a/pkg/server/middleware/tcp/middlewares.go +++ b/pkg/server/middleware/tcp/middlewares.go @@ -3,6 +3,7 @@ package tcpmiddleware import ( "context" "fmt" + "slices" "strings" "github.com/traefik/traefik/v2/pkg/config/runtime" @@ -74,7 +75,7 @@ func checkRecursion(ctx context.Context, middlewareName string) (context.Context currentStack = []string{} } - if inSlice(middlewareName, currentStack) { + if slices.Contains(currentStack, middlewareName) { return ctx, fmt.Errorf("could not instantiate middleware %s: recursion detected in %s", middlewareName, strings.Join(append(currentStack, middlewareName), "->")) } @@ -117,12 +118,3 @@ func (b *Builder) buildConstructor(ctx context.Context, middlewareName string) ( return middleware, nil } - -func inSlice(element string, stack []string) bool { - for _, value := range stack { - if value == element { - return true - } - } - return false -} diff --git a/pkg/server/router/router_test.go b/pkg/server/router/router_test.go index 0ba85b527..65d074039 100644 --- a/pkg/server/router/router_test.go +++ b/pkg/server/router/router_test.go @@ -945,7 +945,7 @@ func BenchmarkRouterServe(b *testing.B) { reqHost := requestdecorator.New(nil) b.ReportAllocs() - for i := 0; i < b.N; i++ { + for range b.N { reqHost.ServeHTTP(w, req, handlers["web"].ServeHTTP) } } @@ -980,7 +980,7 @@ func BenchmarkService(b *testing.B) { handler, _ := serviceManager.BuildHTTP(context.Background(), "foo-service") b.ReportAllocs() - for i := 0; i < b.N; i++ { + for range b.N { handler.ServeHTTP(w, req) } } diff --git a/pkg/server/server_entrypoint_tcp_test.go b/pkg/server/server_entrypoint_tcp_test.go index 9d66c44e0..f0b12c8dd 100644 --- a/pkg/server/server_entrypoint_tcp_test.go +++ b/pkg/server/server_entrypoint_tcp_test.go @@ -112,7 +112,7 @@ func testShutdown(t *testing.T, router *tcprouter.Router) { // but technically also as early as the Shutdown has closed the listener, // i.e. during the shutdown and before the gracetime is over. var testOk bool - for i := 0; i < 10; i++ { + for range 10 { loopConn, err := net.Dial("tcp", epAddr) if err == nil { loopConn.Close() @@ -141,7 +141,7 @@ func startEntrypoint(entryPoint *TCPEntryPoint, router *tcprouter.Router) (net.C entryPoint.SwitchRouter(router) - for i := 0; i < 10; i++ { + for range 10 { conn, err := net.Dial("tcp", entryPoint.listener.Addr().String()) if err != nil { time.Sleep(100 * time.Millisecond) diff --git a/pkg/server/service/loadbalancer/mirror/mirror_test.go b/pkg/server/service/loadbalancer/mirror/mirror_test.go index 430baac8f..b417fa13d 100644 --- a/pkg/server/service/loadbalancer/mirror/mirror_test.go +++ b/pkg/server/service/loadbalancer/mirror/mirror_test.go @@ -32,7 +32,7 @@ func TestMirroringOn100(t *testing.T) { }), 50) assert.NoError(t, err) - for i := 0; i < 100; i++ { + for range 100 { mirror.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) } @@ -61,7 +61,7 @@ func TestMirroringOn10(t *testing.T) { }), 50) assert.NoError(t, err) - for i := 0; i < 10; i++ { + for range 10 { mirror.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) } @@ -156,7 +156,7 @@ func TestMirroringWithBody(t *testing.T) { mirror := New(handler, pool, defaultMaxBodySize, nil) - for i := 0; i < numMirrors; i++ { + for range numMirrors { err := mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { assert.NotNil(t, r.Body) bb, err := io.ReadAll(r.Body) diff --git a/pkg/server/service/loadbalancer/wrr/wrr_test.go b/pkg/server/service/loadbalancer/wrr/wrr_test.go index 7328fd98d..32068504e 100644 --- a/pkg/server/service/loadbalancer/wrr/wrr_test.go +++ b/pkg/server/service/loadbalancer/wrr/wrr_test.go @@ -40,7 +40,7 @@ func TestBalancer(t *testing.T) { }), Int(1)) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} - for i := 0; i < 4; i++ { + for range 4 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } @@ -68,7 +68,7 @@ func TestBalancerOneServerZeroWeight(t *testing.T) { balancer.AddService("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), Int(0)) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} - for i := 0; i < 3; i++ { + for range 3 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } @@ -113,7 +113,7 @@ func TestBalancerOneServerDown(t *testing.T) { balancer.SetStatus(context.WithValue(context.Background(), serviceName, "parent"), "second", false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} - for i := 0; i < 3; i++ { + for range 3 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } @@ -135,14 +135,14 @@ func TestBalancerDownThenUp(t *testing.T) { balancer.SetStatus(context.WithValue(context.Background(), serviceName, "parent"), "second", false) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} - for i := 0; i < 3; i++ { + for range 3 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 3, recorder.save["first"]) balancer.SetStatus(context.WithValue(context.Background(), serviceName, "parent"), "second", true) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} - for i := 0; i < 2; i++ { + for range 2 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 1, recorder.save["first"]) @@ -184,7 +184,7 @@ func TestBalancerPropagate(t *testing.T) { }) recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} - for i := 0; i < 8; i++ { + for range 8 { topBalancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 2, recorder.save["first"]) @@ -197,7 +197,7 @@ func TestBalancerPropagate(t *testing.T) { // fourth gets downed, but balancer2 still up since third is still up. balancer2.SetStatus(context.WithValue(context.Background(), serviceName, "top"), "fourth", false) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} - for i := 0; i < 8; i++ { + for range 8 { topBalancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 2, recorder.save["first"]) @@ -211,7 +211,7 @@ func TestBalancerPropagate(t *testing.T) { // down as well for topBalancer. balancer2.SetStatus(context.WithValue(context.Background(), serviceName, "top"), "third", false) recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} - for i := 0; i < 8; i++ { + for range 8 { topBalancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } assert.Equal(t, 4, recorder.save["first"]) @@ -252,7 +252,7 @@ func TestSticky(t *testing.T) { recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} req := httptest.NewRequest(http.MethodGet, "/", nil) - for i := 0; i < 3; i++ { + for range 3 { for _, cookie := range recorder.Result().Cookies() { assert.NotContains(t, "test=first", cookie.Value) assert.NotContains(t, "test=second", cookie.Value) @@ -286,7 +286,7 @@ func TestSticky_FallBack(t *testing.T) { req := httptest.NewRequest(http.MethodGet, "/", nil) req.AddCookie(&http.Cookie{Name: "test", Value: "second"}) - for i := 0; i < 3; i++ { + for range 3 { recorder.ResponseRecorder = httptest.NewRecorder() balancer.ServeHTTP(recorder, req) @@ -313,7 +313,7 @@ func TestBalancerBias(t *testing.T) { recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} - for i := 0; i < 14; i++ { + for range 14 { balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil)) } diff --git a/pkg/server/service/proxy_test.go b/pkg/server/service/proxy_test.go index 3a0a34553..567ba6105 100644 --- a/pkg/server/service/proxy_test.go +++ b/pkg/server/service/proxy_test.go @@ -31,7 +31,7 @@ func BenchmarkProxy(b *testing.B) { handler, _ := buildProxy(Bool(false), nil, &staticTransport{res}, pool) b.ReportAllocs() - for i := 0; i < b.N; i++ { + for range b.N { handler.ServeHTTP(w, req) } } diff --git a/pkg/server/service/roundtripper.go b/pkg/server/service/roundtripper.go index 31493bbb9..fc5f9e88b 100644 --- a/pkg/server/service/roundtripper.go +++ b/pkg/server/service/roundtripper.go @@ -9,6 +9,7 @@ import ( "net" "net/http" "reflect" + "slices" "strings" "sync" "time" @@ -210,12 +211,9 @@ func (k *KerberosRoundTripper) RoundTrip(request *http.Request) (*http.Response, } func containsNTLMorNegotiate(h []string) bool { - for _, s := range h { - if strings.HasPrefix(s, "NTLM") || strings.HasPrefix(s, "Negotiate") { - return true - } - } - return false + return slices.ContainsFunc(h, func(s string) bool { + return strings.HasPrefix(s, "NTLM") || strings.HasPrefix(s, "Negotiate") + }) } func createRootCACertPool(rootCAs []traefiktls.FileOrContent) *x509.CertPool { diff --git a/pkg/server/service/roundtripper_test.go b/pkg/server/service/roundtripper_test.go index 460bc9a60..d9212ab8d 100644 --- a/pkg/server/service/roundtripper_test.go +++ b/pkg/server/service/roundtripper_test.go @@ -139,7 +139,7 @@ func TestKeepConnectionWhenSameConfiguration(t *testing.T) { }, } - for i := 0; i < 10; i++ { + for range 10 { rtManager.Update(dynamicConf) tr, err := rtManager.Get("test") diff --git a/pkg/server/service/service.go b/pkg/server/service/service.go index 39dacd5ad..cc43e76a2 100644 --- a/pkg/server/service/service.go +++ b/pkg/server/service/service.go @@ -85,7 +85,7 @@ func (m *Manager) BuildHTTP(rootCtx context.Context, serviceName string) (http.H value := reflect.ValueOf(*conf.Service) var count int - for i := 0; i < value.NumField(); i++ { + for i := range value.NumField() { if !value.Field(i).IsNil() { count++ } diff --git a/pkg/tcp/wrr_load_balancer_test.go b/pkg/tcp/wrr_load_balancer_test.go index a07f51762..5ee18caad 100644 --- a/pkg/tcp/wrr_load_balancer_test.go +++ b/pkg/tcp/wrr_load_balancer_test.go @@ -135,7 +135,7 @@ func TestLoadBalancing(t *testing.T) { } conn := &fakeConn{writeCall: make(map[string]int)} - for i := 0; i < test.totalCall; i++ { + for range test.totalCall { balancer.ServeTCP(conn) } diff --git a/pkg/tls/tlsmanager.go b/pkg/tls/tlsmanager.go index fb2be8efe..3208ad7d3 100644 --- a/pkg/tls/tlsmanager.go +++ b/pkg/tls/tlsmanager.go @@ -6,6 +6,7 @@ import ( "crypto/x509" "errors" "fmt" + "slices" "strings" "sync" @@ -181,7 +182,7 @@ func (m *Manager) Get(storeName, configName string) (*tls.Config, error) { tlsConfig.GetCertificate = func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) { domainToCheck := types.CanonicalDomain(clientHello.ServerName) - if isACMETLS(clientHello) { + if slices.Contains(clientHello.SupportedProtos, tlsalpn01.ACMETLS1Protocol) { certificate := acmeTLSStore.GetBestCertificate(clientHello) if certificate == nil { log.WithoutContext().Debugf("TLS: no certificate for TLSALPN challenge: %s", domainToCheck) @@ -419,13 +420,3 @@ func buildDefaultCertificate(defaultCertificate *Certificate) (*tls.Certificate, } return &cert, nil } - -func isACMETLS(clientHello *tls.ClientHelloInfo) bool { - for _, proto := range clientHello.SupportedProtos { - if proto == tlsalpn01.ACMETLS1Protocol { - return true - } - } - - return false -} diff --git a/pkg/types/http_code_range.go b/pkg/types/http_code_range.go index 4a8f541a5..b00ac1957 100644 --- a/pkg/types/http_code_range.go +++ b/pkg/types/http_code_range.go @@ -1,6 +1,7 @@ package types import ( + "slices" "strconv" "strings" ) @@ -34,10 +35,7 @@ func NewHTTPCodeRanges(strBlocks []string) (HTTPCodeRanges, error) { // Contains tests whether the passed status code is within one of its HTTP code ranges. func (h HTTPCodeRanges) Contains(statusCode int) bool { - for _, block := range h { - if statusCode >= block[0] && statusCode <= block[1] { - return true - } - } - return false + return slices.ContainsFunc(h, func(block [2]int) bool { + return statusCode >= block[0] && statusCode <= block[1] + }) } diff --git a/pkg/udp/conn_test.go b/pkg/udp/conn_test.go index 44e748474..651d70064 100644 --- a/pkg/udp/conn_test.go +++ b/pkg/udp/conn_test.go @@ -210,7 +210,7 @@ func testTimeout(t *testing.T, withRead bool) { } }() - for i := 0; i < 10; i++ { + for range 10 { udpConn2, err := net.Dial("udp", ln.Addr().String()) require.NoError(t, err)