chore: update linter

This commit is contained in:
Ludovic Fernandez 2024-02-19 15:44:03 +01:00 committed by GitHub
parent 1034646ae2
commit 88a2020817
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
57 changed files with 139 additions and 218 deletions

View file

@ -7,7 +7,7 @@ on:
env: env:
GO_VERSION: '1.22' GO_VERSION: '1.22'
GOLANGCI_LINT_VERSION: v1.56.0 GOLANGCI_LINT_VERSION: v1.56.2
MISSSPELL_VERSION: v0.4.1 MISSSPELL_VERSION: v0.4.1
jobs: jobs:

View file

@ -225,7 +225,7 @@ issues:
- 'SA1019: c.Providers.ConsulCatalog.Namespace is deprecated' - 'SA1019: c.Providers.ConsulCatalog.Namespace is deprecated'
- 'SA1019: c.Providers.Consul.Namespace is deprecated' - 'SA1019: c.Providers.Consul.Namespace is deprecated'
- 'SA1019: c.Providers.Nomad.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: exclude-rules:
- path: '(.+)_test.go' - path: '(.+)_test.go'
linters: linters:

View file

@ -25,7 +25,7 @@ global_job_config:
- export "PATH=${GOPATH}/bin:${PATH}" - export "PATH=${GOPATH}/bin:${PATH}"
- mkdir -vp "${SEMAPHORE_GIT_DIR}" "${GOPATH}/bin" - mkdir -vp "${SEMAPHORE_GIT_DIR}" "${GOPATH}/bin"
- export GOPROXY=https://proxy.golang.org,direct - 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" - curl -sSfL https://gist.githubusercontent.com/traefiker/6d7ac019c11d011e4f131bb2cca8900e/raw/goreleaser.sh | bash -s -- -b "${GOPATH}/bin"
- checkout - checkout
- cache restore traefik-$(checksum go.sum) - cache restore traefik-$(checksum go.sum)

View file

@ -160,7 +160,7 @@ func (c Centrifuge) writeStruct(name string, obj *types.Struct, rootPkg string,
b := strings.Builder{} b := strings.Builder{}
b.WriteString(fmt.Sprintf("type %s struct {\n", name)) 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) field := obj.Field(i)
if !field.Exported() { if !field.Exported() {

View file

@ -67,7 +67,7 @@ func (s *ThrottlingSuite) TestThrottleConfReload() {
confChanges := 10 confChanges := 10
for i := 0; i < confChanges; i++ { for i := range confChanges {
config.HTTP.Routers[fmt.Sprintf("routerHTTP%d", i)] = router config.HTTP.Routers[fmt.Sprintf("routerHTTP%d", i)] = router
data, err := json.Marshal(config) data, err := json.Marshal(config)
require.NoError(s.T(), err) require.NoError(s.T(), err)

View file

@ -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. // Verify load-balancing on root still works, and that we're getting an alternation between wsp2, and wsp4.
reachedServers := make(map[string]int) reachedServers := make(map[string]int)
for i := 0; i < 4; i++ { for range 4 {
resp, err := client.Do(rootReq) resp, err := client.Do(rootReq)
require.NoError(s.T(), err) 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. // Verify load-balancing on foo still works, and that we're getting wsp2, wsp2, wsp2, wsp2, etc.
want := `IP: ` + s.whoami2IP want := `IP: ` + s.whoami2IP
for i := 0; i < 4; i++ { for range 4 {
resp, err := client.Do(fooReq) resp, err := client.Do(fooReq)
require.NoError(s.T(), err) 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. // Verify load-balancing on bar still works, and that we're getting wsp2, wsp2, wsp2, wsp2, etc.
want = `IP: ` + s.whoami2IP want = `IP: ` + s.whoami2IP
for i := 0; i < 4; i++ { for range 4 {
resp, err := client.Do(barReq) resp, err := client.Do(barReq)
require.NoError(s.T(), err) require.NoError(s.T(), err)
@ -390,7 +390,7 @@ func (s *HealthCheckSuite) TestPropagate() {
try.Sleep(time.Second) try.Sleep(time.Second)
// Verify that everything is down, and that we get 503s everywhere. // 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) resp, err := client.Do(rootReq)
require.NoError(s.T(), err) require.NoError(s.T(), err)
assert.Equal(s.T(), http.StatusServiceUnavailable, resp.StatusCode) assert.Equal(s.T(), http.StatusServiceUnavailable, resp.StatusCode)
@ -417,7 +417,7 @@ func (s *HealthCheckSuite) TestPropagate() {
// Verify everything is up on root router. // Verify everything is up on root router.
reachedServers = make(map[string]int) reachedServers = make(map[string]int)
for i := 0; i < 4; i++ { for range 4 {
resp, err := client.Do(rootReq) resp, err := client.Do(rootReq)
require.NoError(s.T(), err) require.NoError(s.T(), err)
@ -452,7 +452,7 @@ func (s *HealthCheckSuite) TestPropagate() {
// Verify everything is up on foo router. // Verify everything is up on foo router.
reachedServers = make(map[string]int) reachedServers = make(map[string]int)
for i := 0; i < 4; i++ { for range 4 {
resp, err := client.Do(fooReq) resp, err := client.Do(fooReq)
require.NoError(s.T(), err) require.NoError(s.T(), err)
@ -487,7 +487,7 @@ func (s *HealthCheckSuite) TestPropagate() {
// Verify everything is up on bar router. // Verify everything is up on bar router.
reachedServers = make(map[string]int) reachedServers = make(map[string]int)
for i := 0; i < 4; i++ { for range 4 {
resp, err := client.Do(barReq) resp, err := client.Do(barReq)
require.NoError(s.T(), err) require.NoError(s.T(), err)

View file

@ -239,7 +239,7 @@ func (s *BaseSuite) createComposeProject(name string) {
} }
if containerConfig.Deploy.Replicas > 0 { 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) id = fmt.Sprintf("%s-%d", id, i+1)
con, err := s.createContainer(ctx, containerConfig, id, mounts) con, err := s.createContainer(ctx, containerConfig, id, mounts)
require.NoError(s.T(), err) require.NoError(s.T(), err)

View file

@ -307,7 +307,7 @@ func (s *SimpleSuite) TestMetricsPrometheusTwoRoutersOneService() {
require.NoError(s.T(), err) require.NoError(s.T(), err)
// adding a loop to test if metrics are not deleted // 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) request, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/metrics", nil)
require.NoError(s.T(), err) require.NoError(s.T(), err)
@ -771,7 +771,7 @@ func (s *SimpleSuite) TestWRR() {
require.NoError(s.T(), err) require.NoError(s.T(), err)
repartition := map[string]int{} 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) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil)
require.NoError(s.T(), err) 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) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil)
require.NoError(s.T(), err) require.NoError(s.T(), err)
for i := 0; i < 4; i++ { for range 4 {
response, err := http.DefaultClient.Do(req) response, err := http.DefaultClient.Do(req)
require.NoError(s.T(), err) require.NoError(s.T(), err)
assert.Equal(s.T(), http.StatusOK, response.StatusCode) 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) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil)
require.NoError(s.T(), err) require.NoError(s.T(), err)
for i := 0; i < 10; i++ { for range 10 {
response, err := http.DefaultClient.Do(req) response, err := http.DefaultClient.Do(req)
require.NoError(s.T(), err) require.NoError(s.T(), err)
assert.Equal(s.T(), http.StatusOK, response.StatusCode) 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)) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", bytes.NewBuffer(body20))
require.NoError(s.T(), err) require.NoError(s.T(), err)
req.Header.Set("Size", "20") req.Header.Set("Size", "20")
for i := 0; i < 10; i++ { for range 10 {
response, err := http.DefaultClient.Do(req) response, err := http.DefaultClient.Do(req)
require.NoError(s.T(), err) require.NoError(s.T(), err)
assert.Equal(s.T(), http.StatusOK, response.StatusCode) 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)) req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoamiWithMaxBody", bytes.NewBuffer(body5))
require.NoError(s.T(), err) require.NoError(s.T(), err)
req.Header.Set("Size", "5") req.Header.Set("Size", "5")
for i := 0; i < 10; i++ { for range 10 {
response, err := http.DefaultClient.Do(req) response, err := http.DefaultClient.Do(req)
require.NoError(s.T(), err) require.NoError(s.T(), err)
assert.Equal(s.T(), http.StatusOK, response.StatusCode) 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)) req, err = http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoamiWithMaxBody", bytes.NewBuffer(body20))
require.NoError(s.T(), err) require.NoError(s.T(), err)
req.Header.Set("Size", "20") req.Header.Set("Size", "20")
for i := 0; i < 10; i++ { for range 10 {
response, err := http.DefaultClient.Do(req) response, err := http.DefaultClient.Do(req)
require.NoError(s.T(), err) require.NoError(s.T(), err)
assert.Equal(s.T(), http.StatusOK, response.StatusCode) 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")) 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) 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) req, err := http.NewRequest(http.MethodGet, "http://127.0.0.1:8000/whoami", nil)
require.NoError(s.T(), err) require.NoError(s.T(), err)

View file

@ -263,7 +263,7 @@ func (s *TCPSuite) TestWRR() {
require.NoError(s.T(), err) require.NoError(s.T(), err)
call := map[string]int{} call := map[string]int{}
for i := 0; i < 4; i++ { for range 4 {
// Traefik passes through, termination handled by whoami-b or whoami-bb // Traefik passes through, termination handled by whoami-b or whoami-bb
out, err := guessWhoTLSPassthrough("127.0.0.1:8093", "whoami-b.test") out, err := guessWhoTLSPassthrough("127.0.0.1:8093", "whoami-b.test")
require.NoError(s.T(), err) require.NoError(s.T(), err)

View file

@ -82,7 +82,7 @@ func (s *UDPSuite) TestWRR() {
stop := make(chan struct{}) stop := make(chan struct{})
go func() { go func() {
call := map[string]int{} call := map[string]int{}
for i := 0; i < 8; i++ { for range 8 {
out, err := guessWhoUDP("127.0.0.1:8093") out, err := guessWhoUDP("127.0.0.1:8093")
require.NoError(s.T(), err) require.NoError(s.T(), err)
switch { switch {

View file

@ -223,7 +223,7 @@ func clean(element any) {
valueSvcRoot := valSvcs.MapIndex(key).Elem() valueSvcRoot := valSvcs.MapIndex(key).Elem()
var svcFieldNames []string var svcFieldNames []string
for i := 0; i < valueSvcRoot.NumField(); i++ { for i := range valueSvcRoot.NumField() {
svcFieldNames = append(svcFieldNames, valueSvcRoot.Type().Field(i).Name) svcFieldNames = append(svcFieldNames, valueSvcRoot.Type().Field(i).Name)
} }

View file

@ -4,6 +4,7 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"net/url" "net/url"
"slices"
"strconv" "strconv"
"strings" "strings"
) )
@ -50,13 +51,9 @@ func (c *searchCriterion) searchIn(values ...string) bool {
return true return true
} }
for _, v := range values { return slices.ContainsFunc(values, func(v string) bool {
if strings.Contains(strings.ToLower(v), strings.ToLower(c.Search)) { return strings.Contains(strings.ToLower(v), strings.ToLower(c.Search))
return true })
}
}
return false
} }
func pagination(request *http.Request, max int) (pageInfo, error) { func pagination(request *http.Request, max int) (pageInfo, error) {

View file

@ -149,7 +149,7 @@ func getProviderName(id string) string {
func extractType(element interface{}) string { func extractType(element interface{}) string {
v := reflect.ValueOf(element).Elem() v := reflect.ValueOf(element).Elem()
for i := 0; i < v.NumField(); i++ { for i := range v.NumField() {
field := v.Field(i) field := v.Field(i)
if field.Kind() == reflect.Map && field.Type().Elem() == reflect.TypeOf(dynamic.PluginConf{}) { if field.Kind() == reflect.Map && field.Type().Elem() == reflect.TypeOf(dynamic.PluginConf{}) {

View file

@ -256,7 +256,7 @@ func TestHandler_EntryPoints(t *testing.T) {
func generateEntryPoints(nb int) map[string]*static.EntryPoint { func generateEntryPoints(nb int) map[string]*static.EntryPoint {
eps := make(map[string]*static.EntryPoint, nb) 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{ eps[fmt.Sprintf("ep%2d", i)] = &static.EntryPoint{
Address: ":" + strconv.Itoa(i), Address: ":" + strconv.Itoa(i),
} }

View file

@ -972,7 +972,7 @@ func TestHandler_HTTP(t *testing.T) {
func generateHTTPRouters(nbRouters int) map[string]*runtime.RouterInfo { func generateHTTPRouters(nbRouters int) map[string]*runtime.RouterInfo {
routers := make(map[string]*runtime.RouterInfo, nbRouters) 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{ routers[fmt.Sprintf("bar%2d@myprovider", i)] = &runtime.RouterInfo{
Router: &dynamic.Router{ Router: &dynamic.Router{
EntryPoints: []string{"web"}, EntryPoints: []string{"web"},

View file

@ -226,7 +226,7 @@ func getProviders(conf static.Configuration) []string {
var providers []string var providers []string
v := reflect.ValueOf(conf.Providers).Elem() v := reflect.ValueOf(conf.Providers).Elem()
for i := 0; i < v.NumField(); i++ { for i := range v.NumField() {
field := v.Field(i) field := v.Field(i)
if field.Kind() == reflect.Ptr && field.Elem().Kind() == reflect.Struct { if field.Kind() == reflect.Ptr && field.Elem().Kind() == reflect.Struct {
if !field.IsNil() { if !field.IsNil() {
@ -256,7 +256,7 @@ func getMetrics(conf static.Configuration) string {
} }
v := reflect.ValueOf(conf.Metrics).Elem() v := reflect.ValueOf(conf.Metrics).Elem()
for i := 0; i < v.NumField(); i++ { for i := range v.NumField() {
field := v.Field(i) field := v.Field(i)
if field.Kind() == reflect.Ptr && field.Elem().Kind() == reflect.Struct { if field.Kind() == reflect.Ptr && field.Elem().Kind() == reflect.Struct {
if !field.IsNil() { if !field.IsNil() {
@ -274,7 +274,7 @@ func getTracing(conf static.Configuration) string {
} }
v := reflect.ValueOf(conf.Tracing).Elem() v := reflect.ValueOf(conf.Tracing).Elem()
for i := 0; i < v.NumField(); i++ { for i := range v.NumField() {
field := v.Field(i) field := v.Field(i)
if field.Kind() == reflect.Ptr && field.Elem().Kind() == reflect.Struct { if field.Kind() == reflect.Ptr && field.Elem().Kind() == reflect.Struct {
if !field.IsNil() { if !field.IsNil() {

View file

@ -93,7 +93,7 @@ func setTyped(field reflect.Value, i interface{}) {
func setMap(field reflect.Value) error { func setMap(field reflect.Value) error {
field.Set(reflect.MakeMap(field.Type())) field.Set(reflect.MakeMap(field.Type()))
for i := 0; i < mapItemNumber; i++ { for i := range mapItemNumber {
baseKeyName := makeKeyName(field.Type().Elem()) baseKeyName := makeKeyName(field.Type().Elem())
key := reflect.ValueOf(fmt.Sprintf("%s%d", baseKeyName, i)) 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 { func setStruct(field reflect.Value) error {
for i := 0; i < field.NumField(); i++ { for i := range field.NumField() {
fld := field.Field(i) fld := field.Field(i)
stFld := field.Type().Field(i) stFld := field.Type().Field(i)
@ -142,7 +142,7 @@ func setStruct(field reflect.Value) error {
func setSlice(field reflect.Value) error { func setSlice(field reflect.Value) error {
field.Set(reflect.MakeSlice(field.Type(), sliceItemNumber, sliceItemNumber)) 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 { if err := fill(field.Index(j)); err != nil {
return err return err
} }

View file

@ -55,7 +55,7 @@ func getFieldNames(rootName string, rootType reflect.Type) []string {
return nil return nil
} }
for i := 0; i < rootType.NumField(); i++ { for i := range rootType.NumField() {
field := rootType.Field(i) field := rootType.Field(i)
if !parser.IsExported(field) { if !parser.IsExported(field) {

View file

@ -74,7 +74,7 @@ func TestLogRotation(t *testing.T) {
halfDone := make(chan bool) halfDone := make(chan bool)
writeDone := make(chan bool) writeDone := make(chan bool)
go func() { go func() {
for i := 0; i < iterations; i++ { for i := range iterations {
handler.ServeHTTP(recorder, req) handler.ServeHTTP(recorder, req)
if i == iterations/2 { if i == iterations/2 {
halfDone <- true halfDone <- true

View file

@ -149,7 +149,7 @@ func BenchmarkCapture(b *testing.B) {
b.ReportAllocs() b.ReportAllocs()
b.SetBytes(int64(test.size)) b.SetBytes(int64(test.size))
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for range b.N {
runBenchmark(b, test.size, req, handlers) 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 { func generateBytes(length int) []byte {
var value []byte var value []byte
for i := 0; i < length; i++ { for i := range length {
value = append(value, 0x61+byte(i%26)) value = append(value, 0x61+byte(i%26))
} }
return value return value

View file

@ -499,7 +499,7 @@ func BenchmarkCompress(b *testing.B) {
} }
b.ResetTimer() b.ResetTimer()
for i := 0; i < b.N; i++ { for range b.N {
runBenchmark(b, req, handler) runBenchmark(b, req, handler)
} }
}) })
@ -520,7 +520,7 @@ func runBenchmark(b *testing.B, req *http.Request, handler http.Handler) {
func generateBytes(length int) []byte { func generateBytes(length int) []byte {
var value []byte var value []byte
for i := 0; i < length; i++ { for i := range length {
value = append(value, 0x61+byte(i)) value = append(value, 0x61+byte(i))
} }
return value return value

View file

@ -58,7 +58,7 @@ func (lb *healthCheckLoadBalancer) ServeHTTP(w http.ResponseWriter, r *http.Requ
func (lb *healthCheckLoadBalancer) Servers() []*url.URL { func (lb *healthCheckLoadBalancer) Servers() []*url.URL {
servers := make([]*url.URL, lb.amountServer) servers := make([]*url.URL, lb.amountServer)
for i := 0; i < lb.amountServer; i++ { for range lb.amountServer {
servers = append(servers, testhelpers.MustParseURL("http://localhost")) servers = append(servers, testhelpers.MustParseURL("http://localhost"))
} }
return servers return servers

View file

@ -3,6 +3,7 @@ package metrics
import ( import (
"context" "context"
"net/http" "net/http"
"slices"
"strconv" "strconv"
"strings" "strings"
"time" "time"
@ -175,12 +176,10 @@ func isSSERequest(req *http.Request) bool {
func containsHeader(req *http.Request, name, value string) bool { func containsHeader(req *http.Request, name, value string) bool {
items := strings.Split(req.Header.Get(name), ",") items := strings.Split(req.Header.Get(name), ",")
for _, item := range items {
if value == strings.ToLower(strings.TrimSpace(item)) { return slices.ContainsFunc(items, func(item string) bool {
return true return value == strings.ToLower(strings.TrimSpace(item))
} })
}
return false
} }
// getMethod returns the request's method. // getMethod returns the request's method.

View file

@ -49,7 +49,7 @@ func (hr *Resolver) CNAMEFlatten(ctx context.Context, host string) string {
logger := log.FromContext(ctx) logger := log.FromContext(ctx)
cacheDuration := 0 * time.Second cacheDuration := 0 * time.Second
for depth := 0; depth < hr.ResolvDepth; depth++ { for depth := range hr.ResolvDepth {
resolv, err := cnameResolve(ctx, request, hr.ResolvConfig) resolv, err := cnameResolve(ctx, request, hr.ResolvConfig)
if err != nil { if err != nil {
logger.Error(err) logger.Error(err)

View file

@ -203,7 +203,7 @@ func TestMultipleRetriesShouldNotLooseHeaders(t *testing.T) {
} }
// Validate that we don't have headers from previous attempts // 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) headerName := fmt.Sprintf("X-Foo-Test-%d", i)
headerValue = responseRecorder.Header().Get("headerName") headerValue = responseRecorder.Header().Get("headerName")
if headerValue != "" { if headerValue != "" {

View file

@ -324,11 +324,7 @@ func addRuleOnRoute(route *mux.Route, rule *rules.Tree) error {
// IsASCII checks if the given string contains only ASCII characters. // IsASCII checks if the given string contains only ASCII characters.
func IsASCII(s string) bool { func IsASCII(s string) bool {
for i := 0; i < len(s); i++ { return !strings.ContainsFunc(s, func(r rune) bool {
if s[i] >= utf8.RuneSelf { return r >= utf8.RuneSelf
return false })
}
}
return true
} }

View file

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"net" "net"
"regexp" "regexp"
"slices"
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
@ -301,15 +302,9 @@ func alpn(tree *matchersTree, protos ...string) error {
} }
tree.matcher = func(meta ConnData) bool { tree.matcher = func(meta ConnData) bool {
for _, proto := range meta.alpnProtos { return slices.ContainsFunc(meta.alpnProtos, func(proto string) bool {
for _, filter := range protos { return slices.Contains(protos, proto)
if proto == filter { })
return true
}
}
}
return false
} }
return nil return nil
@ -469,7 +464,7 @@ func varGroupName(idx int) string {
func braceIndices(s string) ([]int, error) { func braceIndices(s string) ([]int, error) {
var level, idx int var level, idx int
var idxs []int var idxs []int
for i := 0; i < len(s); i++ { for i := range len(s) {
switch s[i] { switch s[i] {
case '{': case '{':
if level++; level == 1 { if level++; level == 1 {

View file

@ -2,6 +2,7 @@ package acme
import ( import (
"fmt" "fmt"
"slices"
"sync" "sync"
"time" "time"
@ -118,7 +119,7 @@ func (c *ChallengeTLSALPN) ListenConfiguration(conf dynamic.Configuration) {
c.muChans.Lock() c.muChans.Lock()
for _, certificate := range conf.TLS.Certificates { for _, certificate := range conf.TLS.Certificates {
if !containsACMETLS1(certificate.Stores) { if !slices.Contains(certificate.Stores, tlsalpn01.ACMETLS1Protocol) {
continue continue
} }
@ -161,13 +162,3 @@ func createMessage(certs map[string]*Certificate) dynamic.Message {
return conf return conf
} }
func containsACMETLS1(stores []string) bool {
for _, store := range stores {
if store == tlsalpn01.ACMETLS1Protocol {
return true
}
}
return false
}

View file

@ -424,7 +424,7 @@ func (p *Provider) watchNewDomains(ctx context.Context) {
if len(route.TLS.Domains) > 0 { if len(route.TLS.Domains) > 0 {
domains := deleteUnnecessaryDomains(ctxRouter, route.TLS.Domains) domains := deleteUnnecessaryDomains(ctxRouter, route.TLS.Domains)
for i := 0; i < len(domains); i++ { for i := range len(domains) {
domain := domains[i] domain := domains[i]
safe.Go(func() { safe.Go(func() {
dom, cert, err := p.resolveCertificate(ctx, domain, traefiktls.DefaultTLSStoreName) 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 { if len(route.TLS.Domains) > 0 {
domains := deleteUnnecessaryDomains(ctxRouter, route.TLS.Domains) domains := deleteUnnecessaryDomains(ctxRouter, route.TLS.Domains)
for i := 0; i < len(domains); i++ { for i := range len(domains) {
domain := domains[i] domain := domains[i]
safe.Go(func() { safe.Go(func() {
dom, cert, err := p.resolveCertificate(ctx, domain, traefiktls.DefaultTLSStoreName) dom, cert, err := p.resolveCertificate(ctx, domain, traefiktls.DefaultTLSStoreName)

View file

@ -3,6 +3,7 @@ package constraints
import ( import (
"errors" "errors"
"regexp" "regexp"
"slices"
"github.com/vulcand/predicate" "github.com/vulcand/predicate"
) )
@ -47,12 +48,7 @@ func MatchTags(tags []string, expr string) (bool, error) {
func tagFn(name string) constraintTagFunc { func tagFn(name string) constraintTagFunc {
return func(tags []string) bool { return func(tags []string) bool {
for _, tag := range tags { return slices.Contains(tags, name)
if tag == name {
return true
}
}
return false
} }
} }
@ -63,13 +59,9 @@ func tagRegexFn(expr string) constraintTagFunc {
return false return false
} }
for _, tag := range tags { return slices.ContainsFunc(tags, func(tag string) bool {
if exp.MatchString(tag) { return exp.MatchString(tag)
return true })
}
}
return false
} }
} }

View file

@ -274,7 +274,7 @@ func TestDefaultRule(t *testing.T) {
err := p.Init() err := p.Init()
require.NoError(t, err) require.NoError(t, err)
for i := 0; i < len(test.items); i++ { for i := range len(test.items) {
var err error var err error
test.items[i].ExtraConf, err = p.getExtraConf(test.items[i].Labels) test.items[i].ExtraConf, err = p.getExtraConf(test.items[i].Labels)
require.NoError(t, err) require.NoError(t, err)
@ -2956,7 +2956,7 @@ func Test_buildConfiguration(t *testing.T) {
err := p.Init() err := p.Init()
require.NoError(t, err) require.NoError(t, err)
for i := 0; i < len(test.items); i++ { for i := range len(test.items) {
var err error var err error
test.items[i].ExtraConf, err = p.getExtraConf(test.items[i].Labels) test.items[i].ExtraConf, err = p.getExtraConf(test.items[i].Labels)
require.NoError(t, err) require.NoError(t, err)

View file

@ -361,7 +361,7 @@ func TestDefaultRule(t *testing.T) {
err := p.Init() err := p.Init()
require.NoError(t, err) require.NoError(t, err)
for i := 0; i < len(test.containers); i++ { for i := range len(test.containers) {
var err error var err error
test.containers[i].ExtraConf, err = p.getConfiguration(test.containers[i]) test.containers[i].ExtraConf, err = p.getConfiguration(test.containers[i])
require.NoError(t, err) require.NoError(t, err)
@ -3257,7 +3257,7 @@ func Test_buildConfiguration(t *testing.T) {
err := p.Init() err := p.Init()
require.NoError(t, err) require.NoError(t, err)
for i := 0; i < len(test.containers); i++ { for i := range len(test.containers) {
var err error var err error
test.containers[i].ExtraConf, err = p.getConfiguration(test.containers[i]) test.containers[i].ExtraConf, err = p.getConfiguration(test.containers[i])
require.NoError(t, err) require.NoError(t, err)

View file

@ -333,7 +333,7 @@ func TestDefaultRule(t *testing.T) {
err := p.Init() err := p.Init()
require.NoError(t, err) require.NoError(t, err)
for i := 0; i < len(test.instances); i++ { for i := range len(test.instances) {
var err error var err error
test.instances[i].ExtraConf, err = p.getConfiguration(test.instances[i]) test.instances[i].ExtraConf, err = p.getConfiguration(test.instances[i])
require.NoError(t, err) require.NoError(t, err)
@ -2863,7 +2863,7 @@ func Test_buildConfiguration(t *testing.T) {
err := p.Init() err := p.Init()
require.NoError(t, err) require.NoError(t, err)
for i := 0; i < len(test.containers); i++ { for i := range len(test.containers) {
var err error var err error
test.containers[i].ExtraConf, err = p.getConfiguration(test.containers[i]) test.containers[i].ExtraConf, err = p.getConfiguration(test.containers[i])
require.NoError(t, err) require.NoError(t, err)

View file

@ -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) { 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) miInstances := make(map[string]*ssm.InstanceInformation)
var containerInstancesArns []*string var containerInstancesArns []*string
@ -419,7 +419,7 @@ func (p *Provider) lookupMiInstances(ctx context.Context, client *awsClient, clu
} }
for _, container := range resp.ContainerInstances { 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 // Disallow EC2 Instance IDs
// This prevents considering EC2 instances in ECS // 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 { if len(page.InstanceInformationList) > 0 {
for _, i := range page.InstanceInformationList { for _, i := range page.InstanceInformationList {
if i.InstanceId != nil { 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) { 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) ec2Instances := make(map[string]*ec2.Instance)
var containerInstancesArns []*string var containerInstancesArns []*string
@ -485,7 +485,7 @@ func (p *Provider) lookupEc2Instances(ctx context.Context, client *awsClient, cl
} }
for _, container := range resp.ContainerInstances { 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-* // Disallow Instance IDs of the form mi-*
// This prevents considering external instances in ECS Anywhere setups // This prevents considering external instances in ECS Anywhere setups
// and getting InvalidInstanceID.Malformed error when calling the describe-instances endpoint. // 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 _, r := range page.Reservations {
for _, i := range r.Instances { for _, i := range r.Instances {
if i.InstanceId != nil { if i.InstanceId != nil {
ec2Instances[instanceIds[aws.StringValue(i.InstanceId)]] = i ec2Instances[instanceIDs[aws.StringValue(i.InstanceId)]] = i
} }
} }
} }

View file

@ -73,7 +73,7 @@ func TestChunkIDs(t *testing.T) {
t.Parallel() t.Parallel()
var IDs []*string var IDs []*string
for v := 0; v < test.count; v++ { for range test.count {
IDs = append(IDs, aws.String("a")) IDs = append(IDs, aws.String("a"))
} }

View file

@ -6,6 +6,7 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
"slices"
"time" "time"
"github.com/traefik/traefik/v2/pkg/log" "github.com/traefik/traefik/v2/pkg/log"
@ -452,12 +453,8 @@ func (c *clientWrapper) isWatchedNamespace(ns string) bool {
if c.isNamespaceAll { if c.isNamespaceAll {
return true return true
} }
for _, watchedNamespace := range c.watchedNamespaces {
if watchedNamespace == ns { return slices.Contains(c.watchedNamespaces, ns)
return true
}
}
return false
} }
// translateNotFoundError will translate a "not found" error to a boolean return // translateNotFoundError will translate a "not found" error to a boolean return

View file

@ -5,6 +5,7 @@ import (
"errors" "errors"
"fmt" "fmt"
"os" "os"
"slices"
"time" "time"
"github.com/traefik/traefik/v2/pkg/log" "github.com/traefik/traefik/v2/pkg/log"
@ -548,10 +549,6 @@ func (c *clientWrapper) isWatchedNamespace(ns string) bool {
if c.isNamespaceAll { if c.isNamespaceAll {
return true return true
} }
for _, watchedNamespace := range c.watchedNamespaces {
if watchedNamespace == ns { return slices.Contains(c.watchedNamespaces, ns)
return true
}
}
return false
} }

View file

@ -7,6 +7,7 @@ import (
"os" "os"
"path/filepath" "path/filepath"
"runtime" "runtime"
"slices"
"time" "time"
"github.com/hashicorp/go-version" "github.com/hashicorp/go-version"
@ -538,12 +539,8 @@ func (c *clientWrapper) isWatchedNamespace(ns string) bool {
if c.isNamespaceAll { if c.isNamespaceAll {
return true return true
} }
for _, watchedNamespace := range c.watchedNamespaces {
if watchedNamespace == ns { return slices.Contains(c.watchedNamespaces, ns)
return true
}
}
return false
} }
// IngressClass objects are supported since Kubernetes v1.18. // IngressClass objects are supported since Kubernetes v1.18.

View file

@ -8,6 +8,7 @@ import (
"math" "math"
"net" "net"
"os" "os"
"slices"
"sort" "sort"
"strconv" "strconv"
"strings" "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 { func (p *Provider) shouldProcessIngress(ingress *netv1.Ingress, ingressClasses []*netv1.IngressClass) bool {
// configuration through the new kubernetes ingressClass // configuration through the new kubernetes ingressClass
if ingress.Spec.IngressClassName != nil { if ingress.Spec.IngressClassName != nil {
for _, ic := range ingressClasses { return slices.ContainsFunc(ingressClasses, func(ic *netv1.IngressClass) bool {
if *ingress.Spec.IngressClassName == ic.ObjectMeta.Name { return *ingress.Spec.IngressClassName == ic.ObjectMeta.Name
return true })
}
}
return false
} }
return p.IngressClass == ingress.Annotations[annotationKubernetesIngressClass] || return p.IngressClass == ingress.Annotations[annotationKubernetesIngressClass] ||

View file

@ -1146,7 +1146,7 @@ func Test_buildConfiguration(t *testing.T) {
err := p.Init() err := p.Init()
require.NoError(t, err) require.NoError(t, err)
for i := 0; i < len(test.containers); i++ { for i := range len(test.containers) {
var err error var err error
test.containers[i].ExtraConf, err = p.getConfiguration(test.containers[i]) test.containers[i].ExtraConf, err = p.getConfiguration(test.containers[i])
require.NoError(t, err) require.NoError(t, err)

View file

@ -83,7 +83,7 @@ func doOnStruct(field reflect.Value, tag string, redactByDefault bool) error {
} }
} }
case reflect.Struct: case reflect.Struct:
for i := 0; i < field.NumField(); i++ { for i := range field.NumField() {
fld := field.Field(i) fld := field.Field(i)
stField := field.Type().Field(i) stField := field.Type().Field(i)
if !isExported(stField) { if !isExported(stField) {
@ -138,7 +138,7 @@ func doOnStruct(field reflect.Value, tag string, redactByDefault bool) error {
} }
} }
case reflect.Slice: 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 { if err := doOnStruct(field.Index(j), tag, redactByDefault); err != nil {
return err return err
} }
@ -179,7 +179,7 @@ func reset(field reflect.Value, name string) error {
switch field.Type().Elem().Kind() { switch field.Type().Elem().Kind() {
case reflect.String: case reflect.String:
slice := reflect.MakeSlice(field.Type(), field.Len(), field.Len()) 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) slice.Index(j).SetString(maskShort)
} }
field.Set(slice) field.Set(slice)

View file

@ -1,6 +1,8 @@
package server package server
import ( import (
"slices"
"github.com/go-acme/lego/v4/challenge/tlsalpn01" "github.com/go-acme/lego/v4/challenge/tlsalpn01"
"github.com/traefik/traefik/v2/pkg/config/dynamic" "github.com/traefik/traefik/v2/pkg/config/dynamic"
"github.com/traefik/traefik/v2/pkg/log" "github.com/traefik/traefik/v2/pkg/log"
@ -91,7 +93,7 @@ func mergeConfiguration(configurations dynamic.Configurations, defaultEntryPoint
if configuration.TLS != nil { if configuration.TLS != nil {
for _, cert := range configuration.TLS.Certificates { for _, cert := range configuration.TLS.Certificates {
if containsACMETLS1(cert.Stores) && pvd != "tlsalpn.acme" { if slices.Contains(cert.Stores, tlsalpn01.ACMETLS1Protocol) && pvd != "tlsalpn.acme" {
continue continue
} }
@ -179,13 +181,3 @@ func applyModel(cfg dynamic.Configuration) dynamic.Configuration {
return cfg return cfg
} }
func containsACMETLS1(stores []string) bool {
for _, store := range stores {
if store == tlsalpn01.ACMETLS1Protocol {
return true
}
}
return false
}

View file

@ -305,7 +305,7 @@ func TestListenProvidersThrottleProviderConfigReload(t *testing.T) {
throttleDuration: 30 * time.Millisecond, throttleDuration: 30 * time.Millisecond,
} }
for i := 0; i < 5; i++ { for i := range 5 {
pvd.messages = append(pvd.messages, dynamic.Message{ pvd.messages = append(pvd.messages, dynamic.Message{
ProviderName: "mock", ProviderName: "mock",
Configuration: &dynamic.Configuration{ Configuration: &dynamic.Configuration{

View file

@ -6,6 +6,7 @@ import (
"fmt" "fmt"
"net/http" "net/http"
"reflect" "reflect"
"slices"
"strings" "strings"
"github.com/containous/alice" "github.com/containous/alice"
@ -97,7 +98,7 @@ func checkRecursion(ctx context.Context, middlewareName string) (context.Context
if !ok { if !ok {
currentStack = []string{} 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 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 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 return tracing.Wrap(ctx, middleware), nil
} }
func inSlice(element string, stack []string) bool {
for _, value := range stack {
if value == element {
return true
}
}
return false
}

View file

@ -3,6 +3,7 @@ package tcpmiddleware
import ( import (
"context" "context"
"fmt" "fmt"
"slices"
"strings" "strings"
"github.com/traefik/traefik/v2/pkg/config/runtime" "github.com/traefik/traefik/v2/pkg/config/runtime"
@ -74,7 +75,7 @@ func checkRecursion(ctx context.Context, middlewareName string) (context.Context
currentStack = []string{} 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 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 return middleware, nil
} }
func inSlice(element string, stack []string) bool {
for _, value := range stack {
if value == element {
return true
}
}
return false
}

View file

@ -945,7 +945,7 @@ func BenchmarkRouterServe(b *testing.B) {
reqHost := requestdecorator.New(nil) reqHost := requestdecorator.New(nil)
b.ReportAllocs() b.ReportAllocs()
for i := 0; i < b.N; i++ { for range b.N {
reqHost.ServeHTTP(w, req, handlers["web"].ServeHTTP) reqHost.ServeHTTP(w, req, handlers["web"].ServeHTTP)
} }
} }
@ -980,7 +980,7 @@ func BenchmarkService(b *testing.B) {
handler, _ := serviceManager.BuildHTTP(context.Background(), "foo-service") handler, _ := serviceManager.BuildHTTP(context.Background(), "foo-service")
b.ReportAllocs() b.ReportAllocs()
for i := 0; i < b.N; i++ { for range b.N {
handler.ServeHTTP(w, req) handler.ServeHTTP(w, req)
} }
} }

View file

@ -112,7 +112,7 @@ func testShutdown(t *testing.T, router *tcprouter.Router) {
// but technically also as early as the Shutdown has closed the listener, // but technically also as early as the Shutdown has closed the listener,
// i.e. during the shutdown and before the gracetime is over. // i.e. during the shutdown and before the gracetime is over.
var testOk bool var testOk bool
for i := 0; i < 10; i++ { for range 10 {
loopConn, err := net.Dial("tcp", epAddr) loopConn, err := net.Dial("tcp", epAddr)
if err == nil { if err == nil {
loopConn.Close() loopConn.Close()
@ -141,7 +141,7 @@ func startEntrypoint(entryPoint *TCPEntryPoint, router *tcprouter.Router) (net.C
entryPoint.SwitchRouter(router) entryPoint.SwitchRouter(router)
for i := 0; i < 10; i++ { for range 10 {
conn, err := net.Dial("tcp", entryPoint.listener.Addr().String()) conn, err := net.Dial("tcp", entryPoint.listener.Addr().String())
if err != nil { if err != nil {
time.Sleep(100 * time.Millisecond) time.Sleep(100 * time.Millisecond)

View file

@ -32,7 +32,7 @@ func TestMirroringOn100(t *testing.T) {
}), 50) }), 50)
assert.NoError(t, err) assert.NoError(t, err)
for i := 0; i < 100; i++ { for range 100 {
mirror.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) mirror.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil))
} }
@ -61,7 +61,7 @@ func TestMirroringOn10(t *testing.T) {
}), 50) }), 50)
assert.NoError(t, err) assert.NoError(t, err)
for i := 0; i < 10; i++ { for range 10 {
mirror.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil)) mirror.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/", nil))
} }
@ -156,7 +156,7 @@ func TestMirroringWithBody(t *testing.T) {
mirror := New(handler, pool, defaultMaxBodySize, nil) 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) { err := mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
assert.NotNil(t, r.Body) assert.NotNil(t, r.Body)
bb, err := io.ReadAll(r.Body) bb, err := io.ReadAll(r.Body)

View file

@ -40,7 +40,7 @@ func TestBalancer(t *testing.T) {
}), Int(1)) }), Int(1))
recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} 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)) 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)) balancer.AddService("second", http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {}), Int(0))
recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} 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)) 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) balancer.SetStatus(context.WithValue(context.Background(), serviceName, "parent"), "second", false)
recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} 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)) 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) balancer.SetStatus(context.WithValue(context.Background(), serviceName, "parent"), "second", false)
recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} 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)) balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
} }
assert.Equal(t, 3, recorder.save["first"]) assert.Equal(t, 3, recorder.save["first"])
balancer.SetStatus(context.WithValue(context.Background(), serviceName, "parent"), "second", true) balancer.SetStatus(context.WithValue(context.Background(), serviceName, "parent"), "second", true)
recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} 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)) balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
} }
assert.Equal(t, 1, recorder.save["first"]) 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{}} 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)) topBalancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
} }
assert.Equal(t, 2, recorder.save["first"]) 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. // fourth gets downed, but balancer2 still up since third is still up.
balancer2.SetStatus(context.WithValue(context.Background(), serviceName, "top"), "fourth", false) balancer2.SetStatus(context.WithValue(context.Background(), serviceName, "top"), "fourth", false)
recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} 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)) topBalancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
} }
assert.Equal(t, 2, recorder.save["first"]) assert.Equal(t, 2, recorder.save["first"])
@ -211,7 +211,7 @@ func TestBalancerPropagate(t *testing.T) {
// down as well for topBalancer. // down as well for topBalancer.
balancer2.SetStatus(context.WithValue(context.Background(), serviceName, "top"), "third", false) balancer2.SetStatus(context.WithValue(context.Background(), serviceName, "top"), "third", false)
recorder = &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} 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)) topBalancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
} }
assert.Equal(t, 4, recorder.save["first"]) 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{}} recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}}
req := httptest.NewRequest(http.MethodGet, "/", nil) req := httptest.NewRequest(http.MethodGet, "/", nil)
for i := 0; i < 3; i++ { for range 3 {
for _, cookie := range recorder.Result().Cookies() { for _, cookie := range recorder.Result().Cookies() {
assert.NotContains(t, "test=first", cookie.Value) assert.NotContains(t, "test=first", cookie.Value)
assert.NotContains(t, "test=second", 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 := httptest.NewRequest(http.MethodGet, "/", nil)
req.AddCookie(&http.Cookie{Name: "test", Value: "second"}) req.AddCookie(&http.Cookie{Name: "test", Value: "second"})
for i := 0; i < 3; i++ { for range 3 {
recorder.ResponseRecorder = httptest.NewRecorder() recorder.ResponseRecorder = httptest.NewRecorder()
balancer.ServeHTTP(recorder, req) balancer.ServeHTTP(recorder, req)
@ -313,7 +313,7 @@ func TestBalancerBias(t *testing.T) {
recorder := &responseRecorder{ResponseRecorder: httptest.NewRecorder(), save: map[string]int{}} 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)) balancer.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/", nil))
} }

View file

@ -31,7 +31,7 @@ func BenchmarkProxy(b *testing.B) {
handler, _ := buildProxy(Bool(false), nil, &staticTransport{res}, pool) handler, _ := buildProxy(Bool(false), nil, &staticTransport{res}, pool)
b.ReportAllocs() b.ReportAllocs()
for i := 0; i < b.N; i++ { for range b.N {
handler.ServeHTTP(w, req) handler.ServeHTTP(w, req)
} }
} }

View file

@ -9,6 +9,7 @@ import (
"net" "net"
"net/http" "net/http"
"reflect" "reflect"
"slices"
"strings" "strings"
"sync" "sync"
"time" "time"
@ -210,12 +211,9 @@ func (k *KerberosRoundTripper) RoundTrip(request *http.Request) (*http.Response,
} }
func containsNTLMorNegotiate(h []string) bool { func containsNTLMorNegotiate(h []string) bool {
for _, s := range h { return slices.ContainsFunc(h, func(s string) bool {
if strings.HasPrefix(s, "NTLM") || strings.HasPrefix(s, "Negotiate") { return strings.HasPrefix(s, "NTLM") || strings.HasPrefix(s, "Negotiate")
return true })
}
}
return false
} }
func createRootCACertPool(rootCAs []traefiktls.FileOrContent) *x509.CertPool { func createRootCACertPool(rootCAs []traefiktls.FileOrContent) *x509.CertPool {

View file

@ -139,7 +139,7 @@ func TestKeepConnectionWhenSameConfiguration(t *testing.T) {
}, },
} }
for i := 0; i < 10; i++ { for range 10 {
rtManager.Update(dynamicConf) rtManager.Update(dynamicConf)
tr, err := rtManager.Get("test") tr, err := rtManager.Get("test")

View file

@ -85,7 +85,7 @@ func (m *Manager) BuildHTTP(rootCtx context.Context, serviceName string) (http.H
value := reflect.ValueOf(*conf.Service) value := reflect.ValueOf(*conf.Service)
var count int var count int
for i := 0; i < value.NumField(); i++ { for i := range value.NumField() {
if !value.Field(i).IsNil() { if !value.Field(i).IsNil() {
count++ count++
} }

View file

@ -135,7 +135,7 @@ func TestLoadBalancing(t *testing.T) {
} }
conn := &fakeConn{writeCall: make(map[string]int)} conn := &fakeConn{writeCall: make(map[string]int)}
for i := 0; i < test.totalCall; i++ { for range test.totalCall {
balancer.ServeTCP(conn) balancer.ServeTCP(conn)
} }

View file

@ -6,6 +6,7 @@ import (
"crypto/x509" "crypto/x509"
"errors" "errors"
"fmt" "fmt"
"slices"
"strings" "strings"
"sync" "sync"
@ -181,7 +182,7 @@ func (m *Manager) Get(storeName, configName string) (*tls.Config, error) {
tlsConfig.GetCertificate = func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) { tlsConfig.GetCertificate = func(clientHello *tls.ClientHelloInfo) (*tls.Certificate, error) {
domainToCheck := types.CanonicalDomain(clientHello.ServerName) domainToCheck := types.CanonicalDomain(clientHello.ServerName)
if isACMETLS(clientHello) { if slices.Contains(clientHello.SupportedProtos, tlsalpn01.ACMETLS1Protocol) {
certificate := acmeTLSStore.GetBestCertificate(clientHello) certificate := acmeTLSStore.GetBestCertificate(clientHello)
if certificate == nil { if certificate == nil {
log.WithoutContext().Debugf("TLS: no certificate for TLSALPN challenge: %s", domainToCheck) log.WithoutContext().Debugf("TLS: no certificate for TLSALPN challenge: %s", domainToCheck)
@ -419,13 +420,3 @@ func buildDefaultCertificate(defaultCertificate *Certificate) (*tls.Certificate,
} }
return &cert, nil return &cert, nil
} }
func isACMETLS(clientHello *tls.ClientHelloInfo) bool {
for _, proto := range clientHello.SupportedProtos {
if proto == tlsalpn01.ACMETLS1Protocol {
return true
}
}
return false
}

View file

@ -1,6 +1,7 @@
package types package types
import ( import (
"slices"
"strconv" "strconv"
"strings" "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. // Contains tests whether the passed status code is within one of its HTTP code ranges.
func (h HTTPCodeRanges) Contains(statusCode int) bool { func (h HTTPCodeRanges) Contains(statusCode int) bool {
for _, block := range h { return slices.ContainsFunc(h, func(block [2]int) bool {
if statusCode >= block[0] && statusCode <= block[1] { return statusCode >= block[0] && statusCode <= block[1]
return true })
}
}
return false
} }

View file

@ -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()) udpConn2, err := net.Dial("udp", ln.Addr().String())
require.NoError(t, err) require.NoError(t, err)