From bdba7d3adfd404ea5de8fab5ab875470521108da Mon Sep 17 00:00:00 2001 From: Romain Date: Thu, 4 Mar 2021 20:08:03 +0100 Subject: [PATCH] Update to go1.16 --- build.Dockerfile | 2 +- docs/content/contributing/building-testing.md | 4 +- exp.Dockerfile | 2 +- go.mod | 5 +- go.sum | 9 +- integration/access_log_test.go | 11 +- integration/acme_test.go | 3 +- integration/consul_test.go | 5 +- integration/docker_test.go | 8 +- integration/etcd_test.go | 5 +- integration/grpc_test.go | 5 +- integration/integration_test.go | 5 +- integration/k8s_test.go | 7 +- integration/log_rotation_test.go | 5 +- integration/redis_test.go | 5 +- integration/simple_test.go | 10 +- integration/tls_client_headers_test.go | 7 +- integration/try/condition.go | 10 +- integration/websocket_test.go | 5 +- integration/zk_test.go | 5 +- pkg/anonymize/anonymize_config_test.go | 9 +- pkg/anonymize/anonymize_doOnJSON_test.go | 6 +- pkg/api/handler_entrypoint_test.go | 9 +- pkg/api/handler_http_test.go | 9 +- pkg/api/handler_overview_test.go | 9 +- pkg/api/handler_tcp_test.go | 9 +- pkg/api/handler_test.go | 11 +- pkg/api/handler_udp_test.go | 9 +- pkg/cli/loader_file.go | 3 +- pkg/config/dynamic/middlewares.go | 3 +- pkg/metrics/influxdb_test.go | 4 +- pkg/middlewares/accesslog/logger_test.go | 46 ++------ pkg/middlewares/auth/auth.go | 4 +- pkg/middlewares/auth/basic_auth_test.go | 17 ++- pkg/middlewares/auth/digest_auth_test.go | 9 +- pkg/middlewares/auth/forward.go | 4 +- pkg/middlewares/auth/forward_test.go | 13 +-- pkg/middlewares/compress/compress_test.go | 6 +- pkg/middlewares/retry/retry.go | 6 +- pkg/middlewares/retry/retry_test.go | 107 ++++++------------ pkg/pilot/pilot.go | 6 +- pkg/plugins/client.go | 7 +- pkg/provider/acme/local_store.go | 6 +- pkg/provider/acme/local_store_test.go | 6 +- pkg/provider/file/file.go | 5 +- pkg/provider/file/file_test.go | 23 +--- pkg/provider/http/http.go | 4 +- pkg/provider/kubernetes/crd/client.go | 3 +- .../kubernetes/crd/client_mock_test.go | 4 +- .../kubernetes/crd/kubernetes_test.go | 4 +- pkg/provider/kubernetes/gateway/client.go | 4 +- .../kubernetes/gateway/client_mock_test.go | 4 +- pkg/provider/kubernetes/ingress/client.go | 3 +- .../kubernetes/ingress/client_mock_test.go | 4 +- pkg/provider/traefik/internal_test.go | 6 +- pkg/server/router/router_test.go | 6 +- pkg/server/server_entrypoint_tcp_test.go | 2 +- .../service/loadbalancer/mirror/mirror.go | 7 +- .../loadbalancer/mirror/mirror_test.go | 10 +- pkg/server/service/proxy_test.go | 4 +- pkg/tls/certificate.go | 3 +- pkg/types/tls.go | 3 +- 62 files changed, 217 insertions(+), 318 deletions(-) diff --git a/build.Dockerfile b/build.Dockerfile index 736447861..44880272a 100644 --- a/build.Dockerfile +++ b/build.Dockerfile @@ -1,4 +1,4 @@ -FROM golang:1.15-alpine +FROM golang:1.16-alpine RUN apk --update upgrade \ && apk --no-cache --no-progress add git mercurial bash gcc musl-dev curl tar ca-certificates tzdata \ diff --git a/docs/content/contributing/building-testing.md b/docs/content/contributing/building-testing.md index 665852872..f2e7eea57 100644 --- a/docs/content/contributing/building-testing.md +++ b/docs/content/contributing/building-testing.md @@ -30,7 +30,7 @@ Successfully tagged traefik-webui:latest [...] docker build -t "traefik-dev:4475--feature-documentation" -f build.Dockerfile . Sending build context to Docker daemon 279MB -Step 1/10 : FROM golang:1.14-alpine +Step 1/10 : FROM golang:1.16-alpine ---> f4bfb3d22bda [...] Successfully built 5c3c1a911277 @@ -62,7 +62,7 @@ PRE_TARGET= make test-unit Requirements: -- `go` v1.14+ +- `go` v1.16+ - environment variable `GO111MODULE=on` - [go-bindata](https://github.com/containous/go-bindata) `GO111MODULE=off go get -u github.com/containous/go-bindata/...` diff --git a/exp.Dockerfile b/exp.Dockerfile index b63b6f67b..318f8c95f 100644 --- a/exp.Dockerfile +++ b/exp.Dockerfile @@ -12,7 +12,7 @@ RUN npm install RUN npm run build # BUILD -FROM golang:1.15-alpine as gobuild +FROM golang:1.16-alpine as gobuild RUN apk --update upgrade \ && apk --no-cache --no-progress add git mercurial bash gcc musl-dev curl tar ca-certificates tzdata \ diff --git a/go.mod b/go.mod index 94e41ea43..a5fd2b11a 100644 --- a/go.mod +++ b/go.mod @@ -1,6 +1,6 @@ module github.com/traefik/traefik/v2 -go 1.15 +go 1.16 require ( github.com/BurntSushi/toml v0.3.1 @@ -78,7 +78,7 @@ require ( github.com/unrolled/render v1.0.2 github.com/unrolled/secure v1.0.7 github.com/vdemeester/shakers v0.1.0 - github.com/vulcand/oxy v1.1.0 + github.com/vulcand/oxy v1.2.0 github.com/vulcand/predicate v1.1.0 go.elastic.co/apm v1.7.0 go.elastic.co/apm/module/apmot v1.7.0 @@ -88,7 +88,6 @@ require ( google.golang.org/grpc v1.27.1 gopkg.in/DataDog/dd-trace-go.v1 v1.19.0 gopkg.in/fsnotify.v1 v1.4.7 - gopkg.in/jcmturner/goidentity.v3 v3.0.0 // indirect gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776 k8s.io/api v0.19.2 k8s.io/apimachinery v0.19.2 diff --git a/go.sum b/go.sum index 2b1ff801f..516778472 100644 --- a/go.sum +++ b/go.sum @@ -98,7 +98,6 @@ github.com/PuerkitoBio/urlesc v0.0.0-20170810143723-de5bf2ad4578/go.mod h1:uGdko github.com/Shopify/sarama v1.19.0/go.mod h1:FVkBWblsNy7DGZRfXLU0O9RCGt5g3g3yEuWXgklEdEo= github.com/Shopify/sarama v1.23.1 h1:XxJBCZEoWJtoWjf/xRbmGUpAmTZGnuuF0ON0EvxxBrs= github.com/Shopify/sarama v1.23.1/go.mod h1:XLH1GYJnLVE0XCr6KdJGVJRTwY30moWNJ4sERjXX6fs= -github.com/Shopify/toxiproxy v2.1.4+incompatible h1:TKdv8HiTLgE5wdJuEML90aBgNWsokNbMijUGhmcoBJc= github.com/Shopify/toxiproxy v2.1.4+incompatible/go.mod h1:OXgGpZ6Cli1/URJOF1DMxUHB2q5Ap20/P/eIdh4G0pI= github.com/VividCortex/gohistogram v1.0.0 h1:6+hBz+qvs0JOrrNhhmR7lFxo5sINxBCGXrdtl/UvroE= github.com/VividCortex/gohistogram v1.0.0/go.mod h1:Pf5mBqqDxYaXu3hDrrU+w6nw50o/4+TcAqDqk/vUH7g= @@ -664,7 +663,6 @@ github.com/nats-io/nats.go v1.9.1/go.mod h1:ZjDU1L/7fJ09jvUSRVBR2e7+RnLiiIQyqyzE github.com/nats-io/nkeys v0.1.0/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= github.com/nats-io/nkeys v0.1.3/go.mod h1:xpnFELMwJABBLVhffcfd1MZx6VsNRFpEugbxziKVo7w= github.com/nats-io/nuid v1.0.1/go.mod h1:19wcPz3Ph3q0Jbyiqsd0kePYG7A95tJPxeL+1OSON2c= -github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32 h1:W6apQkHrMkS0Muv8G/TipAy/FJl/rCYT0+EuS8+Z0z4= github.com/nbio/st v0.0.0-20140626010706-e9e8d9816f32/go.mod h1:9wM+0iRr9ahx58uYLpLIr5fm8diHn0JbqRycJi6w0Ms= github.com/nrdcg/auroradns v1.0.1 h1:m/kBq83Xvy3cU261MOknd8BdnOk12q4lAWM+kOdsC2Y= github.com/nrdcg/auroradns v1.0.1/go.mod h1:y4pc0i9QXYlFCWrhWrUSIETnZgrf4KuwjDIWmmXo3JI= @@ -895,8 +893,8 @@ github.com/urfave/cli v1.22.4/go.mod h1:Gos4lmkARVdJ6EkW0WaNv/tZAAMe9V7XWyB60NtX github.com/vdemeester/shakers v0.1.0 h1:K+n9sSyUCg2ywmZkv+3c7vsYZfivcfKhMh8kRxCrONM= github.com/vdemeester/shakers v0.1.0/go.mod h1:IZ1HHynUOQt32iQ3rvAeVddXLd19h/6LWiKsh9RZtAQ= github.com/vektah/gqlparser v1.1.2/go.mod h1:1ycwN7Ij5njmMkPPAOaRFY4rET2Enx7IkVv3vaXspKw= -github.com/vulcand/oxy v1.1.0 h1:DbBijGo1+6cFqR9jarkMxasdj0lgWwrrFtue6ijek4Q= -github.com/vulcand/oxy v1.1.0/go.mod h1:ADiMYHi8gkGl2987yQIzDRoXZilANF4WtKaQ92OppKY= +github.com/vulcand/oxy v1.2.0 h1:Y2Wt1EgQddA/qMnp1+YXjehPsyw2Gy8CAfavkFF+fQk= +github.com/vulcand/oxy v1.2.0/go.mod h1:nGeNTWfyYQj3ghi3W8ok7vLSkw7Gkvr0x+G/v8Wk7vM= github.com/vulcand/predicate v1.1.0 h1:Gq/uWopa4rx/tnZu2opOSBqHK63Yqlou/SzrbwdJiNg= github.com/vulcand/predicate v1.1.0/go.mod h1:mlccC5IRBoc2cIFmCB8ZM62I3VDb6p2GXESMHa3CnZg= github.com/vultr/govultr/v2 v2.0.0 h1:+lAtqfWy3g9VwL7tT2Fpyad8Vv4MxOhT/NU8O5dk+EQ= @@ -925,7 +923,6 @@ go.elastic.co/fastjson v1.0.0 h1:ooXV/ABvf+tBul26jcVViPT3sBir0PvXgibYB1IQQzg= go.elastic.co/fastjson v1.0.0/go.mod h1:PmeUOMMtLHQr9ZS9J9owrAVg0FkaZDRZJEFTTGHtchs= go.etcd.io/bbolt v1.3.1-etcd.8/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= -go.etcd.io/bbolt v1.3.3 h1:MUGmc65QhB3pIlaQ5bB4LwqSj6GIonVJXpZiaKNyaKk= go.etcd.io/bbolt v1.3.3/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU= go.etcd.io/etcd v0.0.0-20191023171146-3cf2f69b5738/go.mod h1:dnLIgRNXwCJa5e+c6mIZCrds/GIG4ncV9HhK5PX7jPg= go.etcd.io/etcd v3.3.13+incompatible h1:jCejD5EMnlGxFvcGRyEV4VGlENZc7oPQX6o0t7n3xbw= @@ -1271,8 +1268,6 @@ gopkg.in/jcmturner/aescts.v1 v1.0.1 h1:cVVZBK2b1zY26haWB4vbBiZrfFQnfbTVrE3xZq6hr gopkg.in/jcmturner/aescts.v1 v1.0.1/go.mod h1:nsR8qBOg+OucoIW+WMhB3GspUQXq9XorLnQb9XtvcOo= gopkg.in/jcmturner/dnsutils.v1 v1.0.1 h1:cIuC1OLRGZrld+16ZJvvZxVJeKPsvd5eUIvxfoN5hSM= gopkg.in/jcmturner/dnsutils.v1 v1.0.1/go.mod h1:m3v+5svpVOhtFAP/wSz+yzh4Mc0Fg7eRhxkJMWSIz9Q= -gopkg.in/jcmturner/goidentity.v3 v3.0.0 h1:1duIyWiTaYvVx3YX2CYtpJbUFd7/UuPYCfgXtQ3VTbI= -gopkg.in/jcmturner/goidentity.v3 v3.0.0/go.mod h1:oG2kH0IvSYNIu80dVAyu/yoefjq1mNfM5bm88whjWx4= gopkg.in/jcmturner/gokrb5.v7 v7.2.3 h1:hHMV/yKPwMnJhPuPx7pH2Uw/3Qyf+thJYlisUc44010= gopkg.in/jcmturner/gokrb5.v7 v7.2.3/go.mod h1:l8VISx+WGYp+Fp7KRbsiUuXTTOnxIc3Tuvyavf11/WM= gopkg.in/jcmturner/rpc.v1 v1.1.0 h1:QHIUxTX1ISuAv9dD2wJ9HWQVuWDX/Zc0PfeC2tjc4rU= diff --git a/integration/access_log_test.go b/integration/access_log_test.go index 74d8200e1..59f23eccb 100644 --- a/integration/access_log_test.go +++ b/integration/access_log_test.go @@ -5,7 +5,6 @@ import ( "crypto/rand" "fmt" "io" - "io/ioutil" "net/http" "os" "strconv" @@ -58,7 +57,7 @@ func (s *AccessLogSuite) TestAccessLog(c *check.C) { defer display(c) defer func() { - traefikLog, err := ioutil.ReadFile(traefikTestLogFile) + traefikLog, err := os.ReadFile(traefikTestLogFile) c.Assert(err, checker.IsNil) log.WithoutContext().Info(string(traefikLog)) }() @@ -545,7 +544,7 @@ func (s *AccessLogSuite) TestAccessLogAuthFrontendSuccess(c *check.C) { } func checkNoOtherTraefikProblems(c *check.C) { - traefikLog, err := ioutil.ReadFile(traefikTestLogFile) + traefikLog, err := os.ReadFile(traefikTestLogFile) c.Assert(err, checker.IsNil) if len(traefikLog) > 0 { fmt.Printf("%s\n", string(traefikLog)) @@ -583,7 +582,7 @@ func checkAccessLogExactValuesOutput(c *check.C, values []accessLogValue) int { } func extractLines(c *check.C) []string { - accessLog, err := ioutil.ReadFile(traefikTestAccessLogFile) + accessLog, err := os.ReadFile(traefikTestAccessLogFile) c.Assert(err, checker.IsNil) lines := strings.Split(string(accessLog), "\n") @@ -613,7 +612,7 @@ func ensureWorkingDirectoryIsClean() { } func checkTraefikStarted(c *check.C) []byte { - traefikLog, err := ioutil.ReadFile(traefikTestLogFile) + traefikLog, err := os.ReadFile(traefikTestLogFile) c.Assert(err, checker.IsNil) if len(traefikLog) > 0 { fmt.Printf("%s\n", string(traefikLog)) @@ -663,7 +662,7 @@ func waitForTraefik(c *check.C, containerName string) { func displayTraefikLogFile(c *check.C, path string) { if c.Failed() { if _, err := os.Stat(path); !os.IsNotExist(err) { - content, errRead := ioutil.ReadFile(path) + content, errRead := os.ReadFile(path) fmt.Printf("%s: Traefik logs: \n", c.TestName()) if errRead == nil { fmt.Println(content) diff --git a/integration/acme_test.go b/integration/acme_test.go index a67eb96e2..503f03c6c 100644 --- a/integration/acme_test.go +++ b/integration/acme_test.go @@ -4,7 +4,6 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" "net/http" "os" "path/filepath" @@ -67,7 +66,7 @@ func setupPebbleRootCA() (*http.Transport, error) { os.Setenv("LEGO_CA_CERTIFICATES", path) os.Setenv("LEGO_CA_SERVER_NAME", "pebble") - customCAs, err := ioutil.ReadFile(path) + customCAs, err := os.ReadFile(path) if err != nil { return nil, err } diff --git a/integration/consul_test.go b/integration/consul_test.go index 07ade5d17..330069a39 100644 --- a/integration/consul_test.go +++ b/integration/consul_test.go @@ -3,7 +3,6 @@ package integration import ( "bytes" "encoding/json" - "io/ioutil" "net/http" "os" "path/filepath" @@ -138,11 +137,11 @@ func (s *ConsulSuite) TestSimpleConfiguration(c *check.C) { expectedJSON := filepath.FromSlash("testdata/rawdata-consul.json") if *updateExpected { - err = ioutil.WriteFile(expectedJSON, got, 0o666) + err = os.WriteFile(expectedJSON, got, 0o666) c.Assert(err, checker.IsNil) } - expected, err := ioutil.ReadFile(expectedJSON) + expected, err := os.ReadFile(expectedJSON) c.Assert(err, checker.IsNil) if !bytes.Equal(expected, got) { diff --git a/integration/docker_test.go b/integration/docker_test.go index e379d4f6b..bff89ad9e 100644 --- a/integration/docker_test.go +++ b/integration/docker_test.go @@ -3,7 +3,7 @@ package integration import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "os" "strings" @@ -135,7 +135,7 @@ func (s *DockerSuite) TestDefaultDockerContainers(c *check.C) { resp, err := try.ResponseUntilStatusCode(req, 1500*time.Millisecond, http.StatusOK) c.Assert(err, checker.IsNil) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) c.Assert(err, checker.IsNil) var version map[string]interface{} @@ -228,7 +228,7 @@ func (s *DockerSuite) TestDockerContainersWithLabels(c *check.C) { resp, err := try.ResponseUntilStatusCode(req, 1500*time.Millisecond, http.StatusOK) c.Assert(err, checker.IsNil) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) c.Assert(err, checker.IsNil) var version map[string]interface{} @@ -307,7 +307,7 @@ func (s *DockerSuite) TestRestartDockerContainers(c *check.C) { resp, err := try.ResponseUntilStatusCode(req, 1500*time.Millisecond, http.StatusOK) c.Assert(err, checker.IsNil) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) c.Assert(err, checker.IsNil) var version map[string]interface{} diff --git a/integration/etcd_test.go b/integration/etcd_test.go index a4ca83262..ff8f8cc16 100644 --- a/integration/etcd_test.go +++ b/integration/etcd_test.go @@ -3,7 +3,6 @@ package integration import ( "bytes" "encoding/json" - "io/ioutil" "net/http" "os" "path/filepath" @@ -138,11 +137,11 @@ func (s *EtcdSuite) TestSimpleConfiguration(c *check.C) { expectedJSON := filepath.FromSlash("testdata/rawdata-etcd.json") if *updateExpected { - err = ioutil.WriteFile(expectedJSON, got, 0o666) + err = os.WriteFile(expectedJSON, got, 0o666) c.Assert(err, checker.IsNil) } - expected, err := ioutil.ReadFile(expectedJSON) + expected, err := os.ReadFile(expectedJSON) c.Assert(err, checker.IsNil) if !bytes.Equal(expected, got) { diff --git a/integration/grpc_test.go b/integration/grpc_test.go index 51ede7b60..496f4b371 100644 --- a/integration/grpc_test.go +++ b/integration/grpc_test.go @@ -5,7 +5,6 @@ import ( "crypto/tls" "crypto/x509" "errors" - "io/ioutil" "math/rand" "net" "os" @@ -35,9 +34,9 @@ type myserver struct { func (s *GRPCSuite) SetUpSuite(c *check.C) { var err error - LocalhostCert, err = ioutil.ReadFile("./resources/tls/local.cert") + LocalhostCert, err = os.ReadFile("./resources/tls/local.cert") c.Assert(err, check.IsNil) - LocalhostKey, err = ioutil.ReadFile("./resources/tls/local.key") + LocalhostKey, err = os.ReadFile("./resources/tls/local.key") c.Assert(err, check.IsNil) } diff --git a/integration/integration_test.go b/integration/integration_test.go index 020ea3c53..1cd438d9b 100644 --- a/integration/integration_test.go +++ b/integration/integration_test.go @@ -5,7 +5,6 @@ import ( "bytes" "flag" "fmt" - "io/ioutil" "net" "os" "os/exec" @@ -143,7 +142,7 @@ func (s *BaseSuite) traefikCmd(args ...string) (*exec.Cmd, func(*check.C)) { func (s *BaseSuite) displayLogK3S(c *check.C) { filePath := "./fixtures/k8s/config.skip/k3s.log" if _, err := os.Stat(filePath); err == nil { - content, errR := ioutil.ReadFile(filePath) + content, errR := os.ReadFile(filePath) if errR != nil { log.WithoutContext().Error(errR) } @@ -178,7 +177,7 @@ func (s *BaseSuite) adaptFile(c *check.C, path string, tempObjects interface{}) c.Assert(err, checker.IsNil) folder, prefix := filepath.Split(path) - tmpFile, err := ioutil.TempFile(folder, strings.TrimSuffix(prefix, filepath.Ext(prefix))+"_*"+filepath.Ext(prefix)) + tmpFile, err := os.CreateTemp(folder, strings.TrimSuffix(prefix, filepath.Ext(prefix))+"_*"+filepath.Ext(prefix)) c.Assert(err, checker.IsNil) defer tmpFile.Close() diff --git a/integration/k8s_test.go b/integration/k8s_test.go index b5f2b2093..392c327cf 100644 --- a/integration/k8s_test.go +++ b/integration/k8s_test.go @@ -7,7 +7,6 @@ import ( "flag" "fmt" "io" - "io/ioutil" "net/http" "os" "path/filepath" @@ -153,14 +152,14 @@ func testConfiguration(c *check.C, path, apiPort string) { newJSON, err := json.MarshalIndent(rtRepr, "", "\t") c.Assert(err, checker.IsNil) - err = ioutil.WriteFile(expectedJSON, newJSON, 0o644) + err = os.WriteFile(expectedJSON, newJSON, 0o644) c.Assert(err, checker.IsNil) c.Errorf("We do not want a passing test in file update mode") } func matchesConfig(wantConfig string, buf *bytes.Buffer) try.ResponseCondition { return func(res *http.Response) error { - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) if err != nil { return fmt.Errorf("failed to read response body: %w", err) } @@ -187,7 +186,7 @@ func matchesConfig(wantConfig string, buf *bytes.Buffer) try.ResponseCondition { return err } - expected, err := ioutil.ReadFile(wantConfig) + expected, err := os.ReadFile(wantConfig) if err != nil { return err } diff --git a/integration/log_rotation_test.go b/integration/log_rotation_test.go index d91bf04b4..2fe27d78b 100644 --- a/integration/log_rotation_test.go +++ b/integration/log_rotation_test.go @@ -4,7 +4,6 @@ package integration import ( "bufio" - "io/ioutil" "net/http" "os" "strings" @@ -130,14 +129,14 @@ func (s *LogRotationSuite) TestTraefikLogRotation(c *check.C) { } func logAccessLogFile(c *check.C, fileName string) { - output, err := ioutil.ReadFile(fileName) + output, err := os.ReadFile(fileName) c.Assert(err, checker.IsNil) c.Logf("Contents of file %s\n%s", fileName, string(output)) } func verifyEmptyErrorLog(c *check.C, name string) { err := try.Do(5*time.Second, func() error { - traefikLog, e2 := ioutil.ReadFile(name) + traefikLog, e2 := os.ReadFile(name) if e2 != nil { return e2 } diff --git a/integration/redis_test.go b/integration/redis_test.go index f601ca35a..eb31d5533 100644 --- a/integration/redis_test.go +++ b/integration/redis_test.go @@ -3,7 +3,6 @@ package integration import ( "bytes" "encoding/json" - "io/ioutil" "net/http" "os" "path/filepath" @@ -138,11 +137,11 @@ func (s *RedisSuite) TestSimpleConfiguration(c *check.C) { expectedJSON := filepath.FromSlash("testdata/rawdata-redis.json") if *updateExpected { - err = ioutil.WriteFile(expectedJSON, got, 0o666) + err = os.WriteFile(expectedJSON, got, 0o666) c.Assert(err, checker.IsNil) } - expected, err := ioutil.ReadFile(expectedJSON) + expected, err := os.ReadFile(expectedJSON) c.Assert(err, checker.IsNil) if !bytes.Equal(expected, got) { diff --git a/integration/simple_test.go b/integration/simple_test.go index d5cbc09a9..17519d0d5 100644 --- a/integration/simple_test.go +++ b/integration/simple_test.go @@ -5,7 +5,7 @@ import ( "crypto/rand" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "os" @@ -688,7 +688,7 @@ func (s *SimpleSuite) TestWRR(c *check.C) { c.Assert(err, checker.IsNil) c.Assert(response.StatusCode, checker.Equals, http.StatusOK) - body, err := ioutil.ReadAll(response.Body) + body, err := io.ReadAll(response.Body) c.Assert(err, checker.IsNil) if strings.Contains(string(body), server1) { @@ -739,7 +739,7 @@ func (s *SimpleSuite) TestWRRSticky(c *check.C) { req.AddCookie(cookie) } - body, err := ioutil.ReadAll(response.Body) + body, err := io.ReadAll(response.Body) c.Assert(err, checker.IsNil) if strings.Contains(string(body), server1) { @@ -819,7 +819,7 @@ func (s *SimpleSuite) TestMirrorWithBody(c *check.C) { c.Assert(err, checker.IsNil) verifyBody := func(req *http.Request) { - b, _ := ioutil.ReadAll(req.Body) + b, _ := io.ReadAll(req.Body) switch req.Header.Get("Size") { case "20": if !bytes.Equal(b, body20) { @@ -1030,7 +1030,7 @@ func (s *SimpleSuite) TestContentTypeDisableAutoDetect(c *check.C) { rw.WriteHeader(http.StatusOK) - data, err := ioutil.ReadFile("fixtures/test.pdf") + data, err := os.ReadFile("fixtures/test.pdf") c.Assert(err, checker.IsNil) _, err = rw.Write(data) diff --git a/integration/tls_client_headers_test.go b/integration/tls_client_headers_test.go index f55d2ff99..9d2de014c 100644 --- a/integration/tls_client_headers_test.go +++ b/integration/tls_client_headers_test.go @@ -2,7 +2,6 @@ package integration import ( "crypto/tls" - "io/ioutil" "net/http" "os" "time" @@ -26,11 +25,11 @@ func (s *TLSClientHeadersSuite) SetUpSuite(c *check.C) { } func (s *TLSClientHeadersSuite) TestTLSClientHeaders(c *check.C) { - rootCertContent, err := ioutil.ReadFile(rootCertPath) + rootCertContent, err := os.ReadFile(rootCertPath) c.Assert(err, check.IsNil) - serverCertContent, err := ioutil.ReadFile(certPemPath) + serverCertContent, err := os.ReadFile(certPemPath) c.Assert(err, check.IsNil) - ServerKeyContent, err := ioutil.ReadFile(certKeyPath) + ServerKeyContent, err := os.ReadFile(certKeyPath) c.Assert(err, check.IsNil) file := s.adaptFile(c, "fixtures/tlsclientheaders/simple.toml", struct { diff --git a/integration/try/condition.go b/integration/try/condition.go index a2619a28b..c10d20a9a 100644 --- a/integration/try/condition.go +++ b/integration/try/condition.go @@ -3,7 +3,7 @@ package try import ( "errors" "fmt" - "io/ioutil" + "io" "net/http" "reflect" "strings" @@ -19,7 +19,7 @@ type ResponseCondition func(*http.Response) error // The condition returns an error if the request body does not contain all the given strings. func BodyContains(values ...string) ResponseCondition { return func(res *http.Response) error { - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) if err != nil { return fmt.Errorf("failed to read response body: %w", err) } @@ -37,7 +37,7 @@ func BodyContains(values ...string) ResponseCondition { // The condition returns an error if the request body contain one of the given strings. func BodyNotContains(values ...string) ResponseCondition { return func(res *http.Response) error { - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) if err != nil { return fmt.Errorf("failed to read response body: %w", err) } @@ -55,7 +55,7 @@ func BodyNotContains(values ...string) ResponseCondition { // The condition returns an error if the request body does not contain one of the given strings. func BodyContainsOr(values ...string) ResponseCondition { return func(res *http.Response) error { - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) if err != nil { return fmt.Errorf("failed to read response body: %w", err) } @@ -73,7 +73,7 @@ func BodyContainsOr(values ...string) ResponseCondition { // The condition returns an error if the request body does not have body content. func HasBody() ResponseCondition { return func(res *http.Response) error { - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) if err != nil { return fmt.Errorf("failed to read response body: %w", err) } diff --git a/integration/websocket_test.go b/integration/websocket_test.go index 1b312fa72..819da7cc1 100644 --- a/integration/websocket_test.go +++ b/integration/websocket_test.go @@ -4,7 +4,6 @@ import ( "crypto/tls" "crypto/x509" "encoding/base64" - "io/ioutil" "net" "net/http" "net/http/httptest" @@ -279,7 +278,7 @@ func (s *WebsocketSuite) TestSSLTermination(c *check.C) { // Add client self-signed cert roots := x509.NewCertPool() - certContent, err := ioutil.ReadFile("./resources/tls/local.cert") + certContent, err := os.ReadFile("./resources/tls/local.cert") c.Assert(err, checker.IsNil) roots.AppendCertsFromPEM(certContent) gorillawebsocket.DefaultDialer.TLSClientConfig = &tls.Config{ @@ -484,7 +483,7 @@ func (s *WebsocketSuite) TestSSLhttp2(c *check.C) { // Add client self-signed cert roots := x509.NewCertPool() - certContent, err := ioutil.ReadFile("./resources/tls/local.cert") + certContent, err := os.ReadFile("./resources/tls/local.cert") c.Assert(err, checker.IsNil) roots.AppendCertsFromPEM(certContent) gorillawebsocket.DefaultDialer.TLSClientConfig = &tls.Config{ diff --git a/integration/zk_test.go b/integration/zk_test.go index 5ab71151f..61154779d 100644 --- a/integration/zk_test.go +++ b/integration/zk_test.go @@ -3,7 +3,6 @@ package integration import ( "bytes" "encoding/json" - "io/ioutil" "net/http" "os" "path/filepath" @@ -138,11 +137,11 @@ func (s *ZookeeperSuite) TestSimpleConfiguration(c *check.C) { expectedJSON := filepath.FromSlash("testdata/rawdata-zk.json") if *updateExpected { - err = ioutil.WriteFile(expectedJSON, got, 0o666) + err = os.WriteFile(expectedJSON, got, 0o666) c.Assert(err, checker.IsNil) } - expected, err := ioutil.ReadFile(expectedJSON) + expected, err := os.ReadFile(expectedJSON) c.Assert(err, checker.IsNil) if !bytes.Equal(expected, got) { diff --git a/pkg/anonymize/anonymize_config_test.go b/pkg/anonymize/anonymize_config_test.go index 4c3b67d4c..b769b78c2 100644 --- a/pkg/anonymize/anonymize_config_test.go +++ b/pkg/anonymize/anonymize_config_test.go @@ -2,7 +2,6 @@ package anonymize import ( "flag" - "io/ioutil" "os" "strings" "testing" @@ -462,14 +461,14 @@ func TestDo_dynamicConfiguration(t *testing.T) { }, } - expectedConfiguration, err := ioutil.ReadFile("./testdata/anonymized-dynamic-config.json") + expectedConfiguration, err := os.ReadFile("./testdata/anonymized-dynamic-config.json") require.NoError(t, err) cleanJSON, err := Do(config, true) require.NoError(t, err) if *updateExpected { - require.NoError(t, ioutil.WriteFile("testdata/anonymized-dynamic-config.json", []byte(cleanJSON), 0666)) + require.NoError(t, os.WriteFile("testdata/anonymized-dynamic-config.json", []byte(cleanJSON), 0666)) } expected := strings.TrimSuffix(string(expectedConfiguration), "\n") @@ -965,14 +964,14 @@ func TestDo_staticConfiguration(t *testing.T) { }, } - expectedConfiguration, err := ioutil.ReadFile("./testdata/anonymized-static-config.json") + expectedConfiguration, err := os.ReadFile("./testdata/anonymized-static-config.json") require.NoError(t, err) cleanJSON, err := Do(config, true) require.NoError(t, err) if *updateExpected { - require.NoError(t, ioutil.WriteFile("testdata/anonymized-static-config.json", []byte(cleanJSON), 0666)) + require.NoError(t, os.WriteFile("testdata/anonymized-static-config.json", []byte(cleanJSON), 0666)) } expected := strings.TrimSuffix(string(expectedConfiguration), "\n") diff --git a/pkg/anonymize/anonymize_doOnJSON_test.go b/pkg/anonymize/anonymize_doOnJSON_test.go index 1ff7b9d4b..85248954b 100644 --- a/pkg/anonymize/anonymize_doOnJSON_test.go +++ b/pkg/anonymize/anonymize_doOnJSON_test.go @@ -1,7 +1,7 @@ package anonymize import ( - "io/ioutil" + "os" "testing" "github.com/stretchr/testify/assert" @@ -9,12 +9,12 @@ import ( ) func Test_doOnJSON(t *testing.T) { - baseConfiguration, err := ioutil.ReadFile("./testdata/example.json") + baseConfiguration, err := os.ReadFile("./testdata/example.json") require.NoError(t, err) anomConfiguration := doOnJSON(string(baseConfiguration)) - expectedConfiguration, err := ioutil.ReadFile("./testdata/expected.json") + expectedConfiguration, err := os.ReadFile("./testdata/expected.json") require.NoError(t, err) assert.JSONEq(t, string(expectedConfiguration), anomConfiguration) diff --git a/pkg/api/handler_entrypoint_test.go b/pkg/api/handler_entrypoint_test.go index 5a2a134aa..a3c31e583 100644 --- a/pkg/api/handler_entrypoint_test.go +++ b/pkg/api/handler_entrypoint_test.go @@ -3,9 +3,10 @@ package api import ( "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" + "os" "strconv" "testing" @@ -212,7 +213,7 @@ func TestHandler_EntryPoints(t *testing.T) { } assert.Equal(t, resp.Header.Get("Content-Type"), "application/json") - contents, err := ioutil.ReadAll(resp.Body) + contents, err := io.ReadAll(resp.Body) require.NoError(t, err) err = resp.Body.Close() @@ -226,11 +227,11 @@ func TestHandler_EntryPoints(t *testing.T) { newJSON, err := json.MarshalIndent(results, "", "\t") require.NoError(t, err) - err = ioutil.WriteFile(test.expected.jsonFile, newJSON, 0o644) + err = os.WriteFile(test.expected.jsonFile, newJSON, 0o644) require.NoError(t, err) } - data, err := ioutil.ReadFile(test.expected.jsonFile) + data, err := os.ReadFile(test.expected.jsonFile) require.NoError(t, err) assert.JSONEq(t, string(data), string(contents)) }) diff --git a/pkg/api/handler_http_test.go b/pkg/api/handler_http_test.go index 93adb0b23..e3698fa4c 100644 --- a/pkg/api/handler_http_test.go +++ b/pkg/api/handler_http_test.go @@ -4,9 +4,10 @@ import ( "context" "encoding/json" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" + "os" "strconv" "testing" @@ -826,7 +827,7 @@ func TestHandler_HTTP(t *testing.T) { } assert.Equal(t, resp.Header.Get("Content-Type"), "application/json") - contents, err := ioutil.ReadAll(resp.Body) + contents, err := io.ReadAll(resp.Body) require.NoError(t, err) err = resp.Body.Close() @@ -840,11 +841,11 @@ func TestHandler_HTTP(t *testing.T) { newJSON, err := json.MarshalIndent(results, "", "\t") require.NoError(t, err) - err = ioutil.WriteFile(test.expected.jsonFile, newJSON, 0o644) + err = os.WriteFile(test.expected.jsonFile, newJSON, 0o644) require.NoError(t, err) } - data, err := ioutil.ReadFile(test.expected.jsonFile) + data, err := os.ReadFile(test.expected.jsonFile) require.NoError(t, err) assert.JSONEq(t, string(data), string(contents)) }) diff --git a/pkg/api/handler_overview_test.go b/pkg/api/handler_overview_test.go index e5238ce28..00a4bc36c 100644 --- a/pkg/api/handler_overview_test.go +++ b/pkg/api/handler_overview_test.go @@ -2,9 +2,10 @@ package api import ( "encoding/json" - "io/ioutil" + "io" "net/http" "net/http/httptest" + "os" "testing" "github.com/stretchr/testify/assert" @@ -263,7 +264,7 @@ func TestHandler_Overview(t *testing.T) { } assert.Equal(t, resp.Header.Get("Content-Type"), "application/json") - contents, err := ioutil.ReadAll(resp.Body) + contents, err := io.ReadAll(resp.Body) require.NoError(t, err) err = resp.Body.Close() @@ -277,11 +278,11 @@ func TestHandler_Overview(t *testing.T) { newJSON, err := json.MarshalIndent(results, "", "\t") require.NoError(t, err) - err = ioutil.WriteFile(test.expected.jsonFile, newJSON, 0o644) + err = os.WriteFile(test.expected.jsonFile, newJSON, 0o644) require.NoError(t, err) } - data, err := ioutil.ReadFile(test.expected.jsonFile) + data, err := os.ReadFile(test.expected.jsonFile) require.NoError(t, err) assert.JSONEq(t, string(data), string(contents)) }) diff --git a/pkg/api/handler_tcp_test.go b/pkg/api/handler_tcp_test.go index ebbc0fed7..f00a99a4b 100644 --- a/pkg/api/handler_tcp_test.go +++ b/pkg/api/handler_tcp_test.go @@ -3,9 +3,10 @@ package api import ( "context" "encoding/json" - "io/ioutil" + "io" "net/http" "net/http/httptest" + "os" "testing" "github.com/stretchr/testify/assert" @@ -534,7 +535,7 @@ func TestHandler_TCP(t *testing.T) { assert.Equal(t, resp.Header.Get("Content-Type"), "application/json") - contents, err := ioutil.ReadAll(resp.Body) + contents, err := io.ReadAll(resp.Body) require.NoError(t, err) err = resp.Body.Close() @@ -548,11 +549,11 @@ func TestHandler_TCP(t *testing.T) { newJSON, err := json.MarshalIndent(results, "", "\t") require.NoError(t, err) - err = ioutil.WriteFile(test.expected.jsonFile, newJSON, 0o644) + err = os.WriteFile(test.expected.jsonFile, newJSON, 0o644) require.NoError(t, err) } - data, err := ioutil.ReadFile(test.expected.jsonFile) + data, err := os.ReadFile(test.expected.jsonFile) require.NoError(t, err) assert.JSONEq(t, string(data), string(contents)) }) diff --git a/pkg/api/handler_test.go b/pkg/api/handler_test.go index 065bb9035..1dd55ebdb 100644 --- a/pkg/api/handler_test.go +++ b/pkg/api/handler_test.go @@ -3,9 +3,10 @@ package api import ( "encoding/json" "flag" - "io/ioutil" + "io" "net/http" "net/http/httptest" + "os" "testing" "github.com/stretchr/testify/assert" @@ -144,7 +145,7 @@ func TestHandler_RawData(t *testing.T) { assert.Equal(t, test.expected.statusCode, resp.StatusCode) assert.Equal(t, resp.Header.Get("Content-Type"), "application/json") - contents, err := ioutil.ReadAll(resp.Body) + contents, err := io.ReadAll(resp.Body) require.NoError(t, err) err = resp.Body.Close() @@ -161,11 +162,11 @@ func TestHandler_RawData(t *testing.T) { newJSON, err := json.MarshalIndent(rtRepr, "", "\t") require.NoError(t, err) - err = ioutil.WriteFile(test.expected.json, newJSON, 0o644) + err = os.WriteFile(test.expected.json, newJSON, 0o644) require.NoError(t, err) } - data, err := ioutil.ReadFile(test.expected.json) + data, err := os.ReadFile(test.expected.json) require.NoError(t, err) assert.JSONEq(t, string(data), string(contents)) }) @@ -267,7 +268,7 @@ func TestHandler_GetMiddleware(t *testing.T) { return } - data, err := ioutil.ReadAll(resp.Body) + data, err := io.ReadAll(resp.Body) require.NoError(t, err) err = resp.Body.Close() diff --git a/pkg/api/handler_udp_test.go b/pkg/api/handler_udp_test.go index 0d5fc14b1..4a5c0116f 100644 --- a/pkg/api/handler_udp_test.go +++ b/pkg/api/handler_udp_test.go @@ -3,9 +3,10 @@ package api import ( "context" "encoding/json" - "io/ioutil" + "io" "net/http" "net/http/httptest" + "os" "testing" "github.com/stretchr/testify/assert" @@ -511,7 +512,7 @@ func TestHandler_UDP(t *testing.T) { assert.Equal(t, resp.Header.Get("Content-Type"), "application/json") - contents, err := ioutil.ReadAll(resp.Body) + contents, err := io.ReadAll(resp.Body) require.NoError(t, err) err = resp.Body.Close() @@ -525,11 +526,11 @@ func TestHandler_UDP(t *testing.T) { newJSON, err := json.MarshalIndent(results, "", "\t") require.NoError(t, err) - err = ioutil.WriteFile(test.expected.jsonFile, newJSON, 0o644) + err = os.WriteFile(test.expected.jsonFile, newJSON, 0o644) require.NoError(t, err) } - data, err := ioutil.ReadFile(test.expected.jsonFile) + data, err := os.ReadFile(test.expected.jsonFile) require.NoError(t, err) assert.JSONEq(t, string(data), string(contents)) }) diff --git a/pkg/cli/loader_file.go b/pkg/cli/loader_file.go index dd3624010..f01eb763f 100644 --- a/pkg/cli/loader_file.go +++ b/pkg/cli/loader_file.go @@ -1,7 +1,6 @@ package cli import ( - "io/ioutil" "os" "strings" @@ -56,7 +55,7 @@ func (f *FileLoader) Load(args []string, cmd *cli.Command) (bool, error) { logger := log.WithoutContext() logger.Printf("Configuration loaded from file: %s", configFile) - content, _ := ioutil.ReadFile(configFile) + content, _ := os.ReadFile(configFile) logger.Debug(string(content)) return true, nil diff --git a/pkg/config/dynamic/middlewares.go b/pkg/config/dynamic/middlewares.go index b6f763465..b931de0d4 100644 --- a/pkg/config/dynamic/middlewares.go +++ b/pkg/config/dynamic/middlewares.go @@ -4,7 +4,6 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" "os" "time" @@ -446,7 +445,7 @@ func (c *ClientTLS) CreateTLSConfig() (*tls.Config, error) { if c.CA != "" { var ca []byte if _, errCA := os.Stat(c.CA); errCA == nil { - ca, err = ioutil.ReadFile(c.CA) + ca, err = os.ReadFile(c.CA) if err != nil { return nil, fmt.Errorf("failed to read CA. %w", err) } diff --git a/pkg/metrics/influxdb_test.go b/pkg/metrics/influxdb_test.go index 9e0bd1735..124392d06 100644 --- a/pkg/metrics/influxdb_test.go +++ b/pkg/metrics/influxdb_test.go @@ -3,7 +3,7 @@ package metrics import ( "context" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "regexp" @@ -69,7 +69,7 @@ func TestInfluxDB(t *testing.T) { func TestInfluxDBHTTP(t *testing.T) { c := make(chan *string) ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - body, err := ioutil.ReadAll(r.Body) + body, err := io.ReadAll(r.Body) if err != nil { http.Error(w, "can't read body "+err.Error(), http.StatusBadRequest) return diff --git a/pkg/middlewares/accesslog/logger_test.go b/pkg/middlewares/accesslog/logger_test.go index c2449af94..3f37b8312 100644 --- a/pkg/middlewares/accesslog/logger_test.go +++ b/pkg/middlewares/accesslog/logger_test.go @@ -4,7 +4,6 @@ import ( "crypto/tls" "encoding/json" "fmt" - "io/ioutil" "net/http" "net/http/httptest" "net/url" @@ -42,9 +41,7 @@ var ( ) func TestLogRotation(t *testing.T) { - tempDir := createTempDir(t, "traefik_") - - fileName := filepath.Join(tempDir, "traefik.log") + fileName := filepath.Join(t.TempDir(), "traefik.log") rotatedFileName := fileName + ".rotated" config := &types.AccessLog{FilePath: fileName, Format: CommonFormat} @@ -100,7 +97,7 @@ func TestLogRotation(t *testing.T) { func lineCount(t *testing.T, fileName string) int { t.Helper() - fileContents, err := ioutil.ReadFile(fileName) + fileContents, err := os.ReadFile(fileName) if err != nil { t.Fatalf("Error reading from file %s: %s", fileName, err) } @@ -117,8 +114,6 @@ func lineCount(t *testing.T, fileName string) int { } func TestLoggerHeaderFields(t *testing.T) { - tmpDir := createTempDir(t, CommonFormat) - expectedValue := "expectedValue" testCases := []struct { @@ -172,7 +167,7 @@ func TestLoggerHeaderFields(t *testing.T) { for _, test := range testCases { test := test t.Run(test.desc, func(t *testing.T) { - logFile, err := ioutil.TempFile(tmpDir, "*.log") + logFile, err := os.CreateTemp(t.TempDir(), "*.log") require.NoError(t, err) config := &types.AccessLog{ @@ -202,7 +197,7 @@ func TestLoggerHeaderFields(t *testing.T) { writer.WriteHeader(http.StatusOK) })) - logData, err := ioutil.ReadFile(logFile.Name()) + logData, err := os.ReadFile(logFile.Name()) require.NoError(t, err) if test.expected == types.AccessLogDrop { @@ -215,13 +210,11 @@ func TestLoggerHeaderFields(t *testing.T) { } func TestLoggerCLF(t *testing.T) { - tmpDir := createTempDir(t, CommonFormat) - - logFilePath := filepath.Join(tmpDir, logFileNameSuffix) + logFilePath := filepath.Join(t.TempDir(), logFileNameSuffix) config := &types.AccessLog{FilePath: logFilePath, Format: CommonFormat} doLogging(t, config) - logData, err := ioutil.ReadFile(logFilePath) + logData, err := os.ReadFile(logFilePath) require.NoError(t, err) expectedLog := ` TestHost - TestUser [13/Apr/2016:07:14:19 -0700] "POST testpath HTTP/0.0" 123 12 "testReferer" "testUserAgent" 1 "testRouter" "http://127.0.0.1/testService" 1ms` @@ -229,13 +222,11 @@ func TestLoggerCLF(t *testing.T) { } func TestAsyncLoggerCLF(t *testing.T) { - tmpDir := createTempDir(t, CommonFormat) - - logFilePath := filepath.Join(tmpDir, logFileNameSuffix) + logFilePath := filepath.Join(t.TempDir(), logFileNameSuffix) config := &types.AccessLog{FilePath: logFilePath, Format: CommonFormat, BufferingSize: 1024} doLogging(t, config) - logData, err := ioutil.ReadFile(logFilePath) + logData, err := os.ReadFile(logFilePath) require.NoError(t, err) expectedLog := ` TestHost - TestUser [13/Apr/2016:07:14:19 -0700] "POST testpath HTTP/0.0" 123 12 "testReferer" "testUserAgent" 1 "testRouter" "http://127.0.0.1/testService" 1ms` @@ -450,9 +441,7 @@ func TestLoggerJSON(t *testing.T) { t.Run(test.desc, func(t *testing.T) { t.Parallel() - tmpDir := createTempDir(t, JSONFormat) - - logFilePath := filepath.Join(tmpDir, logFileNameSuffix) + logFilePath := filepath.Join(t.TempDir(), logFileNameSuffix) test.config.FilePath = logFilePath if test.tls { @@ -461,7 +450,7 @@ func TestLoggerJSON(t *testing.T) { doLogging(t, test.config) } - logData, err := ioutil.ReadFile(logFilePath) + logData, err := os.ReadFile(logFilePath) require.NoError(t, err) jsonData := make(map[string]interface{}) @@ -675,7 +664,7 @@ func TestNewLogHandlerOutputStdout(t *testing.T) { doLogging(t, test.config) - written, err := ioutil.ReadFile(file.Name()) + written, err := os.ReadFile(file.Name()) require.NoError(t, err, "unable to read captured stdout from file") assertValidLogData(t, test.expectedLog, written) }) @@ -720,7 +709,7 @@ func assertValidLogData(t *testing.T, expected string, logData []byte) { func captureStdout(t *testing.T) (out *os.File, restoreStdout func()) { t.Helper() - file, err := ioutil.TempFile("", "testlogger") + file, err := os.CreateTemp("", "testlogger") require.NoError(t, err, "failed to create temp file") original := os.Stdout @@ -734,17 +723,6 @@ func captureStdout(t *testing.T) (out *os.File, restoreStdout func()) { return file, restoreStdout } -func createTempDir(t *testing.T, prefix string) string { - t.Helper() - - tmpDir, err := ioutil.TempDir("", prefix) - require.NoError(t, err, "failed to create temp dir") - - t.Cleanup(func() { _ = os.RemoveAll(tmpDir) }) - - return tmpDir -} - func doLoggingTLSOpt(t *testing.T, config *types.AccessLog, enableTLS bool) { t.Helper() diff --git a/pkg/middlewares/auth/auth.go b/pkg/middlewares/auth/auth.go index c5891199f..e6c1b6108 100644 --- a/pkg/middlewares/auth/auth.go +++ b/pkg/middlewares/auth/auth.go @@ -1,7 +1,7 @@ package auth import ( - "io/ioutil" + "os" "strings" ) @@ -46,7 +46,7 @@ func loadUsers(fileName string, appendUsers []string) ([]string, error) { } func getLinesFromFile(filename string) ([]string, error) { - dat, err := ioutil.ReadFile(filename) + dat, err := os.ReadFile(filename) if err != nil { return nil, err } diff --git a/pkg/middlewares/auth/basic_auth_test.go b/pkg/middlewares/auth/basic_auth_test.go index 0eb454c9d..9e1b92ad1 100644 --- a/pkg/middlewares/auth/basic_auth_test.go +++ b/pkg/middlewares/auth/basic_auth_test.go @@ -3,7 +3,7 @@ package auth import ( "context" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "os" @@ -66,7 +66,7 @@ func TestBasicAuthSuccess(t *testing.T) { assert.Equal(t, http.StatusOK, res.StatusCode, "they should be equal") - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) require.NoError(t, err) defer res.Body.Close() @@ -97,7 +97,7 @@ func TestBasicAuthUserHeader(t *testing.T) { assert.Equal(t, http.StatusOK, res.StatusCode) - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) require.NoError(t, err) defer res.Body.Close() @@ -128,7 +128,7 @@ func TestBasicAuthHeaderRemoved(t *testing.T) { assert.Equal(t, http.StatusOK, res.StatusCode) - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) require.NoError(t, err) err = res.Body.Close() require.NoError(t, err) @@ -159,7 +159,7 @@ func TestBasicAuthHeaderPresent(t *testing.T) { assert.Equal(t, http.StatusOK, res.StatusCode) - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) require.NoError(t, err) err = res.Body.Close() require.NoError(t, err) @@ -215,9 +215,8 @@ func TestBasicAuthUsersFromFile(t *testing.T) { t.Parallel() // Creates the temporary configuration file with the users - usersFile, err := ioutil.TempFile("", "auth-users") + usersFile, err := os.CreateTemp(t.TempDir(), "auth-users") require.NoError(t, err) - defer os.Remove(usersFile.Name()) _, err = usersFile.Write([]byte(test.userFileContent)) require.NoError(t, err) @@ -250,7 +249,7 @@ func TestBasicAuthUsersFromFile(t *testing.T) { require.Equal(t, http.StatusOK, res.StatusCode, "Cannot authenticate user "+userName) var body []byte - body, err = ioutil.ReadAll(res.Body) + body, err = io.ReadAll(res.Body) require.NoError(t, err) err = res.Body.Close() require.NoError(t, err) @@ -270,7 +269,7 @@ func TestBasicAuthUsersFromFile(t *testing.T) { require.Equal(t, `Basic realm="`+test.realm+`"`, res.Header.Get("WWW-Authenticate")) } - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) require.NoError(t, err) err = res.Body.Close() require.NoError(t, err) diff --git a/pkg/middlewares/auth/digest_auth_test.go b/pkg/middlewares/auth/digest_auth_test.go index 4ba746799..066f80e0f 100644 --- a/pkg/middlewares/auth/digest_auth_test.go +++ b/pkg/middlewares/auth/digest_auth_test.go @@ -3,7 +3,7 @@ package auth import ( "context" "fmt" - "io/ioutil" + "io" "net/http" "net/http/httptest" "os" @@ -93,9 +93,8 @@ func TestDigestAuthUsersFromFile(t *testing.T) { t.Parallel() // Creates the temporary configuration file with the users - usersFile, err := ioutil.TempFile("", "auth-users") + usersFile, err := os.CreateTemp(t.TempDir(), "auth-users") require.NoError(t, err) - defer os.Remove(usersFile.Name()) _, err = usersFile.Write([]byte(test.userFileContent)) require.NoError(t, err) @@ -127,7 +126,7 @@ func TestDigestAuthUsersFromFile(t *testing.T) { require.Equal(t, http.StatusOK, res.StatusCode, "Cannot authenticate user "+userName) var body []byte - body, err = ioutil.ReadAll(res.Body) + body, err = io.ReadAll(res.Body) require.NoError(t, err) err = res.Body.Close() require.NoError(t, err) @@ -145,7 +144,7 @@ func TestDigestAuthUsersFromFile(t *testing.T) { require.Equal(t, http.StatusUnauthorized, res.StatusCode) var body []byte - body, err = ioutil.ReadAll(res.Body) + body, err = io.ReadAll(res.Body) require.NoError(t, err) err = res.Body.Close() require.NoError(t, err) diff --git a/pkg/middlewares/auth/forward.go b/pkg/middlewares/auth/forward.go index 65722316a..ed9e7d2ef 100644 --- a/pkg/middlewares/auth/forward.go +++ b/pkg/middlewares/auth/forward.go @@ -4,7 +4,7 @@ import ( "context" "errors" "fmt" - "io/ioutil" + "io" "net" "net/http" "regexp" @@ -126,7 +126,7 @@ func (fa *forwardAuth) ServeHTTP(rw http.ResponseWriter, req *http.Request) { return } - body, readError := ioutil.ReadAll(forwardResponse.Body) + body, readError := io.ReadAll(forwardResponse.Body) if readError != nil { logMessage := fmt.Sprintf("Error reading body %s. Cause: %s", fa.address, readError) logger.Debug(logMessage) diff --git a/pkg/middlewares/auth/forward_test.go b/pkg/middlewares/auth/forward_test.go index 13a8f5a5f..1aeb5ef9a 100644 --- a/pkg/middlewares/auth/forward_test.go +++ b/pkg/middlewares/auth/forward_test.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "io" - "io/ioutil" "net/http" "net/http/httptest" "testing" @@ -44,7 +43,7 @@ func TestForwardAuthFail(t *testing.T) { require.NoError(t, err) assert.Equal(t, http.StatusForbidden, res.StatusCode) - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) require.NoError(t, err) err = res.Body.Close() require.NoError(t, err) @@ -92,7 +91,7 @@ func TestForwardAuthSuccess(t *testing.T) { require.NoError(t, err) assert.Equal(t, http.StatusOK, res.StatusCode) - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) require.NoError(t, err) err = res.Body.Close() require.NoError(t, err) @@ -134,7 +133,7 @@ func TestForwardAuthRedirect(t *testing.T) { require.NoError(t, err) assert.Equal(t, "http://example.com/redirect-test", location.String()) - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) require.NoError(t, err) err = res.Body.Close() require.NoError(t, err) @@ -187,7 +186,7 @@ func TestForwardAuthRemoveHopByHopHeaders(t *testing.T) { require.NoError(t, err) assert.Equal(t, "http://example.com/redirect-test", location.String(), "they should be equal") - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) require.NoError(t, err) assert.NotEmpty(t, string(body), "there should be something in the body") } @@ -238,7 +237,7 @@ func TestForwardAuthFailResponseHeaders(t *testing.T) { assert.Equal(t, value, res.Header[key]) } - body, err := ioutil.ReadAll(res.Body) + body, err := io.ReadAll(res.Body) require.NoError(t, err) err = res.Body.Close() require.NoError(t, err) @@ -489,5 +488,5 @@ type mockBackend struct { } func (b *mockBackend) Setup(componentName string) (opentracing.Tracer, io.Closer, error) { - return b.Tracer, ioutil.NopCloser(nil), nil + return b.Tracer, io.NopCloser(nil), nil } diff --git a/pkg/middlewares/compress/compress_test.go b/pkg/middlewares/compress/compress_test.go index 93f1d6575..f3b01ed0e 100644 --- a/pkg/middlewares/compress/compress_test.go +++ b/pkg/middlewares/compress/compress_test.go @@ -2,7 +2,7 @@ package compress import ( "context" - "io/ioutil" + "io" "net/http" "net/http/httptest" "testing" @@ -205,7 +205,7 @@ func TestIntegrationShouldNotCompress(t *testing.T) { assert.Equal(t, gzipValue, resp.Header.Get(contentEncodingHeader)) assert.Equal(t, acceptEncodingHeader, resp.Header.Get(varyHeader)) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) assert.EqualValues(t, fakeCompressedBody, body) }) @@ -287,7 +287,7 @@ func TestIntegrationShouldCompress(t *testing.T) { assert.Equal(t, gzipValue, resp.Header.Get(contentEncodingHeader)) assert.Equal(t, acceptEncodingHeader, resp.Header.Get(varyHeader)) - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) require.NoError(t, err) if assert.ObjectsAreEqualValues(body, fakeBody) { assert.Fail(t, "expected a compressed body", "got %v", body) diff --git a/pkg/middlewares/retry/retry.go b/pkg/middlewares/retry/retry.go index 57333d9d3..388b3c2a4 100644 --- a/pkg/middlewares/retry/retry.go +++ b/pkg/middlewares/retry/retry.go @@ -4,7 +4,7 @@ import ( "bufio" "context" "fmt" - "io/ioutil" + "io" "math" "net" "net/http" @@ -73,12 +73,12 @@ func (r *retry) GetTracingInformation() (string, ext.SpanKindEnum) { } func (r *retry) ServeHTTP(rw http.ResponseWriter, req *http.Request) { - // if we might make multiple attempts, swap the body for an ioutil.NopCloser + // if we might make multiple attempts, swap the body for an io.NopCloser // cf https://github.com/traefik/traefik/issues/1008 if r.attempts > 1 { body := req.Body defer body.Close() - req.Body = ioutil.NopCloser(body) + req.Body = io.NopCloser(body) } attempts := 1 diff --git a/pkg/middlewares/retry/retry_test.go b/pkg/middlewares/retry/retry_test.go index 47e97efc6..c0a967f7d 100644 --- a/pkg/middlewares/retry/retry_test.go +++ b/pkg/middlewares/retry/retry_test.go @@ -3,10 +3,10 @@ package retry import ( "context" "fmt" + "io" "net/http" "net/http/httptest" "net/http/httptrace" - "strconv" "strings" "testing" "time" @@ -16,10 +16,7 @@ import ( "github.com/stretchr/testify/require" ptypes "github.com/traefik/paerser/types" "github.com/traefik/traefik/v2/pkg/config/dynamic" - "github.com/traefik/traefik/v2/pkg/middlewares/emptybackendhandler" "github.com/traefik/traefik/v2/pkg/testhelpers" - "github.com/vulcand/oxy/forward" - "github.com/vulcand/oxy/roundrobin" ) func TestRetry(t *testing.T) { @@ -32,14 +29,14 @@ func TestRetry(t *testing.T) { }{ { desc: "no retry on success", - config: dynamic.Retry{Attempts: 1}, + config: dynamic.Retry{Attempts: 5}, wantRetryAttempts: 0, wantResponseStatus: http.StatusOK, amountFaultyEndpoints: 0, }, { desc: "no retry on success with backoff", - config: dynamic.Retry{Attempts: 1, InitialInterval: ptypes.Duration(time.Microsecond * 50)}, + config: dynamic.Retry{Attempts: 5, InitialInterval: ptypes.Duration(time.Microsecond * 50)}, wantRetryAttempts: 0, wantResponseStatus: http.StatusOK, amountFaultyEndpoints: 0, @@ -102,42 +99,28 @@ func TestRetry(t *testing.T) { }, } - backendServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - rw.WriteHeader(http.StatusOK) - _, err := rw.Write([]byte("OK")) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - } - })) - - forwarder, err := forward.New() - require.NoError(t, err) - for _, test := range testCases { test := test t.Run(test.desc, func(t *testing.T) { t.Parallel() - loadBalancer, err := roundrobin.New(forwarder) - require.NoError(t, err) + retryAttemps := 0 + next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + retryAttemps++ - // out of range port - basePort := 1133444 - for i := 0; i < test.amountFaultyEndpoints; i++ { - // 192.0.2.0 is a non-routable IP for testing purposes. - // See: https://stackoverflow.com/questions/528538/non-routable-ip-address/18436928#18436928 - // We only use the port specification here because the URL is used as identifier - // in the load balancer and using the exact same URL would not add a new server. - err = loadBalancer.UpsertServer(testhelpers.MustParseURL("http://192.0.2.0:" + strconv.Itoa(basePort+i))) - require.NoError(t, err) - } + if retryAttemps > test.amountFaultyEndpoints { + // calls WroteHeaders on httptrace. + _ = r.Write(io.Discard) - // add the functioning server to the end of the load balancer list - err = loadBalancer.UpsertServer(testhelpers.MustParseURL(backendServer.URL)) - require.NoError(t, err) + rw.WriteHeader(http.StatusOK) + return + } + + rw.WriteHeader(http.StatusBadGateway) + }) retryListener := &countingRetryListener{} - retry, err := New(context.Background(), loadBalancer, test.config, retryListener, "traefikTest") + retry, err := New(context.Background(), next, test.config, retryListener, "traefikTest") require.NoError(t, err) recorder := httptest.NewRecorder() @@ -152,15 +135,9 @@ func TestRetry(t *testing.T) { } func TestRetryEmptyServerList(t *testing.T) { - forwarder, err := forward.New() - require.NoError(t, err) - - loadBalancer, err := roundrobin.New(forwarder) - require.NoError(t, err) - - // The EmptyBackend middleware ensures that there is a 503 - // response status set when there is no backend server in the pool. - next := emptybackendhandler.New(loadBalancer) + next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + rw.WriteHeader(http.StatusServiceUnavailable) + }) retryListener := &countingRetryListener{} retry, err := New(context.Background(), next, dynamic.Retry{Attempts: 3}, retryListener, "traefikTest") @@ -293,47 +270,29 @@ func TestRetryWebsocket(t *testing.T) { }, } - forwarder, err := forward.New() - if err != nil { - t.Fatalf("Error creating forwarder: %v", err) - } - - backendServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - upgrader := websocket.Upgrader{} - _, err := upgrader.Upgrade(rw, req, nil) - if err != nil { - http.Error(rw, err.Error(), http.StatusInternalServerError) - } - })) - for _, test := range testCases { test := test t.Run(test.desc, func(t *testing.T) { t.Parallel() - loadBalancer, err := roundrobin.New(forwarder) - if err != nil { - t.Fatalf("Error creating load balancer: %v", err) - } + retryAttemps := 0 + next := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + retryAttemps++ - // out of range port - basePort := 1133444 - for i := 0; i < test.amountFaultyEndpoints; i++ { - // 192.0.2.0 is a non-routable IP for testing purposes. - // See: https://stackoverflow.com/questions/528538/non-routable-ip-address/18436928#18436928 - // We only use the port specification here because the URL is used as identifier - // in the load balancer and using the exact same URL would not add a new server. - _ = loadBalancer.UpsertServer(testhelpers.MustParseURL("http://192.0.2.0:" + strconv.Itoa(basePort+i))) - } + if retryAttemps > test.amountFaultyEndpoints { + upgrader := websocket.Upgrader{} + _, err := upgrader.Upgrade(rw, r, nil) + if err != nil { + http.Error(rw, err.Error(), http.StatusInternalServerError) + } + return + } - // add the functioning server to the end of the load balancer list - err = loadBalancer.UpsertServer(testhelpers.MustParseURL(backendServer.URL)) - if err != nil { - t.Fatalf("Fail to upsert server: %v", err) - } + rw.WriteHeader(http.StatusBadGateway) + }) retryListener := &countingRetryListener{} - retryH, err := New(context.Background(), loadBalancer, dynamic.Retry{Attempts: test.maxRequestAttempts}, retryListener, "traefikTest") + retryH, err := New(context.Background(), next, dynamic.Retry{Attempts: test.maxRequestAttempts}, retryListener, "traefikTest") require.NoError(t, err) retryServer := httptest.NewServer(retryH) diff --git a/pkg/pilot/pilot.go b/pkg/pilot/pilot.go index 9edd984c6..7869bd4b5 100644 --- a/pkg/pilot/pilot.go +++ b/pkg/pilot/pilot.go @@ -6,7 +6,7 @@ import ( "encoding/json" "fmt" "hash/fnv" - "io/ioutil" + "io" "net/http" "time" @@ -153,7 +153,7 @@ func (c *client) createUUID() (string, error) { defer resp.Body.Close() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return "", fmt.Errorf("failed read response body: %w", err) } @@ -236,7 +236,7 @@ func (c *client) sendDataRetryable(ctx context.Context, req *http.Request) error defer func() { _ = resp.Body.Close() }() - body, err := ioutil.ReadAll(resp.Body) + body, err := io.ReadAll(resp.Body) if err != nil { return fmt.Errorf("failed to read response body: %w", err) } diff --git a/pkg/plugins/client.go b/pkg/plugins/client.go index da9885492..26c1f801b 100644 --- a/pkg/plugins/client.go +++ b/pkg/plugins/client.go @@ -8,7 +8,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net/http" "net/url" "os" @@ -68,7 +67,7 @@ func NewClient(opts ClientOptions) (*Client, error) { return nil, err } - goPath, err := ioutil.TempDir(sourcesRootPath, "gop-*") + goPath, err := os.MkdirTemp(sourcesRootPath, "gop-*") if err != nil { return nil, fmt.Errorf("failed to create GoPath: %w", err) } @@ -197,7 +196,7 @@ func (c *Client) Download(ctx context.Context, pName, pVersion string) (string, return hash, nil } - data, _ := ioutil.ReadAll(resp.Body) + data, _ := io.ReadAll(resp.Body) return "", fmt.Errorf("error: %d: %s", resp.StatusCode, string(data)) } @@ -353,7 +352,7 @@ func (c *Client) WriteState(plugins map[string]Descriptor) error { return err } - return ioutil.WriteFile(c.stateFile, mp, 0o600) + return os.WriteFile(c.stateFile, mp, 0o600) } // ResetAll resets all plugins related directories. diff --git a/pkg/provider/acme/local_store.go b/pkg/provider/acme/local_store.go index 7078270ae..33084b320 100644 --- a/pkg/provider/acme/local_store.go +++ b/pkg/provider/acme/local_store.go @@ -2,7 +2,7 @@ package acme import ( "encoding/json" - "io/ioutil" + "io" "os" "sync" @@ -60,7 +60,7 @@ func (s *LocalStore) get(resolverName string) (*StoredData, error) { } defer f.Close() - file, err := ioutil.ReadAll(f) + file, err := io.ReadAll(f) if err != nil { return nil, err } @@ -108,7 +108,7 @@ func (s *LocalStore) listenSaveAction() { logger.Error(err) } - err = ioutil.WriteFile(s.filename, data, 0o600) + err = os.WriteFile(s.filename, data, 0o600) if err != nil { logger.Error(err) } diff --git a/pkg/provider/acme/local_store_test.go b/pkg/provider/acme/local_store_test.go index ad3d1cf6c..44d4ab0fc 100644 --- a/pkg/provider/acme/local_store_test.go +++ b/pkg/provider/acme/local_store_test.go @@ -2,7 +2,7 @@ package acme import ( "fmt" - "io/ioutil" + "os" "path/filepath" "testing" "time" @@ -23,7 +23,7 @@ func TestLocalStore_GetAccount(t *testing.T) { } }`, email) - err := ioutil.WriteFile(acmeFile, []byte(filePayload), 0o600) + err := os.WriteFile(acmeFile, []byte(filePayload), 0o600) require.NoError(t, err) testCases := []struct { @@ -68,7 +68,7 @@ func TestLocalStore_SaveAccount(t *testing.T) { time.Sleep(100 * time.Millisecond) - file, err := ioutil.ReadFile(acmeFile) + file, err := os.ReadFile(acmeFile) require.NoError(t, err) expected := `{ diff --git a/pkg/provider/file/file.go b/pkg/provider/file/file.go index e7781d1b8..d6a8847c5 100644 --- a/pkg/provider/file/file.go +++ b/pkg/provider/file/file.go @@ -5,7 +5,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "strings" @@ -197,7 +196,7 @@ func flattenCertificates(ctx context.Context, tlsConfig *dynamic.TLSConfiguratio } func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory string, configuration *dynamic.Configuration) (*dynamic.Configuration, error) { - fileList, err := ioutil.ReadDir(directory) + fileList, err := os.ReadDir(directory) if err != nil { return configuration, fmt.Errorf("unable to read directory %s: %w", directory, err) } @@ -436,7 +435,7 @@ func (p *Provider) decodeConfiguration(filePath, content string) (*dynamic.Confi func readFile(filename string) (string, error) { if len(filename) > 0 { - buf, err := ioutil.ReadFile(filename) + buf, err := os.ReadFile(filename) if err != nil { return "", err } diff --git a/pkg/provider/file/file_test.go b/pkg/provider/file/file_test.go index ca6f36728..6dde44321 100644 --- a/pkg/provider/file/file_test.go +++ b/pkg/provider/file/file_test.go @@ -3,7 +3,6 @@ package file import ( "context" "io" - "io/ioutil" "os" "path/filepath" "strconv" @@ -27,13 +26,12 @@ type ProvideTestCase struct { } func TestTLSContent(t *testing.T) { - tempDir := createTempDir(t, "testdir") - defer os.RemoveAll(tempDir) + tempDir := t.TempDir() fileTLS, err := createTempFile("./fixtures/toml/tls_file.cert", tempDir) require.NoError(t, err) - fileConfig, err := ioutil.TempFile(tempDir, "temp*.toml") + fileConfig, err := os.CreateTemp(tempDir, "temp*.toml") require.NoError(t, err) content := ` @@ -245,7 +243,7 @@ func getTestCases() []ProvideTestCase { func createProvider(t *testing.T, test ProvideTestCase, watch bool) *Provider { t.Helper() - tempDir := createTempDir(t, "testdir") + tempDir := t.TempDir() provider := &Provider{} provider.Watch = true @@ -265,7 +263,7 @@ func createProvider(t *testing.T, test ProvideTestCase, watch bool) *Provider { var file *os.File if watch { var err error - file, err = ioutil.TempFile(tempDir, "temp*"+filepath.Ext(test.filePath)) + file, err = os.CreateTemp(tempDir, "temp*"+filepath.Ext(test.filePath)) require.NoError(t, err) } else { var err error @@ -283,17 +281,6 @@ func createProvider(t *testing.T, test ProvideTestCase, watch bool) *Provider { return provider } -// createTempDir Helper. -func createTempDir(t *testing.T, dir string) string { - t.Helper() - - d, err := ioutil.TempDir("", dir) - if err != nil { - t.Fatal(err) - } - return d -} - func copyFile(srcPath, dstPath string) error { dst, err := os.OpenFile(dstPath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o666) if err != nil { @@ -312,7 +299,7 @@ func copyFile(srcPath, dstPath string) error { } func createTempFile(srcPath, tempDir string) (*os.File, error) { - file, err := ioutil.TempFile(tempDir, "temp*"+filepath.Ext(srcPath)) + file, err := os.CreateTemp(tempDir, "temp*"+filepath.Ext(srcPath)) if err != nil { return nil, err } diff --git a/pkg/provider/http/http.go b/pkg/provider/http/http.go index 37ef0b735..8d1ce329e 100644 --- a/pkg/provider/http/http.go +++ b/pkg/provider/http/http.go @@ -4,7 +4,7 @@ import ( "context" "fmt" "hash/fnv" - "io/ioutil" + "io" "net/http" "time" @@ -139,7 +139,7 @@ func (p *Provider) fetchConfigurationData() ([]byte, error) { return nil, fmt.Errorf("received non-ok response code: %d", res.StatusCode) } - return ioutil.ReadAll(res.Body) + return io.ReadAll(res.Body) } // decodeConfiguration decodes and returns the dynamic configuration from the given data. diff --git a/pkg/provider/kubernetes/crd/client.go b/pkg/provider/kubernetes/crd/client.go index 6ab4c160d..2f2e1b7ad 100644 --- a/pkg/provider/kubernetes/crd/client.go +++ b/pkg/provider/kubernetes/crd/client.go @@ -3,7 +3,6 @@ package crd import ( "errors" "fmt" - "io/ioutil" "os" "path/filepath" "runtime" @@ -147,7 +146,7 @@ func newExternalClusterClient(endpoint, token, caFilePath string) (*clientWrappe } if caFilePath != "" { - caData, err := ioutil.ReadFile(caFilePath) + caData, err := os.ReadFile(caFilePath) if err != nil { return nil, fmt.Errorf("failed to read CA file %s: %w", caFilePath, err) } diff --git a/pkg/provider/kubernetes/crd/client_mock_test.go b/pkg/provider/kubernetes/crd/client_mock_test.go index 21fcff601..07c39f766 100644 --- a/pkg/provider/kubernetes/crd/client_mock_test.go +++ b/pkg/provider/kubernetes/crd/client_mock_test.go @@ -2,7 +2,7 @@ package crd import ( "fmt" - "io/ioutil" + "os" "path/filepath" "github.com/traefik/traefik/v2/pkg/provider/kubernetes/crd/traefik/v1alpha1" @@ -46,7 +46,7 @@ func newClientMock(paths ...string) clientMock { var c clientMock for _, path := range paths { - yamlContent, err := ioutil.ReadFile(filepath.FromSlash("./fixtures/" + path)) + yamlContent, err := os.ReadFile(filepath.FromSlash("./fixtures/" + path)) if err != nil { panic(err) } diff --git a/pkg/provider/kubernetes/crd/kubernetes_test.go b/pkg/provider/kubernetes/crd/kubernetes_test.go index 43e612dc8..9b2fa2e60 100644 --- a/pkg/provider/kubernetes/crd/kubernetes_test.go +++ b/pkg/provider/kubernetes/crd/kubernetes_test.go @@ -2,7 +2,7 @@ package crd import ( "context" - "io/ioutil" + "os" "path/filepath" "testing" "time" @@ -4394,7 +4394,7 @@ func TestCrossNamespace(t *testing.T) { var k8sObjects []runtime.Object var crdObjects []runtime.Object for _, path := range test.paths { - yamlContent, err := ioutil.ReadFile(filepath.FromSlash("./fixtures/" + path)) + yamlContent, err := os.ReadFile(filepath.FromSlash("./fixtures/" + path)) if err != nil { panic(err) } diff --git a/pkg/provider/kubernetes/gateway/client.go b/pkg/provider/kubernetes/gateway/client.go index 1e42194c1..27d99ac2e 100644 --- a/pkg/provider/kubernetes/gateway/client.go +++ b/pkg/provider/kubernetes/gateway/client.go @@ -4,7 +4,7 @@ import ( "context" "errors" "fmt" - "io/ioutil" + "os" "time" "github.com/traefik/traefik/v2/pkg/log" @@ -138,7 +138,7 @@ func newExternalClusterClient(endpoint, token, caFilePath string) (*clientWrappe } if caFilePath != "" { - caData, err := ioutil.ReadFile(caFilePath) + caData, err := os.ReadFile(caFilePath) if err != nil { return nil, fmt.Errorf("failed to read CA file %s: %w", caFilePath, err) } diff --git a/pkg/provider/kubernetes/gateway/client_mock_test.go b/pkg/provider/kubernetes/gateway/client_mock_test.go index 73b7d1eb2..25ff59ac8 100644 --- a/pkg/provider/kubernetes/gateway/client_mock_test.go +++ b/pkg/provider/kubernetes/gateway/client_mock_test.go @@ -2,7 +2,7 @@ package gateway import ( "fmt" - "io/ioutil" + "os" "path/filepath" "github.com/traefik/traefik/v2/pkg/provider/kubernetes/k8s" @@ -43,7 +43,7 @@ func newClientMock(paths ...string) clientMock { var c clientMock for _, path := range paths { - yamlContent, err := ioutil.ReadFile(filepath.FromSlash("./fixtures/" + path)) + yamlContent, err := os.ReadFile(filepath.FromSlash("./fixtures/" + path)) if err != nil { panic(err) } diff --git a/pkg/provider/kubernetes/ingress/client.go b/pkg/provider/kubernetes/ingress/client.go index 6c3c5bb77..a37fc1d4d 100644 --- a/pkg/provider/kubernetes/ingress/client.go +++ b/pkg/provider/kubernetes/ingress/client.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "io/ioutil" "os" "path/filepath" "runtime" @@ -112,7 +111,7 @@ func newExternalClusterClient(endpoint, token, caFilePath string) (*clientWrappe } if caFilePath != "" { - caData, err := ioutil.ReadFile(caFilePath) + caData, err := os.ReadFile(caFilePath) if err != nil { return nil, fmt.Errorf("failed to read CA file %s: %w", caFilePath, err) } diff --git a/pkg/provider/kubernetes/ingress/client_mock_test.go b/pkg/provider/kubernetes/ingress/client_mock_test.go index 9ea62d393..94a282990 100644 --- a/pkg/provider/kubernetes/ingress/client_mock_test.go +++ b/pkg/provider/kubernetes/ingress/client_mock_test.go @@ -2,7 +2,7 @@ package ingress import ( "fmt" - "io/ioutil" + "os" "github.com/hashicorp/go-version" "github.com/traefik/traefik/v2/pkg/provider/kubernetes/k8s" @@ -36,7 +36,7 @@ func newClientMock(serverVersion string, paths ...string) clientMock { c.serverVersion = version.Must(version.NewVersion(serverVersion)) for _, path := range paths { - yamlContent, err := ioutil.ReadFile(path) + yamlContent, err := os.ReadFile(path) if err != nil { panic(err) } diff --git a/pkg/provider/traefik/internal_test.go b/pkg/provider/traefik/internal_test.go index 547955413..1e7d5b282 100644 --- a/pkg/provider/traefik/internal_test.go +++ b/pkg/provider/traefik/internal_test.go @@ -4,7 +4,7 @@ import ( "context" "encoding/json" "flag" - "io/ioutil" + "os" "path/filepath" "testing" @@ -271,11 +271,11 @@ func Test_createConfiguration(t *testing.T) { newJSON, err := json.MarshalIndent(cfg, "", " ") require.NoError(t, err) - err = ioutil.WriteFile(filename, newJSON, 0o644) + err = os.WriteFile(filename, newJSON, 0o644) require.NoError(t, err) } - expectedJSON, err := ioutil.ReadFile(filename) + expectedJSON, err := os.ReadFile(filename) require.NoError(t, err) actualJSON, err := json.MarshalIndent(cfg, "", " ") diff --git a/pkg/server/router/router_test.go b/pkg/server/router/router_test.go index 55db73ccc..1e8710a59 100644 --- a/pkg/server/router/router_test.go +++ b/pkg/server/router/router_test.go @@ -2,7 +2,7 @@ package router import ( "context" - "io/ioutil" + "io" "net/http" "net/http/httptest" "strings" @@ -827,7 +827,7 @@ func BenchmarkRouterServe(b *testing.B) { res := &http.Response{ StatusCode: 200, - Body: ioutil.NopCloser(strings.NewReader("")), + Body: io.NopCloser(strings.NewReader("")), } routersConfig := map[string]*dynamic.Router{ @@ -879,7 +879,7 @@ func BenchmarkRouterServe(b *testing.B) { func BenchmarkService(b *testing.B) { res := &http.Response{ StatusCode: 200, - Body: ioutil.NopCloser(strings.NewReader("")), + Body: io.NopCloser(strings.NewReader("")), } serviceConfig := map[string]*dynamic.Service{ diff --git a/pkg/server/server_entrypoint_tcp_test.go b/pkg/server/server_entrypoint_tcp_test.go index a8845d16b..2e147d353 100644 --- a/pkg/server/server_entrypoint_tcp_test.go +++ b/pkg/server/server_entrypoint_tcp_test.go @@ -48,7 +48,7 @@ func TestShutdownTCP(t *testing.T) { for { _, err := http.ReadRequest(bufio.NewReader(conn)) - if errors.Is(err, io.EOF) || (err != nil && strings.HasSuffix(err.Error(), "use of closed network connection")) { + if errors.Is(err, io.EOF) || (err != nil && errors.Is(err, net.ErrClosed)) { return } require.NoError(t, err) diff --git a/pkg/server/service/loadbalancer/mirror/mirror.go b/pkg/server/service/loadbalancer/mirror/mirror.go index d23979cf3..adecf748d 100644 --- a/pkg/server/service/loadbalancer/mirror/mirror.go +++ b/pkg/server/service/loadbalancer/mirror/mirror.go @@ -7,7 +7,6 @@ import ( "errors" "fmt" "io" - "io/ioutil" "net" "net/http" "sync" @@ -88,7 +87,7 @@ func (m *Mirroring) ServeHTTP(rw http.ResponseWriter, req *http.Request) { } if errors.Is(err, errBodyTooLarge) { - req.Body = ioutil.NopCloser(io.MultiReader(bytes.NewReader(bytesRead), req.Body)) + req.Body = io.NopCloser(io.MultiReader(bytes.NewReader(bytesRead), req.Body)) m.handler.ServeHTTP(rw, req) logger.Debugf("no mirroring, request body larger than allowed size") return @@ -182,7 +181,7 @@ func newReusableRequest(req *http.Request, maxBodySize int64) (*reusableRequest, // unbounded body size if maxBodySize < 0 { - body, err := ioutil.ReadAll(req.Body) + body, err := io.ReadAll(req.Body) if err != nil { return nil, nil, err } @@ -217,7 +216,7 @@ func (rr reusableRequest) clone(ctx context.Context) *http.Request { req := rr.req.Clone(ctx) if rr.body != nil { - req.Body = ioutil.NopCloser(bytes.NewReader(rr.body)) + req.Body = io.NopCloser(bytes.NewReader(rr.body)) } return req diff --git a/pkg/server/service/loadbalancer/mirror/mirror_test.go b/pkg/server/service/loadbalancer/mirror/mirror_test.go index cf1402e37..7353f8bea 100644 --- a/pkg/server/service/loadbalancer/mirror/mirror_test.go +++ b/pkg/server/service/loadbalancer/mirror/mirror_test.go @@ -3,7 +3,7 @@ package mirror import ( "bytes" "context" - "io/ioutil" + "io" "net/http" "net/http/httptest" "sync/atomic" @@ -148,7 +148,7 @@ func TestMirroringWithBody(t *testing.T) { handler := http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { assert.NotNil(t, r.Body) - bb, err := ioutil.ReadAll(r.Body) + bb, err := io.ReadAll(r.Body) assert.NoError(t, err) assert.Equal(t, body, bb) rw.WriteHeader(http.StatusOK) @@ -159,7 +159,7 @@ func TestMirroringWithBody(t *testing.T) { for i := 0; i < numMirrors; i++ { err := mirror.AddMirror(http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { assert.NotNil(t, r.Body) - bb, err := ioutil.ReadAll(r.Body) + bb, err := io.ReadAll(r.Body) assert.NoError(t, err) assert.Equal(t, body, bb) atomic.AddInt32(&countMirror, 1) @@ -213,13 +213,13 @@ func TestCloneRequest(t *testing.T) { // first call cloned := rr.clone(ctx) - body, err := ioutil.ReadAll(cloned.Body) + body, err := io.ReadAll(cloned.Body) assert.NoError(t, err) assert.Equal(t, bb, body) // second call cloned = rr.clone(ctx) - body, err = ioutil.ReadAll(cloned.Body) + body, err = io.ReadAll(cloned.Body) assert.NoError(t, err) assert.Equal(t, bb, body) }) diff --git a/pkg/server/service/proxy_test.go b/pkg/server/service/proxy_test.go index beba3580f..72805f2a1 100644 --- a/pkg/server/service/proxy_test.go +++ b/pkg/server/service/proxy_test.go @@ -1,7 +1,7 @@ package service import ( - "io/ioutil" + "io" "net/http" "net/http/httptest" "strings" @@ -21,7 +21,7 @@ func (t *staticTransport) RoundTrip(r *http.Request) (*http.Response, error) { func BenchmarkProxy(b *testing.B) { res := &http.Response{ StatusCode: 200, - Body: ioutil.NopCloser(strings.NewReader("")), + Body: io.NopCloser(strings.NewReader("")), } w := httptest.NewRecorder() diff --git a/pkg/tls/certificate.go b/pkg/tls/certificate.go index 032c1cb0b..b18f867e3 100644 --- a/pkg/tls/certificate.go +++ b/pkg/tls/certificate.go @@ -4,7 +4,6 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" "os" "sort" "strings" @@ -90,7 +89,7 @@ func (f FileOrContent) Read() ([]byte, error) { var content []byte if f.IsPath() { var err error - content, err = ioutil.ReadFile(f.String()) + content, err = os.ReadFile(f.String()) if err != nil { return nil, err } diff --git a/pkg/types/tls.go b/pkg/types/tls.go index 416136e78..8760a7217 100644 --- a/pkg/types/tls.go +++ b/pkg/types/tls.go @@ -5,7 +5,6 @@ import ( "crypto/tls" "crypto/x509" "fmt" - "io/ioutil" "os" "github.com/traefik/traefik/v2/pkg/log" @@ -34,7 +33,7 @@ func (clientTLS *ClientTLS) CreateTLSConfig(ctx context.Context) (*tls.Config, e var ca []byte if _, errCA := os.Stat(clientTLS.CA); errCA == nil { var err error - ca, err = ioutil.ReadFile(clientTLS.CA) + ca, err = os.ReadFile(clientTLS.CA) if err != nil { return nil, fmt.Errorf("failed to read CA. %w", err) }