diff --git a/.golangci.toml b/.golangci.toml index 70bc7866d..66b1b5e32 100644 --- a/.golangci.toml +++ b/.golangci.toml @@ -49,6 +49,9 @@ "wsl", # Too strict "gomnd", # Too strict "stylecheck", # skip because report issues related to some generated files. + "testpackage", # Too strict + "goerr113", # Too strict + "nestif", # Too many false-positive. ] [issues] @@ -62,7 +65,7 @@ ] [[issues.exclude-rules]] path = "(.+)_test.go" - linters = ["goconst", "funlen"] + linters = ["goconst", "funlen", "godot"] [[issues.exclude-rules]] path = "integration/.+_test.go" text = "Error return value of `cmd\\.Process\\.Kill` is not checked" @@ -105,3 +108,6 @@ [[issues.exclude-rules]] path = "pkg/tracing/tracing.go" text = "printf-like formatting function 'SetErrorWithEvent' should be named 'SetErrorWithEventf'" + [[issues.exclude-rules]] + path = "pkg/log/deprecated.go" + linters = ["godot"] diff --git a/Makefile b/Makefile index c30dceae0..24513ef18 100644 --- a/Makefile +++ b/Makefile @@ -32,7 +32,7 @@ TRAEFIK_ENVS := \ TRAEFIK_MOUNT := -v "$(CURDIR)/$(BIND_DIR):/go/src/github.com/containous/traefik/$(BIND_DIR)" DOCKER_RUN_OPTS := $(TRAEFIK_ENVS) $(TRAEFIK_MOUNT) "$(TRAEFIK_DEV_IMAGE)" DOCKER_NON_INTERACTIVE ?= false -DOCKER_RUN_TRAEFIK := docker run $(INTEGRATION_OPTS) $(if $(DOCKER_NON_INTERACTIVE), , -it) $(DOCKER_RUN_OPTS) +DOCKER_RUN_TRAEFIK := docker run --add-host=host.docker.internal:127.0.0.1 $(INTEGRATION_OPTS) $(if $(DOCKER_NON_INTERACTIVE), , -it) $(DOCKER_RUN_OPTS) DOCKER_RUN_TRAEFIK_NOTTY := docker run $(INTEGRATION_OPTS) $(if $(DOCKER_NON_INTERACTIVE), , -i) $(DOCKER_RUN_OPTS) PRE_TARGET ?= build-dev-image diff --git a/build.Dockerfile b/build.Dockerfile index eb88c53d5..ea5e7893e 100644 --- a/build.Dockerfile +++ b/build.Dockerfile @@ -19,7 +19,7 @@ RUN mkdir -p /usr/local/bin \ && chmod +x /usr/local/bin/go-bindata # Download golangci-lint binary to bin folder in $GOPATH -RUN curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b $GOPATH/bin v1.23.8 +RUN curl -sfL https://install.goreleaser.com/github.com/golangci/golangci-lint.sh | bash -s -- -b $GOPATH/bin v1.26.0 # Download misspell binary to bin folder in $GOPATH RUN curl -sfL https://raw.githubusercontent.com/client9/misspell/master/install-misspell.sh | bash -s -- -b $GOPATH/bin v0.3.4 diff --git a/cmd/context.go b/cmd/context.go index cc25e4aae..35866fec2 100644 --- a/cmd/context.go +++ b/cmd/context.go @@ -7,7 +7,7 @@ import ( "syscall" ) -// ContextWithSignal creates a context canceled when SIGINT or SIGTERM are notified +// ContextWithSignal creates a context canceled when SIGINT or SIGTERM are notified. func ContextWithSignal(ctx context.Context) context.Context { newCtx, cancel := context.WithCancel(ctx) signals := make(chan os.Signal) diff --git a/cmd/healthcheck/healthcheck.go b/cmd/healthcheck/healthcheck.go index d67341039..d71f01281 100644 --- a/cmd/healthcheck/healthcheck.go +++ b/cmd/healthcheck/healthcheck.go @@ -45,7 +45,7 @@ func runCmd(traefikConfiguration *static.Configuration) func(_ []string) error { } } -// Do try to do a healthcheck +// Do try to do a healthcheck. func Do(staticConfiguration static.Configuration) (*http.Response, error) { if staticConfiguration.Ping == nil { return nil, errors.New("please enable `ping` to use health check") diff --git a/cmd/traefik/traefik.go b/cmd/traefik/traefik.go index 3ed086211..5ea34c16c 100644 --- a/cmd/traefik/traefik.go +++ b/cmd/traefik/traefik.go @@ -274,7 +274,7 @@ func switchRouter(routerFactory *server.RouterFactory, acmeProviders []*acme.Pro } } -// initACMEProvider creates an acme provider from the ACME part of globalConfiguration +// initACMEProvider creates an acme provider from the ACME part of globalConfiguration. func initACMEProvider(c *static.Configuration, providerAggregator *aggregator.ProviderAggregator, tlsManager *traefiktls.Manager) []*acme.Provider { challengeStore := acme.NewLocalChallengeStore() localStores := map[string]*acme.LocalStore{} diff --git a/cmd/version/version.go b/cmd/version/version.go index 756306ad7..3b917086e 100644 --- a/cmd/version/version.go +++ b/cmd/version/version.go @@ -17,7 +17,7 @@ Go version: {{.GoVersion}} Built: {{.BuildTime}} OS/Arch: {{.Os}}/{{.Arch}}` -// NewCmd builds a new Version command +// NewCmd builds a new Version command. func NewCmd() *cli.Command { return &cli.Command{ Name: "version", @@ -33,7 +33,7 @@ func NewCmd() *cli.Command { } } -// GetPrint write Printable version +// GetPrint write Printable version. func GetPrint(wr io.Writer) error { tmpl, err := template.New("").Parse(versionTemplate) if err != nil { diff --git a/docs/content/getting-started/install-traefik.md b/docs/content/getting-started/install-traefik.md index fa24837ac..04703c0e6 100644 --- a/docs/content/getting-started/install-traefik.md +++ b/docs/content/getting-started/install-traefik.md @@ -83,7 +83,7 @@ helm install traefik traefik/traefik ```bash tab="Using Helm CLI" helm install --namespace=traefik-v2 \ - --set="additionalArguments={--logs.level=DEBUG}" \ + --set="additionalArguments={--log.level=DEBUG}" \ traefik traefik/traefik ``` diff --git a/docs/content/https/acme.md b/docs/content/https/acme.md index 95d0b8306..dddd74fbc 100644 --- a/docs/content/https/acme.md +++ b/docs/content/https/acme.md @@ -105,13 +105,13 @@ Please check the [configuration examples below](#configuration-examples) for mor ``` ```bash tab="CLI" - --entryPoints.web.address=:80 - --entryPoints.websecure.address=:443 + --entrypoints.web.address=:80 + --entrypoints.websecure.address=:443 # ... - --certificatesResolvers.myresolver.acme.email=your-email@example.com - --certificatesResolvers.myresolver.acme.storage=acme.json + --certificatesresolvers.myresolver.acme.email=your-email@example.com + --certificatesresolvers.myresolver.acme.storage=acme.json # used during the challenge - --certificatesResolvers.myresolver.acme.httpChallenge.entryPoint=web + --certificatesresolvers.myresolver.acme.httpchallenge.entrypoint=web ``` !!! important "Defining a certificates resolver does not result in all routers automatically using it. Each router that is supposed to use the resolver must [reference](../routing/routers/index.md#certresolver) it." @@ -181,7 +181,7 @@ when using the `TLS-ALPN-01` challenge, Traefik must be reachable by Let's Encry ```bash tab="CLI" # ... - --certificatesResolvers.myresolver.acme.tlsChallenge=true + --certificatesresolvers.myresolver.acme.tlschallenge=true ``` ### `httpChallenge` @@ -189,7 +189,7 @@ when using the `TLS-ALPN-01` challenge, Traefik must be reachable by Let's Encry Use the `HTTP-01` challenge to generate and renew ACME certificates by provisioning an HTTP resource under a well-known URI. As described on the Let's Encrypt [community forum](https://community.letsencrypt.org/t/support-for-ports-other-than-80-and-443/3419/72), -when using the `HTTP-01` challenge, `certificatesResolvers.myresolver.acme.httpChallenge.entryPoint` must be reachable by Let's Encrypt through port 80. +when using the `HTTP-01` challenge, `certificatesresolvers.myresolver.acme.httpchallenge.entrypoint` must be reachable by Let's Encrypt through port 80. ??? example "Using an EntryPoint Called web for the `httpChallenge`" @@ -224,10 +224,10 @@ when using the `HTTP-01` challenge, `certificatesResolvers.myresolver.acme.httpC ``` ```bash tab="CLI" - --entryPoints.web.address=:80 - --entryPoints.websecure.address=:443 + --entrypoints.web.address=:80 + --entrypoints.websecure.address=:443 # ... - --certificatesResolvers.myresolver.acme.httpChallenge.entryPoint=web + --certificatesresolvers.myresolver.acme.httpchallenge.entrypoint=web ``` !!! info "" @@ -261,8 +261,8 @@ Use the `DNS-01` challenge to generate and renew ACME certificates by provisioni ```bash tab="CLI" # ... - --certificatesResolvers.myresolver.acme.dnsChallenge.provider=digitalocean - --certificatesResolvers.myresolver.acme.dnsChallenge.delayBeforeCheck=0 + --certificatesresolvers.myresolver.acme.dnschallenge.provider=digitalocean + --certificatesresolvers.myresolver.acme.dnschallenge.delaybeforecheck=0 # ... ``` @@ -294,6 +294,7 @@ For example, `CF_API_EMAIL_FILE=/run/secrets/traefik_cf-api-email` could be used | [CloudXNS](https://www.cloudxns.net) | `cloudxns` | `CLOUDXNS_API_KEY`, `CLOUDXNS_SECRET_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/cloudxns) | | [ConoHa](https://www.conoha.jp) | `conoha` | `CONOHA_TENANT_ID`, `CONOHA_API_USERNAME`, `CONOHA_API_PASSWORD` | [Additional configuration](https://go-acme.github.io/lego/dns/conoha) | | [Constellix](https://constellix.com) | `constellix` | `CONSTELLIX_API_KEY`, `CONSTELLIX_SECRET_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/constellix) | +| [deSEC](https://desec.io) | `desec` | `DESEC_TOKEN` | [Additional configuration](https://go-acme.github.io/lego/dns/desec) | | [DigitalOcean](https://www.digitalocean.com) | `digitalocean` | `DO_AUTH_TOKEN` | [Additional configuration](https://go-acme.github.io/lego/dns/digitalocean) | | [DNSimple](https://dnsimple.com) | `dnsimple` | `DNSIMPLE_OAUTH_TOKEN`, `DNSIMPLE_BASE_URL` | [Additional configuration](https://go-acme.github.io/lego/dns/dnsimple) | | [DNS Made Easy](https://dnsmadeeasy.com) | `dnsmadeeasy` | `DNSMADEEASY_API_KEY`, `DNSMADEEASY_API_SECRET`, `DNSMADEEASY_SANDBOX` | [Additional configuration](https://go-acme.github.io/lego/dns/dnsmadeeasy) | @@ -312,6 +313,7 @@ For example, `CF_API_EMAIL_FILE=/run/secrets/traefik_cf-api-email` could be used | [Glesys](https://glesys.com/) | `glesys` | `GLESYS_API_USER`, `GLESYS_API_KEY`, `GLESYS_DOMAIN` | [Additional configuration](https://go-acme.github.io/lego/dns/glesys) | | [GoDaddy](https://godaddy.com/) | `godaddy` | `GODADDY_API_KEY`, `GODADDY_API_SECRET` | [Additional configuration](https://go-acme.github.io/lego/dns/godaddy) | | [Google Cloud DNS](https://cloud.google.com/dns/docs/) | `gcloud` | `GCE_PROJECT`, Application Default Credentials [^2] [^3], [`GCE_SERVICE_ACCOUNT_FILE`] | [Additional configuration](https://go-acme.github.io/lego/dns/gcloud) | +| [Hetzner](https://hetzner.com) | `hetzner` | `HETZNER_API_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/hetzner) | | [hosting.de](https://www.hosting.de) | `hostingde` | `HOSTINGDE_API_KEY`, `HOSTINGDE_ZONE_NAME` | [Additional configuration](https://go-acme.github.io/lego/dns/hostingde) | | HTTP request | `httpreq` | `HTTPREQ_ENDPOINT`, `HTTPREQ_MODE`, `HTTPREQ_USERNAME`, `HTTPREQ_PASSWORD` [^1] | [Additional configuration](https://go-acme.github.io/lego/dns/httpreq) | | [IIJ](https://www.iij.ad.jp/) | `iij` | `IIJ_API_ACCESS_KEY`, `IIJ_API_SECRET_KEY`, `IIJ_DO_SERVICE_CODE` | [Additional configuration](https://go-acme.github.io/lego/dns/iij) | @@ -321,12 +323,15 @@ For example, `CF_API_EMAIL_FILE=/run/secrets/traefik_cf-api-email` could be used | [Linode](https://www.linode.com) | `linode` | `LINODE_API_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/linode) | | [Linode v4](https://www.linode.com) | `linodev4` | `LINODE_TOKEN` | [Additional configuration](https://go-acme.github.io/lego/dns/linodev4) | | [Liquid Web](https://www.liquidweb.com/) | `liquidweb` | `LIQUID_WEB_PASSWORD`, `LIQUID_WEB_USERNAME`, `LIQUID_WEB_ZONE` | [Additional configuration](https://go-acme.github.io/lego/dns/liquidweb) | +| [LuaDNS](https://luadns.com) | `luadns` | `LUADNS_API_USERNAME`, `LUADNS_API_TOKEN` | [Additional configuration](https://go-acme.github.io/lego/dns/luadns) | | manual | `manual` | none, but you need to run Traefik interactively [^4], turn on debug log to see instructions and press Enter. | | | [MyDNS.jp](https://www.mydns.jp/) | `mydnsjp` | `MYDNSJP_MASTER_ID`, `MYDNSJP_PASSWORD` | [Additional configuration](https://go-acme.github.io/lego/dns/mydnsjp) | +| [Mythic Beasts](https://www.mythic-beasts.com) | `mythicbeasts` | `MYTHICBEASTS_USER_NAME`, `MYTHICBEASTS_PASSWORD` | [Additional configuration](https://go-acme.github.io/lego/dns/mythicbeasts) | | [Namecheap](https://www.namecheap.com) | `namecheap` | `NAMECHEAP_API_USER`, `NAMECHEAP_API_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/namecheap) | | [name.com](https://www.name.com/) | `namedotcom` | `NAMECOM_USERNAME`, `NAMECOM_API_TOKEN`, `NAMECOM_SERVER` | [Additional configuration](https://go-acme.github.io/lego/dns/namedotcom) | | [Namesilo](https://www.namesilo.com/) | `namesilo` | `NAMESILO_API_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/namesilo) | | [Netcup](https://www.netcup.eu/) | `netcup` | `NETCUP_CUSTOMER_NUMBER`, `NETCUP_API_KEY`, `NETCUP_API_PASSWORD` | [Additional configuration](https://go-acme.github.io/lego/dns/netcup) | +| [Netlify](https://www.netlify.com) | `netlify` | `NETLIFY_TOKEN` | [Additional configuration](https://go-acme.github.io/lego/dns/netlify) | | [NIFCloud](https://cloud.nifty.com/service/dns.htm) | `nifcloud` | `NIFCLOUD_ACCESS_KEY_ID`, `NIFCLOUD_SECRET_ACCESS_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/nifcloud) | | [Ns1](https://ns1.com/) | `ns1` | `NS1_API_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/ns1) | | [Open Telekom Cloud](https://cloud.telekom.de) | `otc` | `OTC_DOMAIN_NAME`, `OTC_USER_NAME`, `OTC_PASSWORD`, `OTC_PROJECT_NAME`, `OTC_IDENTITY_ENDPOINT` | [Additional configuration](https://go-acme.github.io/lego/dns/otc) | @@ -349,6 +354,7 @@ For example, `CF_API_EMAIL_FILE=/run/secrets/traefik_cf-api-email` could be used | [Versio](https://www.versio.nl/domeinnamen) | `versio` | `VERSIO_USERNAME`, `VERSIO_PASSWORD` | [Additional configuration](https://go-acme.github.io/lego/dns/versio) | | [Vscale](https://vscale.io/) | `vscale` | `VSCALE_API_TOKEN` | [Additional configuration](https://go-acme.github.io/lego/dns/vscale) | | [VULTR](https://www.vultr.com) | `vultr` | `VULTR_API_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/vultr) | +| [Yandex](https://yandex.com) | `yandex` | `YANDEX_PDD_TOKEN` | [Additional configuration](https://go-acme.github.io/lego/dns/yandex) | | [Zone.ee](https://www.zone.ee) | `zoneee` | `ZONEEE_API_USER`, `ZONEEE_API_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/zoneee) | | [Zonomi](https://zonomi.com) | `zonomi` | `ZONOMI_API_KEY` | [Additional configuration](https://go-acme.github.io/lego/dns/zonomi) | @@ -389,7 +395,7 @@ certificatesResolvers: ```bash tab="CLI" # ... ---certificatesResolvers.myresolver.acme.dnsChallenge.resolvers=1.1.1.1:53,8.8.8.8:53 +--certificatesresolvers.myresolver.acme.dnschallenge.resolvers=1.1.1.1:53,8.8.8.8:53 ``` #### Wildcard Domains @@ -428,7 +434,7 @@ The CA server to use: ```bash tab="CLI" # ... - --certificatesResolvers.myresolver.acme.caServer=https://acme-staging-v02.api.letsencrypt.org/directory + --certificatesresolvers.myresolver.acme.caserver=https://acme-staging-v02.api.letsencrypt.org/directory # ... ``` @@ -456,7 +462,7 @@ certificatesResolvers: ```bash tab="CLI" # ... ---certificatesResolvers.myresolver.acme.storage=acme.json +--certificatesresolvers.myresolver.acme.storage=acme.json # ... ``` @@ -473,7 +479,7 @@ docker run -v "/my/host/acme:/etc/traefik/acme" traefik ``` !!! warning - For concurrency reason, this file cannot be shared across multiple instances of Traefik. + For concurrency reasons, this file cannot be shared across multiple instances of Traefik. ## Fallback diff --git a/docs/content/https/ref-acme.txt b/docs/content/https/ref-acme.txt index e23c14444..27f8942f2 100644 --- a/docs/content/https/ref-acme.txt +++ b/docs/content/https/ref-acme.txt @@ -4,13 +4,13 @@ # # Required # ---certificatesResolvers.myresolver.acme.email=test@example.com +--certificatesresolvers.myresolver.acme.email=test@example.com # File or key used for certificates storage. # # Required # ---certificatesResolvers.myresolver.acme.storage=acme.json +--certificatesresolvers.myresolver.acme.storage=acme.json # CA server to use. # Uncomment the line to use Let's Encrypt's staging server, @@ -19,7 +19,7 @@ # Optional # Default: "https://acme-v02.api.letsencrypt.org/directory" # ---certificatesResolvers.myresolver.acme.caServer=https://acme-staging-v02.api.letsencrypt.org/directory +--certificatesresolvers.myresolver.acme.caserver=https://acme-staging-v02.api.letsencrypt.org/directory # KeyType to use. # @@ -28,38 +28,38 @@ # # Available values : "EC256", "EC384", "RSA2048", "RSA4096", "RSA8192" # ---certificatesResolvers.myresolver.acme.keyType=RSA4096 +--certificatesresolvers.myresolver.acme.keytype=RSA4096 # Use a TLS-ALPN-01 ACME challenge. # # Optional (but recommended) # ---certificatesResolvers.myresolver.acme.tlsChallenge=true +--certificatesresolvers.myresolver.acme.tlschallenge=true # Use a HTTP-01 ACME challenge. # # Optional # ---certificatesResolvers.myresolver.acme.httpChallenge=true +--certificatesresolvers.myresolver.acme.httpchallenge=true # EntryPoint to use for the HTTP-01 challenges. # # Required # ---certificatesResolvers.myresolver.acme.httpChallenge.entryPoint=web +--certificatesresolvers.myresolver.acme.httpchallenge.entrypoint=web # Use a DNS-01 ACME challenge rather than HTTP-01 challenge. # Note: mandatory for wildcard certificate generation. # # Optional # ---certificatesResolvers.myresolver.acme.dnsChallenge=true +--certificatesresolvers.myresolver.acme.dnschallenge=true # DNS provider used. # # Required # ---certificatesResolvers.myresolver.acme.dnsChallenge.provider=digitalocean +--certificatesresolvers.myresolver.acme.dnschallenge.provider=digitalocean # By default, the provider will verify the TXT DNS challenge record before letting ACME verify. # If delayBeforeCheck is greater than zero, this check is delayed for the configured duration in seconds. @@ -68,14 +68,14 @@ # Optional # Default: 0 # ---certificatesResolvers.myresolver.acme.dnsChallenge.delayBeforeCheck=0 +--certificatesresolvers.myresolver.acme.dnschallenge.delaybeforecheck=0 # Use following DNS servers to resolve the FQDN authority. # # Optional # Default: empty # ---certificatesResolvers.myresolver.acme.dnsChallenge.resolvers=1.1.1.1:53,8.8.8.8:53 +--certificatesresolvers.myresolver.acme.dnschallenge.resolvers=1.1.1.1:53,8.8.8.8:53 # Disable the DNS propagation checks before notifying ACME that the DNS challenge is ready. # @@ -85,4 +85,4 @@ # Optional # Default: false # ---certificatesResolvers.myresolver.acme.dnsChallenge.disablePropagationCheck=true +--certificatesresolvers.myresolver.acme.dnschallenge.disablepropagationcheck=true diff --git a/docs/content/middlewares/redirectscheme.md b/docs/content/middlewares/redirectscheme.md index 144007563..8fd2c5e39 100644 --- a/docs/content/middlewares/redirectscheme.md +++ b/docs/content/middlewares/redirectscheme.md @@ -208,7 +208,7 @@ metadata: spec: redirectScheme: # ... - port: 443 + port: "443" ``` ```yaml tab="Consul Catalog" @@ -247,5 +247,7 @@ http: test-redirectscheme: redirectScheme: # ... - port: 443 + port: "443" ``` + +!!! info "Port in this configuration is a string, not a numeric value." diff --git a/docs/content/providers/kubernetes-ingress.md b/docs/content/providers/kubernetes-ingress.md index 8092293dc..cbd27ff28 100644 --- a/docs/content/providers/kubernetes-ingress.md +++ b/docs/content/providers/kubernetes-ingress.md @@ -358,17 +358,3 @@ providers: If one wants to know more about the various aspects of the Ingress spec that Traefik supports, many examples of Ingresses definitions are located in the tests [data](https://github.com/containous/traefik/tree/v2.2/pkg/provider/kubernetes/ingress/fixtures) of the Traefik repository. - -## LetsEncrypt Support with the Ingress Provider - -By design, Traefik is a stateless application, meaning that it only derives its configuration from the environment it runs in, without additional configuration. -For this reason, users can run multiple instances of Traefik at the same time to achieve HA, as is a common pattern in the kubernetes ecosystem. - -When using a single instance of Traefik with LetsEncrypt, no issues should be encountered, however this could be a single point of failure. -Unfortunately, it is not possible to run multiple instances of Traefik 2.0 with LetsEncrypt enabled, because there is no way to ensure that the correct instance of Traefik will receive the challenge request, and subsequent responses. -Previous versions of Traefik used a [KV store](https://docs.traefik.io/v1.7/configuration/acme/#storage) to attempt to achieve this, but due to sub-optimal performance was dropped as a feature in 2.0. - -If you require LetsEncrypt with HA in a kubernetes environment, we recommend using [TraefikEE](https://containo.us/traefikee/) where distributed LetsEncrypt is a supported feature. - -If you are wanting to continue to run Traefik Community Edition, LetsEncrypt HA can be achieved by using a Certificate Controller such as [Cert-Manager](https://docs.cert-manager.io/en/latest/index.html). -When using Cert-Manager to manage certificates, it will create secrets in your namespaces that can be referenced as TLS secrets in your [ingress objects](https://kubernetes.io/docs/concepts/services-networking/ingress/#tls). diff --git a/docs/mkdocs.yml b/docs/mkdocs.yml index 71bf72a1a..35cbe239a 100644 --- a/docs/mkdocs.yml +++ b/docs/mkdocs.yml @@ -26,7 +26,7 @@ theme: prev: 'Previous' next: 'Next' -copyright: "Copyright © 2016-2019 Containous" +copyright: "Copyright © 2016-2020 Containous" google_analytics: - 'UA-51880359-3' diff --git a/go.mod b/go.mod index d209dfb95..6a00e47a2 100644 --- a/go.mod +++ b/go.mod @@ -36,7 +36,7 @@ require ( github.com/fatih/structs v1.1.0 github.com/flynn/go-shlex v0.0.0-20150515145356-3f9db97f8568 // indirect github.com/gambol99/go-marathon v0.0.0-20180614232016-99a156b96fb2 - github.com/go-acme/lego/v3 v3.6.0 + github.com/go-acme/lego/v3 v3.7.0 github.com/go-check/check v0.0.0-00010101000000-000000000000 github.com/go-kit/kit v0.9.0 github.com/golang/protobuf v1.3.4 diff --git a/go.sum b/go.sum index 2220d3105..c809573b2 100644 --- a/go.sum +++ b/go.sum @@ -109,8 +109,8 @@ github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj github.com/armon/go-radix v1.0.0 h1:F4z6KzEeeQIMeLFa97iZU6vupzoecKdU5TX24SNppXI= github.com/armon/go-radix v1.0.0/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= github.com/aws/aws-sdk-go v1.16.23/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= -github.com/aws/aws-sdk-go v1.23.0 h1:ilfJN/vJtFo1XDFxB2YMBYGeOvGZl6Qow17oyD4+Z9A= -github.com/aws/aws-sdk-go v1.23.0/go.mod h1:KmX6BPdI08NWTb3/sm4ZGu5ShLoqVDhKgpiN924inxo= +github.com/aws/aws-sdk-go v1.30.20 h1:ktsy2vodSZxz/arYqo7DlpkIeNohHL+4Rmjdo7YGtrE= +github.com/aws/aws-sdk-go v1.30.20/go.mod h1:5zCpMtNQVjRREroY7sYe8lOMRSxkhG6MZveU8YkpAk0= github.com/beorn7/perks v0.0.0-20180321164747-3a771d992973/go.mod h1:Dwedo/Wpr24TaqPxmxbtue+5NUziq4I4S80YR8gNf3Q= github.com/beorn7/perks v1.0.0/go.mod h1:KWe93zE9D1o94FZ5RNwFwVgaQK1VOXiVxmqh+CedLV8= github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM= @@ -182,8 +182,8 @@ github.com/dimchansky/utfbom v1.1.0 h1:FcM3g+nofKgUteL8dm/UpdRXNC9KmADgTpLKsu0TR github.com/dimchansky/utfbom v1.1.0/go.mod h1:rO41eb7gLfo8SF1jd9F8HplJm1Fewwi4mQvIirEdv+8= github.com/dnaeon/go-vcr v0.0.0-20180814043457-aafff18a5cc2 h1:G9/PqfhOrt8JXnw0DGTfVoOkKHDhOlEZqhE/cu+NvQM= github.com/dnaeon/go-vcr v0.0.0-20180814043457-aafff18a5cc2/go.mod h1:aBB1+wY4s93YsC3HHjMBMrwTj2R9FHDzUr9KyGc8n1E= -github.com/dnsimple/dnsimple-go v0.30.0 h1:IBIrn9jMKRMwporIRwdFyKdnHXVmwy6obnguB+ZMDIY= -github.com/dnsimple/dnsimple-go v0.30.0/go.mod h1:O5TJ0/U6r7AfT8niYNlmohpLbCSG+c71tQlGr9SeGrg= +github.com/dnsimple/dnsimple-go v0.60.0 h1:N+q+ML1CZGf+5r4udu9Opy7WJNtOaFT9aM86Af9gLhk= +github.com/dnsimple/dnsimple-go v0.60.0/go.mod h1:O5TJ0/U6r7AfT8niYNlmohpLbCSG+c71tQlGr9SeGrg= github.com/docker/cli v0.0.0-20200221155518-740919cc7fc0 h1:hlGHcYGaaHs/yffSubcUKlp8TyV1v7qhcZZ5nGNQ2Fw= github.com/docker/cli v0.0.0-20200221155518-740919cc7fc0/go.mod h1:JLrzqnKDaYBop7H2jaqPtU4hHvMKP+vjCwu2uszcLI8= github.com/docker/distribution v2.7.1+incompatible h1:a5mlkVzth6W5A4fOsS3D2EO5BUmsJpcB+cRlLU7cSug= @@ -247,8 +247,8 @@ github.com/gambol99/go-marathon v0.0.0-20180614232016-99a156b96fb2/go.mod h1:GLy github.com/ghodss/yaml v0.0.0-20150909031657-73d445a93680/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= -github.com/go-acme/lego/v3 v3.6.0 h1:Rv0MrX3DpVp9Xg77yR7x+PCksLLph3Ut/69/9Kim8ac= -github.com/go-acme/lego/v3 v3.6.0/go.mod h1:sB/T7hfyz0HYIBvPmz/C8jIaxF6scbbiGKTzbQ22V6A= +github.com/go-acme/lego/v3 v3.7.0 h1:qC5/8/CbltyAE8fGLE6bGlqucj7pXc/vBxiLwLOsmAQ= +github.com/go-acme/lego/v3 v3.7.0/go.mod h1:4eDjjYkAsDXyNcwN8IhhZAwxz9Ltiks1Zmpv0q20J7A= github.com/go-cmd/cmd v1.0.5/go.mod h1:y8q8qlK5wQibcw63djSl/ntiHUHXHGdCkPk0j4QeW4s= github.com/go-errors/errors v1.0.1 h1:LUHzmkK3GUKUrL/1gfBUxAHzcev3apQlezX/+O7ma6w= github.com/go-errors/errors v1.0.1/go.mod h1:f4zRHt4oKfwPJE5k8C9vpYG+aDHdBFUsgrm6/TyX73Q= @@ -277,6 +277,7 @@ github.com/go-openapi/swag v0.0.0-20160704191624-1d0bd113de87/go.mod h1:DXUve3Dp github.com/go-openapi/swag v0.19.2/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= github.com/go-openapi/swag v0.19.5 h1:lTz6Ys4CmqqCQmZPBlbQENR1/GucA2bzYTE12Pw4tFY= github.com/go-openapi/swag v0.19.5/go.mod h1:POnQmlKehdgb5mhVOsnJFsivZCEZ/vjK9gh66Z9tfKk= +github.com/go-sql-driver/mysql v1.5.0/go.mod h1:DCzpHaOWr8IXmIStZouvnhqoel9Qv2LBy8hT2VhHyBg= github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk= github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= github.com/godbus/dbus v0.0.0-20190422162347-ade71ed3457e/go.mod h1:bBOAhwG1umN6/6ZUMtDFBMQR8jRg9O75tm9K00oMsK4= @@ -425,6 +426,8 @@ github.com/jcmturner/gofork v0.0.0-20190328161633-dc7c13fece03/go.mod h1:MK8+TM0 github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af h1:pmfjZENx5imkbgOkpRUYLnmbU7UEFbjtDA2hxJ1ichM= github.com/jmespath/go-jmespath v0.0.0-20180206201540-c2b33e8439af/go.mod h1:Nht3zPeWKUH0NzdCt2Blrr5ys8VGpn0CEB0cQHVjt7k= +github.com/jmespath/go-jmespath v0.3.0 h1:OS12ieG61fsCg5+qLJ+SsW9NicxNkg3b25OyT2yCeUc= +github.com/jmespath/go-jmespath v0.3.0/go.mod h1:9QtRXoHjLGCJ5IBSaohpXITPlowMeeYCZ7fLUTSywik= github.com/joeshaw/multierror v0.0.0-20140124173710-69b34d4ec901 h1:rp+c0RAYOWj8l6qbCUTSiRLG/iKnW3K3/QfPPuSsBt4= github.com/joeshaw/multierror v0.0.0-20140124173710-69b34d4ec901/go.mod h1:Z86h9688Y0wesXCyonoVr47MasHilkuLMqGhRZ4Hpak= github.com/jonboulle/clockwork v0.1.0 h1:VKV+ZcuP6l3yW9doeqz6ziZGgcynBVQO+obU0+0hcPo= @@ -587,6 +590,8 @@ github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi github.com/pkg/errors v0.8.0/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= +github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/profile v1.2.1/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= diff --git a/integration/access_log_test.go b/integration/access_log_test.go index 61433a12a..31e52e306 100644 --- a/integration/access_log_test.go +++ b/integration/access_log_test.go @@ -24,7 +24,7 @@ const ( traefikTestAccessLogFile = "access.log" ) -// AccessLogSuite +// AccessLogSuite tests suite. type AccessLogSuite struct{ BaseSuite } type accessLogValue struct { @@ -562,7 +562,7 @@ func extractLines(c *check.C) []string { func checkStatsForLogFile(c *check.C) { err := try.Do(1*time.Second, func() error { if _, errStat := os.Stat(traefikTestLogFile); errStat != nil { - return fmt.Errorf("could not get stats for log file: %s", errStat) + return fmt.Errorf("could not get stats for log file: %w", errStat) } return nil }) diff --git a/integration/acme_test.go b/integration/acme_test.go index d253b3ace..a5e34e695 100644 --- a/integration/acme_test.go +++ b/integration/acme_test.go @@ -20,7 +20,7 @@ import ( checker "github.com/vdemeester/shakers" ) -// ACME test suites (using libcompose) +// ACME test suites (using libcompose). type AcmeSuite struct { BaseSuite pebbleIP string @@ -74,7 +74,7 @@ func setupPebbleRootCA() (*http.Transport, error) { certPool := x509.NewCertPool() if ok := certPool.AppendCertsFromPEM(customCAs); !ok { - return nil, fmt.Errorf("error creating x509 cert pool from %q: %v", path, err) + return nil, fmt.Errorf("error creating x509 cert pool from %q: %w", path, err) } return &http.Transport{ @@ -394,7 +394,7 @@ func (s *AcmeSuite) TestTLSALPN01DomainsInSAN(c *check.C) { s.retrieveAcmeCertificate(c, testCase) } -// Test Let's encrypt down +// Test Let's encrypt down. func (s *AcmeSuite) TestNoValidLetsEncryptServer(c *check.C) { file := s.adaptFile(c, "fixtures/acme/acme_base.toml", templateModel{ Acme: map[string]static.CertificateResolver{ @@ -417,7 +417,7 @@ func (s *AcmeSuite) TestNoValidLetsEncryptServer(c *check.C) { c.Assert(err, checker.IsNil) } -// Doing an HTTPS request and test the response certificate +// Doing an HTTPS request and test the response certificate. func (s *AcmeSuite) retrieveAcmeCertificate(c *check.C, testCase acmeTestCase) { if len(testCase.template.PortHTTP) == 0 { testCase.template.PortHTTP = ":5002" diff --git a/integration/consul_catalog_test.go b/integration/consul_catalog_test.go index d7918f4c0..c9424f479 100644 --- a/integration/consul_catalog_test.go +++ b/integration/consul_catalog_test.go @@ -47,7 +47,7 @@ func (s *ConsulCatalogSuite) waitToElectConsulLeader() error { leader, err := s.consulClient.Status().Leader() if err != nil || len(leader) == 0 { - return fmt.Errorf("leader not found. %v", err) + return fmt.Errorf("leader not found. %w", err) } return nil diff --git a/integration/consul_test.go b/integration/consul_test.go index 4da3ff271..d0496b9ca 100644 --- a/integration/consul_test.go +++ b/integration/consul_test.go @@ -19,7 +19,7 @@ import ( checker "github.com/vdemeester/shakers" ) -// Consul test suites (using libcompose) +// Consul test suites (using libcompose). type ConsulSuite struct { BaseSuite kvClient store.Store diff --git a/integration/docker_compose_test.go b/integration/docker_compose_test.go index 5c5e1fc5a..7e1022ac8 100644 --- a/integration/docker_compose_test.go +++ b/integration/docker_compose_test.go @@ -18,7 +18,7 @@ const ( composeProject = "minimal" ) -// Docker test suites +// Docker tests suite. type DockerComposeSuite struct { BaseSuite } diff --git a/integration/docker_test.go b/integration/docker_test.go index 9e5db3972..2116cebaa 100644 --- a/integration/docker_test.go +++ b/integration/docker_test.go @@ -17,14 +17,14 @@ import ( checker "github.com/vdemeester/shakers" ) -// Images to have or pull before the build in order to make it work -// FIXME handle this offline but loading them before build +// Images to have or pull before the build in order to make it work. +// FIXME handle this offline but loading them before build. var RequiredImages = map[string]string{ "swarm": "1.0.0", "containous/whoami": "latest", } -// Docker test suites +// Docker tests suite. type DockerSuite struct { BaseSuite project *docker.Project diff --git a/integration/error_pages_test.go b/integration/error_pages_test.go index 5b218bbe8..111b30a15 100644 --- a/integration/error_pages_test.go +++ b/integration/error_pages_test.go @@ -10,7 +10,7 @@ import ( checker "github.com/vdemeester/shakers" ) -// ErrorPagesSuite test suites (using libcompose) +// ErrorPagesSuite test suites (using libcompose). type ErrorPagesSuite struct { BaseSuite ErrorPageIP string diff --git a/integration/etcd_test.go b/integration/etcd_test.go index 79c6a663f..b0bd07902 100644 --- a/integration/etcd_test.go +++ b/integration/etcd_test.go @@ -19,7 +19,7 @@ import ( checker "github.com/vdemeester/shakers" ) -// etcd test suites (using libcompose) +// etcd test suites (using libcompose). type EtcdSuite struct { BaseSuite kvClient store.Store diff --git a/integration/file_test.go b/integration/file_test.go index 85079b4e0..07b289d6f 100644 --- a/integration/file_test.go +++ b/integration/file_test.go @@ -10,7 +10,7 @@ import ( checker "github.com/vdemeester/shakers" ) -// File test suites +// File tests suite. type FileSuite struct{ BaseSuite } func (s *FileSuite) SetUpSuite(c *check.C) { @@ -32,7 +32,7 @@ func (s *FileSuite) TestSimpleConfiguration(c *check.C) { c.Assert(err, checker.IsNil) } -// #56 regression test, make sure it does not fail +// #56 regression test, make sure it does not fail? func (s *FileSuite) TestSimpleConfigurationNoPanic(c *check.C) { cmd, display := s.traefikCmd(withConfigFile("fixtures/file/56-simple-panic.toml")) defer display(c) diff --git a/integration/grpc_test.go b/integration/grpc_test.go index db61999b6..1a25931a8 100644 --- a/integration/grpc_test.go +++ b/integration/grpc_test.go @@ -24,7 +24,7 @@ var LocalhostKey []byte const randCharset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" -// GRPCSuite +// GRPCSuite tests suite. type GRPCSuite struct{ BaseSuite } type myserver struct { diff --git a/integration/headers_test.go b/integration/headers_test.go index 8d5194abd..34df16a78 100644 --- a/integration/headers_test.go +++ b/integration/headers_test.go @@ -10,7 +10,7 @@ import ( checker "github.com/vdemeester/shakers" ) -// Headers test suites +// Headers tests suite. type HeadersSuite struct{ BaseSuite } func (s *HeadersSuite) TestSimpleConfiguration(c *check.C) { diff --git a/integration/healthcheck_test.go b/integration/healthcheck_test.go index 16d17a0ba..46c400edf 100644 --- a/integration/healthcheck_test.go +++ b/integration/healthcheck_test.go @@ -11,7 +11,7 @@ import ( checker "github.com/vdemeester/shakers" ) -// HealthCheck test suites (using libcompose) +// HealthCheck test suites (using libcompose). type HealthCheckSuite struct { BaseSuite whoami1IP string @@ -206,7 +206,7 @@ func (s *HealthCheckSuite) TestPortOverload(c *check.C) { c.Assert(err, checker.IsNil) } -// Checks if all the loadbalancers created will correctly update the server status +// Checks if all the loadbalancers created will correctly update the server status. func (s *HealthCheckSuite) TestMultipleRoutersOnSameService(c *check.C) { file := s.adaptFile(c, "fixtures/healthcheck/multiple-routers-one-same-service.toml", struct { Server1 string diff --git a/integration/https_test.go b/integration/https_test.go index efb7fb017..bf19cb30c 100644 --- a/integration/https_test.go +++ b/integration/https_test.go @@ -18,7 +18,7 @@ import ( checker "github.com/vdemeester/shakers" ) -// HTTPSSuite +// HTTPSSuite tests suite. type HTTPSSuite struct{ BaseSuite } // TestWithSNIConfigHandshake involves a client sending a SNI hostname of @@ -441,7 +441,7 @@ func (s *HTTPSSuite) TestWithOverlappingDynamicCertificate(c *check.C) { } // TestWithClientCertificateAuthentication -// The client can send a certificate signed by a CA trusted by the server but it's optional +// The client can send a certificate signed by a CA trusted by the server but it's optional. func (s *HTTPSSuite) TestWithClientCertificateAuthentication(c *check.C) { file := s.adaptFile(c, "fixtures/https/clientca/https_1ca1config.toml", struct{}{}) defer os.Remove(file) @@ -499,7 +499,7 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthentication(c *check.C) { } // TestWithClientCertificateAuthentication -// Use two CA:s and test that clients with client signed by either of them can connect +// Use two CA:s and test that clients with client signed by either of them can connect. func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipleCAs(c *check.C) { server1 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { _, _ = rw.Write([]byte("server1")) })) server2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { _, _ = rw.Write([]byte("server2")) })) @@ -596,7 +596,7 @@ func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipleCAs(c *check } // TestWithClientCertificateAuthentication -// Use two CA:s in two different files and test that clients with client signed by either of them can connect +// Use two CA:s in two different files and test that clients with client signed by either of them can connect. func (s *HTTPSSuite) TestWithClientCertificateAuthenticationMultipleCAsMultipleFiles(c *check.C) { server1 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { _, _ = rw.Write([]byte("server1")) })) server2 := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, _ *http.Request) { _, _ = rw.Write([]byte("server2")) })) diff --git a/integration/k8s_test.go b/integration/k8s_test.go index 966dd26ed..36cd3e54e 100644 --- a/integration/k8s_test.go +++ b/integration/k8s_test.go @@ -24,7 +24,7 @@ import ( var updateExpected = flag.Bool("update_expected", false, "Update expected files in testdata") -// K8sSuite +// K8sSuite tests suite. type K8sSuite struct{ BaseSuite } func (s *K8sSuite) SetUpSuite(c *check.C) { @@ -128,7 +128,7 @@ func matchesConfig(wantConfig string, buf *bytes.Buffer) try.ResponseCondition { return func(res *http.Response) error { body, err := ioutil.ReadAll(res.Body) if err != nil { - return fmt.Errorf("failed to read response body: %s", err) + return fmt.Errorf("failed to read response body: %w", err) } if err := res.Body.Close(); err != nil { diff --git a/integration/log_rotation_test.go b/integration/log_rotation_test.go index b5b872f16..8132cb250 100644 --- a/integration/log_rotation_test.go +++ b/integration/log_rotation_test.go @@ -16,7 +16,7 @@ import ( checker "github.com/vdemeester/shakers" ) -// Log rotation integration test suite +// Log rotation integration test suite. type LogRotationSuite struct{ BaseSuite } func (s *LogRotationSuite) SetUpSuite(c *check.C) { diff --git a/integration/marathon15_test.go b/integration/marathon15_test.go index a15ce8e85..fb454f071 100644 --- a/integration/marathon15_test.go +++ b/integration/marathon15_test.go @@ -12,7 +12,7 @@ import ( checker "github.com/vdemeester/shakers" ) -// Marathon test suites (using libcompose) +// Marathon test suites (using libcompose). type MarathonSuite15 struct { BaseSuite marathonURL string diff --git a/integration/marathon_test.go b/integration/marathon_test.go index b0406bf9c..62f4d0bfa 100644 --- a/integration/marathon_test.go +++ b/integration/marathon_test.go @@ -17,7 +17,7 @@ const ( containerNameMarathon = "marathon" ) -// Marathon test suites (using libcompose) +// Marathon test suites (using libcompose). type MarathonSuite struct { BaseSuite marathonURL string diff --git a/integration/redis_test.go b/integration/redis_test.go index 6c2f4bcfa..91022cdad 100644 --- a/integration/redis_test.go +++ b/integration/redis_test.go @@ -19,7 +19,7 @@ import ( checker "github.com/vdemeester/shakers" ) -// Redis test suites (using libcompose) +// Redis test suites (using libcompose). type RedisSuite struct { BaseSuite kvClient store.Store diff --git a/integration/simple_test.go b/integration/simple_test.go index 4af8fdf39..75f692faf 100644 --- a/integration/simple_test.go +++ b/integration/simple_test.go @@ -20,7 +20,7 @@ import ( checker "github.com/vdemeester/shakers" ) -// SimpleSuite +// SimpleSuite tests suite. type SimpleSuite struct{ BaseSuite } func (s *SimpleSuite) TestInvalidConfigShouldFail(c *check.C) { diff --git a/integration/try/condition.go b/integration/try/condition.go index d7d94c4ee..a2619a28b 100644 --- a/integration/try/condition.go +++ b/integration/try/condition.go @@ -12,18 +12,16 @@ import ( ) // ResponseCondition is a retry condition function. -// It receives a response, and returns an error -// if the response failed the condition. +// It receives a response, and returns an error if the response failed the condition. type ResponseCondition func(*http.Response) error // BodyContains returns a retry condition function. -// The condition returns an error if the request body does not contain all the given -// strings. +// 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) if err != nil { - return fmt.Errorf("failed to read response body: %s", err) + return fmt.Errorf("failed to read response body: %w", err) } for _, value := range values { @@ -36,13 +34,12 @@ func BodyContains(values ...string) ResponseCondition { } // BodyNotContains returns a retry condition function. -// The condition returns an error if the request body contain one of the given -// strings. +// 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) if err != nil { - return fmt.Errorf("failed to read response body: %s", err) + return fmt.Errorf("failed to read response body: %w", err) } for _, value := range values { @@ -55,13 +52,12 @@ func BodyNotContains(values ...string) ResponseCondition { } // BodyContainsOr returns a retry condition function. -// The condition returns an error if the request body does not contain one of the given -// strings. +// 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) if err != nil { - return fmt.Errorf("failed to read response body: %s", err) + return fmt.Errorf("failed to read response body: %w", err) } for _, value := range values { @@ -79,7 +75,7 @@ func HasBody() ResponseCondition { return func(res *http.Response) error { body, err := ioutil.ReadAll(res.Body) if err != nil { - return fmt.Errorf("failed to read response body: %s", err) + return fmt.Errorf("failed to read response body: %w", err) } if len(body) == 0 { @@ -182,11 +178,11 @@ func HasHeaderStruct(header http.Header) ResponseCondition { } // DoCondition is a retry condition function. -// It returns an error +// It returns an error. type DoCondition func() error // KVExists is a retry condition function. -// Verify if a Key exists in the store +// Verify if a Key exists in the store. func KVExists(kv store.Store, key string) DoCondition { return func() error { _, err := kv.Exists(key, nil) diff --git a/integration/try/try.go b/integration/try/try.go index f9f982dbf..98231626b 100644 --- a/integration/try/try.go +++ b/integration/try/try.go @@ -115,7 +115,7 @@ func Do(timeout time.Duration, operation DoCondition) error { select { case <-stopTimer.C: fmt.Println("-") - return fmt.Errorf("try operation failed: %s", err) + return fmt.Errorf("try operation failed: %w", err) case <-retryTick.C: fmt.Print("*") if err = operation(); err == nil { diff --git a/integration/websocket_test.go b/integration/websocket_test.go index 99b0a77e5..bfdfea3f9 100644 --- a/integration/websocket_test.go +++ b/integration/websocket_test.go @@ -18,7 +18,7 @@ import ( "golang.org/x/net/websocket" ) -// WebsocketSuite +// WebsocketSuite tests suite. type WebsocketSuite struct{ BaseSuite } func (s *WebsocketSuite) TestBase(c *check.C) { diff --git a/integration/zk_test.go b/integration/zk_test.go index 422ad1d80..bc9ecc9f3 100644 --- a/integration/zk_test.go +++ b/integration/zk_test.go @@ -19,7 +19,7 @@ import ( checker "github.com/vdemeester/shakers" ) -// Zk test suites (using libcompose) +// Zk test suites (using libcompose). type ZookeeperSuite struct { BaseSuite kvClient store.Store diff --git a/pkg/anonymize/anonymize.go b/pkg/anonymize/anonymize.go index f955985aa..8b2191d52 100644 --- a/pkg/anonymize/anonymize.go +++ b/pkg/anonymize/anonymize.go @@ -15,7 +15,7 @@ const ( maskLarge = maskShort + maskShort + maskShort + maskShort + maskShort + maskShort + maskShort + maskShort ) -// Do configuration. +// Do sends configuration. func Do(baseConfig interface{}, indent bool) (string, error) { anomConfig, err := copystructure.Copy(baseConfig) if err != nil { @@ -120,7 +120,7 @@ func reset(field reflect.Value, name string) error { return nil } -// isExported return true is a struct field is exported, else false +// isExported return true is a struct field is exported, else false. func isExported(f reflect.StructField) bool { if f.PkgPath != "" && !f.Anonymous { return false diff --git a/pkg/api/dashboard.go b/pkg/api/dashboard.go index 1e2ef460d..e71252e48 100644 --- a/pkg/api/dashboard.go +++ b/pkg/api/dashboard.go @@ -8,12 +8,12 @@ import ( "github.com/gorilla/mux" ) -// DashboardHandler expose dashboard routes +// DashboardHandler expose dashboard routes. type DashboardHandler struct { Assets *assetfs.AssetFS } -// Append add dashboard routes on a router +// Append add dashboard routes on a router. func (g DashboardHandler) Append(router *mux.Router) { if g.Assets == nil { log.WithoutContext().Error("No assets for dashboard") diff --git a/pkg/api/debug.go b/pkg/api/debug.go index e9c7f8abc..448b7c7ee 100644 --- a/pkg/api/debug.go +++ b/pkg/api/debug.go @@ -19,10 +19,10 @@ func goroutines() interface{} { return runtime.NumGoroutine() } -// DebugHandler expose debug routes +// DebugHandler expose debug routes. type DebugHandler struct{} -// Append add debug routes on a router +// Append add debug routes on a router. func (g DebugHandler) Append(router *mux.Router) { router.Methods(http.MethodGet).Path("/debug/vars"). HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { diff --git a/pkg/api/handler.go b/pkg/api/handler.go index f62419ea9..be1905858 100644 --- a/pkg/api/handler.go +++ b/pkg/api/handler.go @@ -55,7 +55,7 @@ type Handler struct { runtimeConfiguration *runtime.Configuration } -// NewBuilder returns a http.Handler builder based on runtime.Configuration +// NewBuilder returns a http.Handler builder based on runtime.Configuration. func NewBuilder(staticConfig static.Configuration) func(*runtime.Configuration) http.Handler { return func(configuration *runtime.Configuration) http.Handler { return New(staticConfig, configuration).createRouter() diff --git a/pkg/cli/commands.go b/pkg/cli/commands.go index 8151f3c26..917c1bfff 100644 --- a/pkg/cli/commands.go +++ b/pkg/cli/commands.go @@ -55,7 +55,7 @@ func execute(cmd *Command, args []string, root bool) error { // Calls command without args. if len(args) == 1 { if err := run(cmd, args[1:]); err != nil { - return fmt.Errorf("command %s error: %v", args[0], err) + return fmt.Errorf("command %s error: %w", args[0], err) } return nil } @@ -65,7 +65,7 @@ func execute(cmd *Command, args []string, root bool) error { // then we run the top level command itself. if root && cmd.Name != args[1] && !contains(cmd.subCommands, args[1]) { if err := run(cmd, args[1:]); err != nil { - return fmt.Errorf("command %s error: %v", filepath.Base(args[0]), err) + return fmt.Errorf("command %s error: %w", filepath.Base(args[0]), err) } return nil } @@ -74,7 +74,7 @@ func execute(cmd *Command, args []string, root bool) error { if len(args) >= 2 && cmd.Name == args[1] { if len(args) < 3 || !contains(cmd.subCommands, args[2]) { if err := run(cmd, args[2:]); err != nil { - return fmt.Errorf("command %s error: %v", cmd.Name, err) + return fmt.Errorf("command %s error: %w", cmd.Name, err) } return nil } @@ -83,7 +83,7 @@ func execute(cmd *Command, args []string, root bool) error { // No sub-command, calls the current command. if len(cmd.subCommands) == 0 { if err := run(cmd, args[1:]); err != nil { - return fmt.Errorf("command %s error: %v", cmd.Name, err) + return fmt.Errorf("command %s error: %w", cmd.Name, err) } return nil } diff --git a/pkg/cli/loader_env.go b/pkg/cli/loader_env.go index c622a6821..ae605f684 100644 --- a/pkg/cli/loader_env.go +++ b/pkg/cli/loader_env.go @@ -21,7 +21,7 @@ func (e *EnvLoader) Load(_ []string, cmd *Command) (bool, error) { if err := env.Decode(vars, env.DefaultNamePrefix, cmd.Configuration); err != nil { log.WithoutContext().Debug("environment variables", strings.Join(vars, ", ")) - return false, fmt.Errorf("failed to decode configuration from environment variables: %v ", err) + return false, fmt.Errorf("failed to decode configuration from environment variables: %w ", err) } log.WithoutContext().Println("Configuration loaded from environment variables.") diff --git a/pkg/cli/loader_flag.go b/pkg/cli/loader_flag.go index 36ce0b521..494f7ad5f 100644 --- a/pkg/cli/loader_flag.go +++ b/pkg/cli/loader_flag.go @@ -17,7 +17,7 @@ func (*FlagLoader) Load(args []string, cmd *Command) (bool, error) { } if err := flag.Decode(args, cmd.Configuration); err != nil { - return false, fmt.Errorf("failed to decode configuration from flags: %v", err) + return false, fmt.Errorf("failed to decode configuration from flags: %w", err) } log.WithoutContext().Println("Configuration loaded from flags.") diff --git a/pkg/collector/collector.go b/pkg/collector/collector.go index 6493859a0..8936554a0 100644 --- a/pkg/collector/collector.go +++ b/pkg/collector/collector.go @@ -16,10 +16,10 @@ import ( "github.com/mitchellh/hashstructure" ) -// collectorURL URL where the stats are send +// collectorURL URL where the stats are send. const collectorURL = "https://collect.traefik.io/9vxmmkcdmalbdi635d4jgc5p5rx0h7h8" -// Collected data +// Collected data. type data struct { Version string Codename string diff --git a/pkg/config/dynamic/config.go b/pkg/config/dynamic/config.go index e9749166a..e1c9702d1 100644 --- a/pkg/config/dynamic/config.go +++ b/pkg/config/dynamic/config.go @@ -19,7 +19,7 @@ type Configurations map[string]*Configuration // +k8s:deepcopy-gen=true -// Configuration is the root of the dynamic configuration +// Configuration is the root of the dynamic configuration. type Configuration struct { HTTP *HTTPConfiguration `json:"http,omitempty" toml:"http,omitempty" yaml:"http,omitempty"` TCP *TCPConfiguration `json:"tcp,omitempty" toml:"tcp,omitempty" yaml:"tcp,omitempty"` diff --git a/pkg/config/dynamic/http_config.go b/pkg/config/dynamic/http_config.go index d422797d5..27c5e44f4 100644 --- a/pkg/config/dynamic/http_config.go +++ b/pkg/config/dynamic/http_config.go @@ -47,7 +47,7 @@ type Router struct { // +k8s:deepcopy-gen=true -// RouterTLSConfig holds the TLS configuration for a router +// RouterTLSConfig holds the TLS configuration for a router. type RouterTLSConfig struct { Options string `json:"options,omitempty" toml:"options,omitempty" yaml:"options,omitempty"` CertResolver string `json:"certResolver,omitempty" toml:"certResolver,omitempty" yaml:"certResolver,omitempty"` diff --git a/pkg/config/dynamic/middlewares.go b/pkg/config/dynamic/middlewares.go index cba305a77..8727b818b 100644 --- a/pkg/config/dynamic/middlewares.go +++ b/pkg/config/dynamic/middlewares.go @@ -95,7 +95,7 @@ type Buffering struct { // +k8s:deepcopy-gen=true -// Chain holds a chain of middlewares +// Chain holds a chain of middlewares. type Chain struct { Middlewares []string `json:"middlewares,omitempty" toml:"middlewares,omitempty" yaml:"middlewares,omitempty"` } @@ -191,13 +191,13 @@ type Headers struct { IsDevelopment bool `json:"isDevelopment,omitempty" toml:"isDevelopment,omitempty" yaml:"isDevelopment,omitempty"` } -// HasCustomHeadersDefined checks to see if any of the custom header elements have been set +// HasCustomHeadersDefined checks to see if any of the custom header elements have been set. func (h *Headers) HasCustomHeadersDefined() bool { return h != nil && (len(h.CustomResponseHeaders) != 0 || len(h.CustomRequestHeaders) != 0) } -// HasCorsHeadersDefined checks to see if any of the cors header elements have been set +// HasCorsHeadersDefined checks to see if any of the cors header elements have been set. func (h *Headers) HasCorsHeadersDefined() bool { return h != nil && (h.AccessControlAllowCredentials || len(h.AccessControlAllowHeaders) != 0 || @@ -208,7 +208,7 @@ func (h *Headers) HasCorsHeadersDefined() bool { h.AddVaryHeader) } -// HasSecureHeadersDefined checks to see if any of the secure header elements have been set +// HasSecureHeadersDefined checks to see if any of the secure header elements have been set. func (h *Headers) HasSecureHeadersDefined() bool { return h != nil && (len(h.AllowedHosts) != 0 || len(h.HostsProxyHeaders) != 0 || @@ -245,7 +245,7 @@ type IPStrategy struct { // Get an IP selection strategy. // If nil return the RemoteAddr strategy // else return a strategy base on the configuration using the X-Forwarded-For Header. -// Depth override the ExcludedIPs +// Depth override the ExcludedIPs. func (s *IPStrategy) Get() (ip.Strategy, error) { if s == nil { return &ip.RemoteAddrStrategy{}, nil @@ -420,7 +420,7 @@ type TLSCLientCertificateDNInfo struct { // +k8s:deepcopy-gen=true -// Users holds a list of users +// Users holds a list of users. type Users []string // +k8s:deepcopy-gen=true @@ -449,7 +449,7 @@ func (c *ClientTLS) CreateTLSConfig() (*tls.Config, error) { if _, errCA := os.Stat(c.CA); errCA == nil { ca, err = ioutil.ReadFile(c.CA) if err != nil { - return nil, fmt.Errorf("failed to read CA. %s", err) + return nil, fmt.Errorf("failed to read CA. %w", err) } } else { ca = []byte(c.CA) @@ -478,7 +478,7 @@ func (c *ClientTLS) CreateTLSConfig() (*tls.Config, error) { if errKeyIsFile == nil { cert, err = tls.LoadX509KeyPair(c.Cert, c.Key) if err != nil { - return nil, fmt.Errorf("failed to load TLS keypair: %v", err) + return nil, fmt.Errorf("failed to load TLS keypair: %w", err) } } else { return nil, fmt.Errorf("tls cert is a file, but tls key is not") @@ -487,7 +487,7 @@ func (c *ClientTLS) CreateTLSConfig() (*tls.Config, error) { if errKeyIsFile != nil { cert, err = tls.X509KeyPair([]byte(c.Cert), []byte(c.Key)) if err != nil { - return nil, fmt.Errorf("failed to load TLS keypair: %v", err) + return nil, fmt.Errorf("failed to load TLS keypair: %w", err) } } else { return nil, fmt.Errorf("TLS key is a file, but tls cert is not") diff --git a/pkg/config/dynamic/tcp_config.go b/pkg/config/dynamic/tcp_config.go index 272da7b14..158f3e113 100644 --- a/pkg/config/dynamic/tcp_config.go +++ b/pkg/config/dynamic/tcp_config.go @@ -55,7 +55,7 @@ type TCPRouter struct { // +k8s:deepcopy-gen=true -// RouterTCPTLSConfig holds the TLS configuration for a router +// RouterTCPTLSConfig holds the TLS configuration for a router. type RouterTCPTLSConfig struct { Passthrough bool `json:"passthrough" toml:"passthrough" yaml:"passthrough"` Options string `json:"options,omitempty" toml:"options,omitempty" yaml:"options,omitempty"` @@ -76,7 +76,7 @@ type TCPServersLoadBalancer struct { Servers []TCPServer `json:"servers,omitempty" toml:"servers,omitempty" yaml:"servers,omitempty" label-slice-as-struct:"server"` } -// SetDefaults Default values for a TCPServersLoadBalancer +// SetDefaults Default values for a TCPServersLoadBalancer. func (l *TCPServersLoadBalancer) SetDefaults() { defaultTerminationDelay := 100 // in milliseconds l.TerminationDelay = &defaultTerminationDelay @@ -101,7 +101,7 @@ func (l *TCPServersLoadBalancer) Mergeable(loadBalancer *TCPServersLoadBalancer) // +k8s:deepcopy-gen=true -// TCPServer holds a TCP Server configuration +// TCPServer holds a TCP Server configuration. type TCPServer struct { Address string `json:"address,omitempty" toml:"address,omitempty" yaml:"address,omitempty" label:"-"` Port string `toml:"-" json:"-" yaml:"-"` diff --git a/pkg/config/env/env.go b/pkg/config/env/env.go index 4fc5071e8..3e851f432 100644 --- a/pkg/config/env/env.go +++ b/pkg/config/env/env.go @@ -17,7 +17,7 @@ const DefaultNamePrefix = "TRAEFIK_" // env vars -> map // map -> tree of untyped nodes // untyped nodes -> nodes augmented with metadata such as kind (inferred from element) -// "typed" nodes -> typed element +// "typed" nodes -> typed element. func Decode(environ []string, prefix string, element interface{}) error { if err := checkPrefix(prefix); err != nil { return err @@ -40,7 +40,7 @@ func Decode(environ []string, prefix string, element interface{}) error { // The operation goes through three stages roughly summarized as: // typed configuration in element -> tree of untyped nodes // untyped nodes -> nodes augmented with metadata such as kind (inferred from element) -// "typed" nodes -> environment variables with default values (determined by type/kind) +// "typed" nodes -> environment variables with default values (determined by type/kind). func Encode(element interface{}) ([]parser.Flat, error) { if element == nil { return nil, nil diff --git a/pkg/config/file/file.go b/pkg/config/file/file.go index 619320307..1bd48da8f 100644 --- a/pkg/config/file/file.go +++ b/pkg/config/file/file.go @@ -9,7 +9,7 @@ import ( // The operation goes through three stages roughly summarized as: // file contents -> tree of untyped nodes // untyped nodes -> nodes augmented with metadata such as kind (inferred from element) -// "typed" nodes -> typed element +// "typed" nodes -> typed element. func Decode(filePath string, element interface{}) error { if element == nil { return nil diff --git a/pkg/config/flag/flag.go b/pkg/config/flag/flag.go index 437744f18..fd508a787 100644 --- a/pkg/config/flag/flag.go +++ b/pkg/config/flag/flag.go @@ -10,7 +10,7 @@ import ( // flag arguments -> parsed map of flags // map -> tree of untyped nodes // untyped nodes -> nodes augmented with metadata such as kind (inferred from element) -// "typed" nodes -> typed element +// "typed" nodes -> typed element. func Decode(args []string, element interface{}) error { ref, err := Parse(args, element) if err != nil { @@ -24,7 +24,7 @@ func Decode(args []string, element interface{}) error { // The operation goes through three stages roughly summarized as: // typed configuration in element -> tree of untyped nodes // untyped nodes -> nodes augmented with metadata such as kind (inferred from element) -// "typed" nodes -> flags with default values (determined by type/kind) +// "typed" nodes -> flags with default values (determined by type/kind). func Encode(element interface{}) ([]parser.Flat, error) { if element == nil { return nil, nil diff --git a/pkg/config/kv/kv.go b/pkg/config/kv/kv.go index 940e84ff4..e4e99d8c6 100644 --- a/pkg/config/kv/kv.go +++ b/pkg/config/kv/kv.go @@ -12,7 +12,7 @@ import ( // The operation goes through three stages roughly summarized as: // KV pairs -> tree of untyped nodes // untyped nodes -> nodes augmented with metadata such as kind (inferred from element) -// "typed" nodes -> typed element +// "typed" nodes -> typed element. func Decode(pairs []*store.KVPair, element interface{}, rootName string) error { if element == nil { return nil diff --git a/pkg/config/label/label.go b/pkg/config/label/label.go index e53410115..f2a773531 100644 --- a/pkg/config/label/label.go +++ b/pkg/config/label/label.go @@ -28,7 +28,7 @@ func EncodeConfiguration(conf *dynamic.Configuration) (map[string]string, error) } // Decode converts the labels to an element. -// labels -> [ node -> node + metadata (type) ] -> element (node) +// labels -> [ node -> node + metadata (type) ] -> element (node). func Decode(labels map[string]string, element interface{}, filters ...string) error { return parser.Decode(labels, element, parser.DefaultRootName, filters...) } diff --git a/pkg/config/parser/element_nodes.go b/pkg/config/parser/element_nodes.go index 0f61d9248..a66c108d1 100644 --- a/pkg/config/parser/element_nodes.go +++ b/pkg/config/parser/element_nodes.go @@ -15,7 +15,7 @@ type EncoderToNodeOpts struct { } // EncodeToNode converts an element to a node. -// element -> nodes +// element -> nodes. func EncodeToNode(element interface{}, rootName string, opts EncoderToNodeOpts) (*Node, error) { rValue := reflect.ValueOf(element) node := &Node{Name: rootName} diff --git a/pkg/config/parser/labels_encode.go b/pkg/config/parser/labels_encode.go index e2b353119..91cda15a2 100644 --- a/pkg/config/parser/labels_encode.go +++ b/pkg/config/parser/labels_encode.go @@ -1,7 +1,7 @@ package parser // EncodeNode Converts a node to labels. -// nodes -> labels +// nodes -> labels. func EncodeNode(node *Node) map[string]string { labels := make(map[string]string) encodeNode(labels, node.Name, node) diff --git a/pkg/config/parser/parser.go b/pkg/config/parser/parser.go index 957a27beb..af38c2a02 100644 --- a/pkg/config/parser/parser.go +++ b/pkg/config/parser/parser.go @@ -6,7 +6,7 @@ package parser // The operation goes through three stages roughly summarized as: // labels -> tree of untyped nodes // untyped nodes -> nodes augmented with metadata such as kind (inferred from element) -// "typed" nodes -> typed element +// "typed" nodes -> typed element. func Decode(labels map[string]string, element interface{}, rootName string, filters ...string) error { node, err := DecodeToNode(labels, rootName, filters...) if err != nil { @@ -28,7 +28,7 @@ func Decode(labels map[string]string, element interface{}, rootName string, filt } // Encode converts an element to labels. -// element -> node (value) -> label (node) +// element -> node (value) -> label (node). func Encode(element interface{}, rootName string) (map[string]string, error) { etnOpts := EncoderToNodeOpts{OmitEmpty: true, TagName: TagLabel, AllowSliceAsStruct: true} node, err := EncodeToNode(element, rootName, etnOpts) diff --git a/pkg/config/runtime/runtime.go b/pkg/config/runtime/runtime.go index aa64d7475..10e610e15 100644 --- a/pkg/config/runtime/runtime.go +++ b/pkg/config/runtime/runtime.go @@ -8,7 +8,7 @@ import ( "github.com/containous/traefik/v2/pkg/log" ) -// Status of the router/service +// Status of the router/service. const ( StatusEnabled = "enabled" StatusDisabled = "disabled" diff --git a/pkg/config/runtime/runtime_http.go b/pkg/config/runtime/runtime_http.go index d93d6e844..bfb48820e 100644 --- a/pkg/config/runtime/runtime_http.go +++ b/pkg/config/runtime/runtime_http.go @@ -179,7 +179,7 @@ func (s *ServiceInfo) UpdateServerStatus(server string, status string) { } // GetAllStatus returns all the statuses of all the servers in ServiceInfo. -// It is the responsibility of the caller to check that s is not nil +// It is the responsibility of the caller to check that s is not nil. func (s *ServiceInfo) GetAllStatus() map[string]string { s.serverStatusMu.RLock() defer s.serverStatusMu.RUnlock() diff --git a/pkg/config/runtime/runtime_test.go b/pkg/config/runtime/runtime_test.go index 1cdce84a6..b03cbe6ab 100644 --- a/pkg/config/runtime/runtime_test.go +++ b/pkg/config/runtime/runtime_test.go @@ -9,7 +9,7 @@ import ( "github.com/stretchr/testify/require" ) -// all the Routers/Middlewares/Services are considered fully qualified +// all the Routers/Middlewares/Services are considered fully qualified. func TestPopulateUsedBy(t *testing.T) { testCases := []struct { desc string diff --git a/pkg/config/static/static_config.go b/pkg/config/static/static_config.go index 813ba6d0b..1fac9e019 100644 --- a/pkg/config/static/static_config.go +++ b/pkg/config/static/static_config.go @@ -49,7 +49,7 @@ const ( DefaultAcmeCAServer = "https://acme-v02.api.letsencrypt.org/directory" ) -// Configuration is the static configuration +// Configuration is the static configuration. type Configuration struct { Global *Global `description:"Global configuration options" json:"global,omitempty" toml:"global,omitempty" yaml:"global,omitempty" export:"true"` @@ -81,7 +81,7 @@ type Global struct { SendAnonymousUsage bool `description:"Periodically send anonymous usage statistics. If the option is not specified, it will be enabled by default." json:"sendAnonymousUsage,omitempty" toml:"sendAnonymousUsage,omitempty" yaml:"sendAnonymousUsage,omitempty" label:"allowEmpty" export:"true"` } -// ServersTransport options to configure communication between Traefik and the servers +// ServersTransport options to configure communication between Traefik and the servers. type ServersTransport struct { InsecureSkipVerify bool `description:"Disable SSL certificate verification." json:"insecureSkipVerify,omitempty" toml:"insecureSkipVerify,omitempty" yaml:"insecureSkipVerify,omitempty" export:"true"` RootCAs []tls.FileOrContent `description:"Add cert file for self-signed certificate." json:"rootCAs,omitempty" toml:"rootCAs,omitempty" yaml:"rootCAs,omitempty"` @@ -89,7 +89,7 @@ type ServersTransport struct { ForwardingTimeouts *ForwardingTimeouts `description:"Timeouts for requests forwarded to the backend servers." json:"forwardingTimeouts,omitempty" toml:"forwardingTimeouts,omitempty" yaml:"forwardingTimeouts,omitempty" export:"true"` } -// API holds the API configuration +// API holds the API configuration. type API struct { Insecure bool `description:"Activate API directly on the entryPoint named traefik." json:"insecure,omitempty" toml:"insecure,omitempty" yaml:"insecure,omitempty" export:"true"` Dashboard bool `description:"Activate dashboard." json:"dashboard,omitempty" toml:"dashboard,omitempty" yaml:"dashboard,omitempty" export:"true"` @@ -158,7 +158,7 @@ func (t *Tracing) SetDefaults() { t.SpanNameLimit = 0 } -// Providers contains providers configuration +// Providers contains providers configuration. type Providers struct { ProvidersThrottleDuration types.Duration `description:"Backends throttle duration: minimum duration between 2 events from providers before applying a new configuration. It avoids unnecessary reloads if multiples events are sent in a short amount of time." json:"providersThrottleDuration,omitempty" toml:"providersThrottleDuration,omitempty" yaml:"providersThrottleDuration,omitempty" export:"true"` @@ -224,7 +224,7 @@ func (c *Configuration) initACMEProvider() { legolog.Logger = stdlog.New(log.WithoutContext().WriterLevel(logrus.DebugLevel), "legolog: ", 0) } -// ValidateConfiguration validate that configuration is coherent +// ValidateConfiguration validate that configuration is coherent. func (c *Configuration) ValidateConfiguration() error { var acmeEmail string for name, resolver := range c.CertificatesResolvers { diff --git a/pkg/healthcheck/healthcheck.go b/pkg/healthcheck/healthcheck.go index 65db86f00..738cd40b2 100644 --- a/pkg/healthcheck/healthcheck.go +++ b/pkg/healthcheck/healthcheck.go @@ -25,8 +25,7 @@ const ( var singleton *HealthCheck var once sync.Once -// Balancer is the set of operations required to manage the list of servers in a -// load-balancer. +// Balancer is the set of operations required to manage the list of servers in a load-balancer. type Balancer interface { Servers() []*url.URL RemoveServer(u *url.URL) error @@ -39,8 +38,9 @@ type BalancerHandler interface { Balancer } -// metricsRegistry is a local interface in the health check package, exposing only the required metrics -// necessary for the health check package. This makes it easier for the tests. +// metricsRegistry is a local interface in the health check package, +// exposing only the required metrics necessary for the health check package. +// This makes it easier for the tests. type metricsRegistry interface { BackendServerUpGauge() metrics.Gauge } @@ -68,7 +68,7 @@ type backendURL struct { weight int } -// BackendConfig HealthCheck configuration for a backend +// BackendConfig HealthCheck configuration for a backend. type BackendConfig struct { Options name string @@ -92,7 +92,7 @@ func (b *BackendConfig) newRequest(serverURL *url.URL) (*http.Request, error) { return http.NewRequest(http.MethodGet, u.String(), http.NoBody) } -// this function adds additional http headers and hostname to http.request +// this function adds additional http headers and hostname to http.request. func (b *BackendConfig) addHeadersAndHost(req *http.Request) *http.Request { if b.Options.Hostname != "" { req.Host = b.Options.Hostname @@ -104,14 +104,14 @@ func (b *BackendConfig) addHeadersAndHost(req *http.Request) *http.Request { return req } -// HealthCheck struct +// HealthCheck struct. type HealthCheck struct { Backends map[string]*BackendConfig metrics metricsRegistry cancel context.CancelFunc } -// SetBackendsConfiguration set backends configuration +// SetBackendsConfiguration set backends configuration. func (hc *HealthCheck) SetBackendsConfiguration(parentCtx context.Context, backends map[string]*BackendConfig) { hc.Backends = backends if hc.cancel != nil { @@ -152,28 +152,21 @@ func (hc *HealthCheck) checkBackend(ctx context.Context, backend *BackendConfig) enabledURLs := backend.LB.Servers() var newDisabledURLs []backendURL - // FIXME re enable metrics for _, disabledURL := range backend.disabledURLs { - // FIXME serverUpMetricValue := float64(0) if err := checkHealth(disabledURL.url, backend); err == nil { logger.Warnf("Health check up: Returning to server list. Backend: %q URL: %q Weight: %d", backend.name, disabledURL.url.String(), disabledURL.weight) if err = backend.LB.UpsertServer(disabledURL.url, roundrobin.Weight(disabledURL.weight)); err != nil { logger.Error(err) } - // FIXME serverUpMetricValue = 1 } else { logger.Warnf("Health check still failing. Backend: %q URL: %q Reason: %s", backend.name, disabledURL.url.String(), err) newDisabledURLs = append(newDisabledURLs, disabledURL) } - // FIXME labelValues := []string{"backend", backend.name, "url", backendurl.url.String()} - // FIXME hc.metrics.BackendServerUpGauge().With(labelValues...).Set(serverUpMetricValue) } backend.disabledURLs = newDisabledURLs - // FIXME re enable metrics for _, enableURL := range enabledURLs { - // FIXME serverUpMetricValue := float64(1) if err := checkHealth(enableURL, backend); err != nil { weight := 1 rr, ok := backend.LB.(*roundrobin.RoundRobin) @@ -189,35 +182,25 @@ func (hc *HealthCheck) checkBackend(ctx context.Context, backend *BackendConfig) logger.Error(err) } backend.disabledURLs = append(backend.disabledURLs, backendURL{enableURL, weight}) - // FIXME serverUpMetricValue = 0 } - // FIXME labelValues := []string{"backend", backend.name, "url", enableURL.String()} - // FIXME hc.metrics.BackendServerUpGauge().With(labelValues...).Set(serverUpMetricValue) } } -// FIXME re add metrics -//func GetHealthCheck(metrics metricsRegistry) *HealthCheck { - // GetHealthCheck returns the health check which is guaranteed to be a singleton. func GetHealthCheck() *HealthCheck { once.Do(func() { singleton = newHealthCheck() - //singleton = newHealthCheck(metrics) }) return singleton } -// FIXME re add metrics -//func newHealthCheck(metrics metricsRegistry) *HealthCheck { func newHealthCheck() *HealthCheck { return &HealthCheck{ Backends: make(map[string]*BackendConfig), - //metrics: metrics, } } -// NewBackendConfig Instantiate a new BackendConfig +// NewBackendConfig Instantiate a new BackendConfig. func NewBackendConfig(options Options, backendName string) *BackendConfig { return &BackendConfig{ Options: options, @@ -230,7 +213,7 @@ func NewBackendConfig(options Options, backendName string) *BackendConfig { func checkHealth(serverURL *url.URL, backend *BackendConfig) error { req, err := backend.newRequest(serverURL) if err != nil { - return fmt.Errorf("failed to create HTTP request: %s", err) + return fmt.Errorf("failed to create HTTP request: %w", err) } req = backend.addHeadersAndHost(req) @@ -248,7 +231,7 @@ func checkHealth(serverURL *url.URL, backend *BackendConfig) error { resp, err := client.Do(req) if err != nil { - return fmt.Errorf("HTTP request failed: %s", err) + return fmt.Errorf("HTTP request failed: %w", err) } defer resp.Body.Close() @@ -260,7 +243,7 @@ func checkHealth(serverURL *url.URL, backend *BackendConfig) error { return nil } -// NewLBStatusUpdater returns a new LbStatusUpdater +// NewLBStatusUpdater returns a new LbStatusUpdater. func NewLBStatusUpdater(bh BalancerHandler, info *runtime.ServiceInfo) *LbStatusUpdater { return &LbStatusUpdater{ BalancerHandler: bh, @@ -298,7 +281,7 @@ func (lb *LbStatusUpdater) UpsertServer(u *url.URL, options ...roundrobin.Server // Balancers is a list of Balancers(s) that implements the Balancer interface. type Balancers []Balancer -// Servers returns the servers url from all the BalancerHandler +// Servers returns the servers url from all the BalancerHandler. func (b Balancers) Servers() []*url.URL { var servers []*url.URL for _, lb := range b { diff --git a/pkg/ip/checker.go b/pkg/ip/checker.go index ffe86c01e..c9baf84b1 100644 --- a/pkg/ip/checker.go +++ b/pkg/ip/checker.go @@ -7,13 +7,13 @@ import ( "strings" ) -// Checker allows to check that addresses are in a trusted IPs +// Checker allows to check that addresses are in a trusted IPs. type Checker struct { authorizedIPs []*net.IP authorizedIPsNet []*net.IPNet } -// NewChecker builds a new Checker given a list of CIDR-Strings to trusted IPs +// NewChecker builds a new Checker given a list of CIDR-Strings to trusted IPs. func NewChecker(trustedIPs []string) (*Checker, error) { if len(trustedIPs) == 0 { return nil, errors.New("no trusted IPs provided") @@ -27,7 +27,7 @@ func NewChecker(trustedIPs []string) (*Checker, error) { } else { _, ipAddr, err := net.ParseCIDR(ipMask) if err != nil { - return nil, fmt.Errorf("parsing CIDR trusted IPs %s: %v", ipAddr, err) + return nil, fmt.Errorf("parsing CIDR trusted IPs %s: %w", ipAddr, err) } checker.authorizedIPsNet = append(checker.authorizedIPsNet, ipAddr) } @@ -36,7 +36,7 @@ func NewChecker(trustedIPs []string) (*Checker, error) { return checker, nil } -// IsAuthorized checks if provided request is authorized by the trusted IPs +// IsAuthorized checks if provided request is authorized by the trusted IPs. func (ip *Checker) IsAuthorized(addr string) error { var invalidMatches []string @@ -58,7 +58,7 @@ func (ip *Checker) IsAuthorized(addr string) error { return nil } -// Contains checks if provided address is in the trusted IPs +// Contains checks if provided address is in the trusted IPs. func (ip *Checker) Contains(addr string) (bool, error) { if len(addr) == 0 { return false, errors.New("empty IP address") @@ -66,13 +66,13 @@ func (ip *Checker) Contains(addr string) (bool, error) { ipAddr, err := parseIP(addr) if err != nil { - return false, fmt.Errorf("unable to parse address: %s: %s", addr, err) + return false, fmt.Errorf("unable to parse address: %s: %w", addr, err) } return ip.ContainsIP(ipAddr), nil } -// ContainsIP checks if provided address is in the trusted IPs +// ContainsIP checks if provided address is in the trusted IPs. func (ip *Checker) ContainsIP(addr net.IP) bool { for _, authorizedIP := range ip.authorizedIPs { if authorizedIP.Equal(addr) { diff --git a/pkg/ip/strategy.go b/pkg/ip/strategy.go index 260c5021b..5a32524f6 100644 --- a/pkg/ip/strategy.go +++ b/pkg/ip/strategy.go @@ -10,15 +10,15 @@ const ( xForwardedFor = "X-Forwarded-For" ) -// Strategy a strategy for IP selection +// Strategy a strategy for IP selection. type Strategy interface { GetIP(req *http.Request) string } -// RemoteAddrStrategy a strategy that always return the remote address +// RemoteAddrStrategy a strategy that always return the remote address. type RemoteAddrStrategy struct{} -// GetIP returns the selected IP +// GetIP returns the selected IP. func (s *RemoteAddrStrategy) GetIP(req *http.Request) string { ip, _, err := net.SplitHostPort(req.RemoteAddr) if err != nil { @@ -27,12 +27,12 @@ func (s *RemoteAddrStrategy) GetIP(req *http.Request) string { return ip } -// DepthStrategy a strategy based on the depth inside the X-Forwarded-For from right to left +// DepthStrategy a strategy based on the depth inside the X-Forwarded-For from right to left. type DepthStrategy struct { Depth int } -// GetIP return the selected IP +// GetIP return the selected IP. func (s *DepthStrategy) GetIP(req *http.Request) string { xff := req.Header.Get(xForwardedFor) xffs := strings.Split(xff, ",") @@ -44,12 +44,12 @@ func (s *DepthStrategy) GetIP(req *http.Request) string { } // CheckerStrategy a strategy based on an IP Checker -// allows to check that addresses are in a trusted IPs +// allows to check that addresses are in a trusted IPs. type CheckerStrategy struct { Checker *Checker } -// GetIP return the selected IP +// GetIP return the selected IP. func (s *CheckerStrategy) GetIP(req *http.Request) string { if s.Checker == nil { return "" diff --git a/pkg/log/deprecated.go b/pkg/log/deprecated.go index 2bdf735ed..12bb51176 100644 --- a/pkg/log/deprecated.go +++ b/pkg/log/deprecated.go @@ -80,7 +80,7 @@ func AddHook(hook logrus.Hook) { } // CustomWriterLevel logs writer for a specific level. (with a custom scanner buffer size.) -// adapted from github.com/Sirupsen/logrus/writer.go +// adapted from github.com/Sirupsen/logrus/writer.go. func CustomWriterLevel(level logrus.Level, maxScanTokenSize int) *io.PipeWriter { reader, writer := io.Pipe() @@ -110,7 +110,7 @@ func CustomWriterLevel(level logrus.Level, maxScanTokenSize int) *io.PipeWriter } // extract from github.com/Sirupsen/logrus/writer.go -// Hack the buffer size +// Hack the buffer size. func writerScanner(reader io.ReadCloser, scanTokenSize int, printFunc func(args ...interface{})) { scanner := bufio.NewScanner(reader) diff --git a/pkg/log/fields.go b/pkg/log/fields.go index f84b00498..c7ad31b08 100644 --- a/pkg/log/fields.go +++ b/pkg/log/fields.go @@ -1,6 +1,6 @@ package log -// Log entry name +// Log entry names. const ( EntryPointName = "entryPointName" RouterName = "routerName" diff --git a/pkg/log/log.go b/pkg/log/log.go index 49f7736d6..eb45c0050 100644 --- a/pkg/log/log.go +++ b/pkg/log/log.go @@ -15,7 +15,7 @@ const ( loggerKey contextKey = iota ) -// Logger the Traefik logger +// Logger the Traefik logger. type Logger interface { logrus.FieldLogger WriterLevel(logrus.Level) *io.PipeWriter @@ -57,14 +57,14 @@ func GetLevel() logrus.Level { return logrus.GetLevel() } -// Str adds a string field +// Str adds a string field. func Str(key, value string) func(logrus.Fields) { return func(fields logrus.Fields) { fields[key] = value } } -// With Adds fields +// With Adds fields. func With(ctx context.Context, opts ...func(logrus.Fields)) context.Context { logger := FromContext(ctx) @@ -77,7 +77,7 @@ func With(ctx context.Context, opts ...func(logrus.Fields)) context.Context { return context.WithValue(ctx, loggerKey, logger) } -// FromContext Gets the logger from context +// FromContext Gets the logger from context. func FromContext(ctx context.Context) Logger { if ctx == nil { panic("nil context") @@ -91,12 +91,12 @@ func FromContext(ctx context.Context) Logger { return logger } -// WithoutContext Gets the main logger +// WithoutContext Gets the main logger. func WithoutContext() Logger { return mainLogger } -// OpenFile opens the log file using the specified path +// OpenFile opens the log file using the specified path. func OpenFile(path string) error { logFilePath = path @@ -110,7 +110,7 @@ func OpenFile(path string) error { return nil } -// CloseFile closes the log and sets the Output to stdout +// CloseFile closes the log and sets the Output to stdout. func CloseFile() error { logrus.SetOutput(os.Stdout) @@ -120,9 +120,8 @@ func CloseFile() error { return nil } -// RotateFile closes and reopens the log file to allow for rotation -// by an external source. If the log isn't backed by a file then -// it does nothing. +// RotateFile closes and reopens the log file to allow for rotation by an external source. +// If the log isn't backed by a file then it does nothing. func RotateFile() error { logger := FromContext(context.Background()) diff --git a/pkg/metrics/influxdb.go b/pkg/metrics/influxdb.go index b8bbc363c..53944e73e 100644 --- a/pkg/metrics/influxdb.go +++ b/pkg/metrics/influxdb.go @@ -80,7 +80,7 @@ func RegisterInfluxDB(ctx context.Context, config *types.InfluxDB) Registry { return registry } -// initInfluxDBTicker creates a influxDBClient +// initInfluxDBTicker creates a influxDBClient. func initInfluxDBClient(ctx context.Context, config *types.InfluxDB) *influx.Influx { logger := log.FromContext(ctx) @@ -123,7 +123,7 @@ func initInfluxDBClient(ctx context.Context, config *types.InfluxDB) *influx.Inf })) } -// initInfluxDBTicker initializes metrics pusher +// initInfluxDBTicker initializes metrics pusher. func initInfluxDBTicker(ctx context.Context, config *types.InfluxDB) *time.Ticker { report := time.NewTicker(time.Duration(config.PushInterval)) @@ -135,7 +135,7 @@ func initInfluxDBTicker(ctx context.Context, config *types.InfluxDB) *time.Ticke return report } -// StopInfluxDB stops internal influxDBTicker which controls the pushing of metrics to InfluxDB Agent and resets it to `nil` +// StopInfluxDB stops internal influxDBTicker which controls the pushing of metrics to InfluxDB Agent and resets it to `nil`. func StopInfluxDB() { if influxDBTicker != nil { influxDBTicker.Stop() diff --git a/pkg/metrics/statsd.go b/pkg/metrics/statsd.go index f8f14de63..b0fd36839 100644 --- a/pkg/metrics/statsd.go +++ b/pkg/metrics/statsd.go @@ -71,7 +71,7 @@ func RegisterStatsd(ctx context.Context, config *types.Statsd) Registry { return registry } -// initStatsdTicker initializes metrics pusher and creates a statsdClient if not created already +// initStatsdTicker initializes metrics pusher and creates a statsdClient if not created already. func initStatsdTicker(ctx context.Context, config *types.Statsd) *time.Ticker { address := config.Address if len(address) == 0 { @@ -87,7 +87,7 @@ func initStatsdTicker(ctx context.Context, config *types.Statsd) *time.Ticker { return report } -// StopStatsd stops internal statsdTicker which controls the pushing of metrics to StatsD Agent and resets it to `nil` +// StopStatsd stops internal statsdTicker which controls the pushing of metrics to StatsD Agent and resets it to `nil`. func StopStatsd() { if statsdTicker != nil { statsdTicker.Stop() diff --git a/pkg/middlewares/accesslog/capture_response_writer.go b/pkg/middlewares/accesslog/capture_response_writer.go index 4202b0ee9..dd22cd7d0 100644 --- a/pkg/middlewares/accesslog/capture_response_writer.go +++ b/pkg/middlewares/accesslog/capture_response_writer.go @@ -28,7 +28,7 @@ func newCaptureResponseWriter(rw http.ResponseWriter) capturer { } // captureResponseWriter is a wrapper of type http.ResponseWriter -// that tracks request status and size +// that tracks request status and size. type captureResponseWriter struct { rw http.ResponseWriter status int diff --git a/pkg/middlewares/accesslog/field_middleware.go b/pkg/middlewares/accesslog/field_middleware.go index f201ba53a..7a2aa9944 100644 --- a/pkg/middlewares/accesslog/field_middleware.go +++ b/pkg/middlewares/accesslog/field_middleware.go @@ -7,7 +7,7 @@ import ( "github.com/vulcand/oxy/utils" ) -// FieldApply function hook to add data in accesslog +// FieldApply function hook to add data in accesslog. type FieldApply func(rw http.ResponseWriter, r *http.Request, next http.Handler, data *LogData) // FieldHandler sends a new field to the logger. @@ -39,7 +39,7 @@ func (f *FieldHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { } } -// AddServiceFields add service fields +// AddServiceFields add service fields. func AddServiceFields(rw http.ResponseWriter, req *http.Request, next http.Handler, data *LogData) { data.Core[ServiceURL] = req.URL // note that this is *not* the original incoming URL data.Core[ServiceAddr] = req.URL.Host @@ -47,7 +47,7 @@ func AddServiceFields(rw http.ResponseWriter, req *http.Request, next http.Handl next.ServeHTTP(rw, req) } -// AddOriginFields add origin fields +// AddOriginFields add origin fields. func AddOriginFields(rw http.ResponseWriter, req *http.Request, next http.Handler, data *LogData) { crw := newCaptureResponseWriter(rw) start := time.Now().UTC() diff --git a/pkg/middlewares/accesslog/logger.go b/pkg/middlewares/accesslog/logger.go index 60901effe..dbe17e1c6 100644 --- a/pkg/middlewares/accesslog/logger.go +++ b/pkg/middlewares/accesslog/logger.go @@ -75,7 +75,7 @@ func NewHandler(config *types.AccessLog) (*Handler, error) { if len(config.FilePath) > 0 { f, err := openAccessLogFile(config.FilePath) if err != nil { - return nil, fmt.Errorf("error opening access log file: %s", err) + return nil, fmt.Errorf("error opening access log file: %w", err) } file = f } @@ -132,12 +132,12 @@ func openAccessLogFile(filePath string) (*os.File, error) { dir := filepath.Dir(filePath) if err := os.MkdirAll(dir, 0755); err != nil { - return nil, fmt.Errorf("failed to create log path %s: %s", dir, err) + return nil, fmt.Errorf("failed to create log path %s: %w", dir, err) } file, err := os.OpenFile(filePath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0664) if err != nil { - return nil, fmt.Errorf("error opening file %s: %s", filePath, err) + return nil, fmt.Errorf("error opening file %s: %w", filePath, err) } return file, nil diff --git a/pkg/middlewares/accesslog/parser.go b/pkg/middlewares/accesslog/parser.go index 281a4bbb9..0ba4073c6 100644 --- a/pkg/middlewares/accesslog/parser.go +++ b/pkg/middlewares/accesslog/parser.go @@ -5,7 +5,7 @@ import ( "regexp" ) -// ParseAccessLog parse line of access log and return a map with each fields +// ParseAccessLog parse line of access log and return a map with each fields. func ParseAccessLog(data string) (map[string]string, error) { var buffer bytes.Buffer buffer.WriteString(`(\S+)`) // 1 - ClientHost diff --git a/pkg/middlewares/auth/digest_auth_request_test.go b/pkg/middlewares/auth/digest_auth_request_test.go index c9dff7d1e..7101016c8 100644 --- a/pkg/middlewares/auth/digest_auth_request_test.go +++ b/pkg/middlewares/auth/digest_auth_request_test.go @@ -20,7 +20,7 @@ const ( wwwAuthenticate = "Www-Authenticate" ) -// DigestRequest is a client for digest authentication requests +// DigestRequest is a client for digest authentication requests. type digestRequest struct { client *http.Client username, password string @@ -35,7 +35,7 @@ func (nc nonceCount) String() string { var wanted = []string{algorithm, nonce, opaque, qop, realm} -// New makes a DigestRequest instance +// New makes a DigestRequest instance. func newDigestRequest(username, password string, client *http.Client) *digestRequest { return &digestRequest{ client: client, @@ -44,7 +44,7 @@ func newDigestRequest(username, password string, client *http.Client) *digestReq } } -// Do does requests as http.Do does +// Do does requests as http.Do does. func (r *digestRequest) Do(req *http.Request) (*http.Response, error) { parts, err := r.makeParts(req) if err != nil { @@ -133,7 +133,7 @@ func (r *digestRequest) makeAuthorization(req *http.Request, parts map[string]st ) } -// GenerateRandom generates random string +// GenerateRandom generates random string. func generateRandom(n int) string { b := make([]byte, 8) _, _ = io.ReadFull(rand.Reader, b) diff --git a/pkg/middlewares/chain/chain.go b/pkg/middlewares/chain/chain.go index bf227b069..a4028aa2e 100644 --- a/pkg/middlewares/chain/chain.go +++ b/pkg/middlewares/chain/chain.go @@ -18,7 +18,7 @@ type chainBuilder interface { BuildChain(ctx context.Context, middlewares []string) *alice.Chain } -// New creates a chain middleware +// New creates a chain middleware. func New(ctx context.Context, next http.Handler, config dynamic.Chain, builder chainBuilder, name string) (http.Handler, error) { log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware") diff --git a/pkg/middlewares/circuitbreaker/circuit_breaker.go b/pkg/middlewares/circuitbreaker/circuit_breaker.go index c4c2c5cf1..94d9aa91b 100644 --- a/pkg/middlewares/circuitbreaker/circuit_breaker.go +++ b/pkg/middlewares/circuitbreaker/circuit_breaker.go @@ -39,7 +39,7 @@ func New(ctx context.Context, next http.Handler, confCircuitBreaker dynamic.Circ }, nil } -// NewCircuitBreakerOptions returns a new CircuitBreakerOption +// NewCircuitBreakerOptions returns a new CircuitBreakerOption. func createCircuitBreakerOptions(expression string) cbreaker.CircuitBreakerOption { return cbreaker.Fallback(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { tracing.SetErrorWithEvent(req, "blocked by circuit-breaker (%q)", expression) diff --git a/pkg/middlewares/customerrors/custom_errors.go b/pkg/middlewares/customerrors/custom_errors.go index ee50f6dda..d5f687fde 100644 --- a/pkg/middlewares/customerrors/custom_errors.go +++ b/pkg/middlewares/customerrors/custom_errors.go @@ -131,12 +131,12 @@ func (c *customErrors) ServeHTTP(rw http.ResponseWriter, req *http.Request) { func newRequest(baseURL string) (*http.Request, error) { u, err := url.Parse(baseURL) if err != nil { - return nil, fmt.Errorf("error pages: error when parse URL: %v", err) + return nil, fmt.Errorf("error pages: error when parse URL: %w", err) } req, err := http.NewRequest(http.MethodGet, u.String(), nil) if err != nil { - return nil, fmt.Errorf("error pages: error when create query: %v", err) + return nil, fmt.Errorf("error pages: error when create query: %w", err) } req.RequestURI = u.RequestURI() @@ -250,7 +250,7 @@ func (cc *codeCatcher) WriteHeader(code int) { cc.headersSent = true } -// Hijack hijacks the connection +// Hijack hijacks the connection. func (cc *codeCatcher) Hijack() (net.Conn, *bufio.ReadWriter, error) { if hj, ok := cc.responseWriter.(http.Hijacker); ok { return hj.Hijack() @@ -349,7 +349,7 @@ func (r *responseRecorderWithoutCloseNotify) WriteHeader(code int) { r.Code = code } -// Hijack hijacks the connection +// Hijack hijacks the connection. func (r *responseRecorderWithoutCloseNotify) Hijack() (net.Conn, *bufio.ReadWriter, error) { return r.responseWriter.(http.Hijacker).Hijack() } diff --git a/pkg/middlewares/forwardedheaders/forwarded_header.go b/pkg/middlewares/forwardedheaders/forwarded_header.go index 455e756ec..4d796c55d 100644 --- a/pkg/middlewares/forwardedheaders/forwarded_header.go +++ b/pkg/middlewares/forwardedheaders/forwarded_header.go @@ -37,9 +37,10 @@ var xHeaders = []string{ xRealIP, } -// XForwarded is an HTTP handler wrapper that sets the X-Forwarded headers, and other relevant headers for a -// reverse-proxy. Unless insecure is set, it first removes all the existing values for those headers if the remote -// address is not one of the trusted ones. +// XForwarded is an HTTP handler wrapper that sets the X-Forwarded headers, +// and other relevant headers for a reverse-proxy. +// Unless insecure is set, +// it first removes all the existing values for those headers if the remote address is not one of the trusted ones. type XForwarded struct { insecure bool trustedIps []string @@ -80,15 +81,13 @@ func (x *XForwarded) isTrustedIP(ip string) bool { return x.ipChecker.IsAuthorized(ip) == nil } -// removeIPv6Zone removes the zone if the given IP is an ipv6 address and it has -// {zone} information in it, like "[fe80::d806:a55d:eb1b:49cc%vEthernet (vmxnet3 -// Ethernet Adapter - Virtual Switch)]:64692" +// removeIPv6Zone removes the zone if the given IP is an ipv6 address and it has {zone} information in it, +// like "[fe80::d806:a55d:eb1b:49cc%vEthernet (vmxnet3 Ethernet Adapter - Virtual Switch)]:64692". func removeIPv6Zone(clientIP string) string { return strings.Split(clientIP, "%")[0] } -// isWebsocketRequest returns whether the specified HTTP request is a -// websocket handshake request +// isWebsocketRequest returns whether the specified HTTP request is a websocket handshake request. func isWebsocketRequest(req *http.Request) bool { containsHeader := func(name, value string) bool { items := strings.Split(req.Header.Get(name), ",") @@ -141,7 +140,7 @@ func (x *XForwarded) rewrite(outreq *http.Request) { } if isWebsocketRequest(outreq) { - if outreq.Header.Get(xForwardedProto) == "https" { + if outreq.Header.Get(xForwardedProto) == "https" || outreq.Header.Get(xForwardedProto) == "wss" { outreq.Header.Set(xForwardedProto, "wss") } else { outreq.Header.Set(xForwardedProto, "ws") @@ -161,7 +160,7 @@ func (x *XForwarded) rewrite(outreq *http.Request) { } } -// ServeHTTP implements http.Handler +// ServeHTTP implements http.Handler. func (x *XForwarded) ServeHTTP(w http.ResponseWriter, r *http.Request) { if !x.insecure && !x.isTrustedIP(r.RemoteAddr) { for _, h := range xHeaders { diff --git a/pkg/middlewares/forwardedheaders/forwarded_header_test.go b/pkg/middlewares/forwardedheaders/forwarded_header_test.go index 0db1f638a..96e36442b 100644 --- a/pkg/middlewares/forwardedheaders/forwarded_header_test.go +++ b/pkg/middlewares/forwardedheaders/forwarded_header_test.go @@ -203,6 +203,17 @@ func TestServeHTTP(t *testing.T) { xForwardedProto: "wss", }, }, + { + desc: "xForwardedProto with websocket and tls and already x-forwarded-proto with wss", + tls: true, + websocket: true, + incomingHeaders: map[string]string{ + xForwardedProto: "wss", + }, + expectedHeaders: map[string]string{ + xForwardedProto: "wss", + }, + }, { desc: "xForwardedPort with explicit port", host: "foo.com:8080", diff --git a/pkg/middlewares/handler_switcher.go b/pkg/middlewares/handler_switcher.go index 79be6d2e9..862c54e16 100644 --- a/pkg/middlewares/handler_switcher.go +++ b/pkg/middlewares/handler_switcher.go @@ -6,12 +6,12 @@ import ( "github.com/containous/traefik/v2/pkg/safe" ) -// HTTPHandlerSwitcher allows hot switching of http.ServeMux +// HTTPHandlerSwitcher allows hot switching of http.ServeMux. type HTTPHandlerSwitcher struct { handler *safe.Safe } -// NewHandlerSwitcher builds a new instance of HTTPHandlerSwitcher +// NewHandlerSwitcher builds a new instance of HTTPHandlerSwitcher. func NewHandlerSwitcher(newHandler http.Handler) (hs *HTTPHandlerSwitcher) { return &HTTPHandlerSwitcher{ handler: safe.New(newHandler), @@ -23,13 +23,13 @@ func (h *HTTPHandlerSwitcher) ServeHTTP(rw http.ResponseWriter, req *http.Reques handlerBackup.ServeHTTP(rw, req) } -// GetHandler returns the current http.ServeMux +// GetHandler returns the current http.ServeMux. func (h *HTTPHandlerSwitcher) GetHandler() (newHandler http.Handler) { handler := h.handler.Get().(http.Handler) return handler } -// UpdateHandler safely updates the current http.ServeMux with a new one +// UpdateHandler safely updates the current http.ServeMux with a new one. func (h *HTTPHandlerSwitcher) UpdateHandler(newHandler http.Handler) { h.handler.Set(newHandler) } diff --git a/pkg/middlewares/inflightreq/inflight_req.go b/pkg/middlewares/inflightreq/inflight_req.go index 8856858a6..9c076c078 100644 --- a/pkg/middlewares/inflightreq/inflight_req.go +++ b/pkg/middlewares/inflightreq/inflight_req.go @@ -38,12 +38,12 @@ func New(ctx context.Context, next http.Handler, config dynamic.InFlightReq, nam sourceMatcher, err := middlewares.GetSourceExtractor(ctxLog, config.SourceCriterion) if err != nil { - return nil, fmt.Errorf("error creating requests limiter: %v", err) + return nil, fmt.Errorf("error creating requests limiter: %w", err) } handler, err := connlimit.New(next, sourceMatcher, config.Amount) if err != nil { - return nil, fmt.Errorf("error creating connection limit: %v", err) + return nil, fmt.Errorf("error creating connection limit: %w", err) } return &inFlightReq{handler: handler, name: name}, nil diff --git a/pkg/middlewares/ipwhitelist/ip_whitelist.go b/pkg/middlewares/ipwhitelist/ip_whitelist.go index 5e7468500..0c63a0cb2 100644 --- a/pkg/middlewares/ipwhitelist/ip_whitelist.go +++ b/pkg/middlewares/ipwhitelist/ip_whitelist.go @@ -18,7 +18,7 @@ const ( typeName = "IPWhiteLister" ) -// ipWhiteLister is a middleware that provides Checks of the Requesting IP against a set of Whitelists +// ipWhiteLister is a middleware that provides Checks of the Requesting IP against a set of Whitelists. type ipWhiteLister struct { next http.Handler whiteLister *ip.Checker @@ -26,7 +26,7 @@ type ipWhiteLister struct { name string } -// New builds a new IPWhiteLister given a list of CIDR-Strings to whitelist +// New builds a new IPWhiteLister given a list of CIDR-Strings to whitelist. func New(ctx context.Context, next http.Handler, config dynamic.IPWhiteList, name string) (http.Handler, error) { logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)) logger.Debug("Creating middleware") @@ -37,7 +37,7 @@ func New(ctx context.Context, next http.Handler, config dynamic.IPWhiteList, nam checker, err := ip.NewChecker(config.SourceRange) if err != nil { - return nil, fmt.Errorf("cannot parse CIDR whitelist %s: %v", config.SourceRange, err) + return nil, fmt.Errorf("cannot parse CIDR whitelist %s: %w", config.SourceRange, err) } strategy, err := config.IPStrategy.Get() diff --git a/pkg/middlewares/metrics/recorder.go b/pkg/middlewares/metrics/recorder.go index b39a79954..66de624b4 100644 --- a/pkg/middlewares/metrics/recorder.go +++ b/pkg/middlewares/metrics/recorder.go @@ -50,7 +50,7 @@ func (r *responseRecorder) WriteHeader(status int) { r.statusCode = status } -// Hijack hijacks the connection +// Hijack hijacks the connection. func (r *responseRecorder) Hijack() (net.Conn, *bufio.ReadWriter, error) { return r.ResponseWriter.(http.Hijacker).Hijack() } diff --git a/pkg/middlewares/passtlsclientcert/pass_tls_client_cert.go b/pkg/middlewares/passtlsclientcert/pass_tls_client_cert.go index e4304ec19..40c9bc186 100644 --- a/pkg/middlewares/passtlsclientcert/pass_tls_client_cert.go +++ b/pkg/middlewares/passtlsclientcert/pass_tls_client_cert.go @@ -139,7 +139,7 @@ func (p *passTLSClientCert) ServeHTTP(rw http.ResponseWriter, req *http.Request) // - the `,` is used to separate certificates // - the `;` is used to separate root fields // - the value of root fields is always wrapped by double quote -// - if a field is empty, the field is ignored +// - if a field is empty, the field is ignored. func (p *passTLSClientCert) getCertInfo(ctx context.Context, certs []*x509.Certificate) string { var headerValues []string diff --git a/pkg/middlewares/pipelining/pipelining.go b/pkg/middlewares/pipelining/pipelining.go index 4124b552f..671e676ac 100644 --- a/pkg/middlewares/pipelining/pipelining.go +++ b/pkg/middlewares/pipelining/pipelining.go @@ -14,12 +14,12 @@ const ( typeName = "Pipelining" ) -// pipelining returns a middleware +// pipelining returns a middleware. type pipelining struct { next http.Handler } -// New returns a new pipelining instance +// New returns a new pipelining instance. func New(ctx context.Context, next http.Handler, name string) http.Handler { log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName)).Debug("Creating middleware") @@ -37,7 +37,7 @@ func (p *pipelining) ServeHTTP(rw http.ResponseWriter, r *http.Request) { } } -// writerWithoutCloseNotify helps to disable closeNotify +// writerWithoutCloseNotify helps to disable closeNotify. type writerWithoutCloseNotify struct { W http.ResponseWriter } @@ -52,8 +52,7 @@ func (w *writerWithoutCloseNotify) Write(buf []byte) (int, error) { return w.W.Write(buf) } -// WriteHeader sends an HTTP response header with the provided -// status code. +// WriteHeader sends an HTTP response header with the provided status code. func (w *writerWithoutCloseNotify) WriteHeader(code int) { w.W.WriteHeader(code) } diff --git a/pkg/middlewares/replacepathregex/replace_path_regex.go b/pkg/middlewares/replacepathregex/replace_path_regex.go index 9aa755455..369417ffc 100644 --- a/pkg/middlewares/replacepathregex/replace_path_regex.go +++ b/pkg/middlewares/replacepathregex/replace_path_regex.go @@ -34,7 +34,7 @@ func New(ctx context.Context, next http.Handler, config dynamic.ReplacePathRegex exp, err := regexp.Compile(strings.TrimSpace(config.Regex)) if err != nil { - return nil, fmt.Errorf("error compiling regular expression %s: %s", config.Regex, err) + return nil, fmt.Errorf("error compiling regular expression %s: %w", config.Regex, err) } return &replacePathRegex{ diff --git a/pkg/middlewares/requestdecorator/hostresolver.go b/pkg/middlewares/requestdecorator/hostresolver.go index 3c4652231..91d2e7238 100644 --- a/pkg/middlewares/requestdecorator/hostresolver.go +++ b/pkg/middlewares/requestdecorator/hostresolver.go @@ -105,7 +105,7 @@ func cnameResolve(ctx context.Context, host string, resolvPath string) (*cnameRe func getRecord(client *dns.Client, msg *dns.Msg, server string, port string) (*cnameResolv, error) { resp, _, err := client.Exchange(msg, net.JoinHostPort(server, port)) if err != nil { - return nil, fmt.Errorf("exchange error for server %s: %v", server, err) + return nil, fmt.Errorf("exchange error for server %s: %w", server, err) } if resp == nil || len(resp.Answer) == 0 { diff --git a/pkg/middlewares/stateful.go b/pkg/middlewares/stateful.go index 4762d97a1..1b75d5450 100644 --- a/pkg/middlewares/stateful.go +++ b/pkg/middlewares/stateful.go @@ -3,7 +3,7 @@ package middlewares import "net/http" // Stateful interface groups all http interfaces that must be -// implemented by a stateful middleware (ie: recorders) +// implemented by a stateful middleware (ie: recorders). type Stateful interface { http.ResponseWriter http.Hijacker diff --git a/pkg/middlewares/tracing/mock_tracing_test.go b/pkg/middlewares/tracing/mock_tracing_test.go index 6ac60b738..f07e8921d 100644 --- a/pkg/middlewares/tracing/mock_tracing_test.go +++ b/pkg/middlewares/tracing/mock_tracing_test.go @@ -27,12 +27,12 @@ func (n MockTracer) Extract(format interface{}, carrier interface{}) (opentracin return nil, opentracing.ErrSpanContextNotFound } -// MockSpanContext +// MockSpanContext. type MockSpanContext struct{} func (n MockSpanContext) ForeachBaggageItem(handler func(k, v string) bool) {} -// MockSpan +// MockSpan. type MockSpan struct { OpName string Tags map[string]interface{} diff --git a/pkg/middlewares/tracing/status_code.go b/pkg/middlewares/tracing/status_code.go index ec1802467..9cec2e16c 100644 --- a/pkg/middlewares/tracing/status_code.go +++ b/pkg/middlewares/tracing/status_code.go @@ -22,12 +22,12 @@ func (s *statusCodeWithoutCloseNotify) WriteHeader(status int) { s.ResponseWriter.WriteHeader(status) } -// Status get response status +// Status get response status. func (s *statusCodeWithoutCloseNotify) Status() int { return s.status } -// Hijack hijacks the connection +// Hijack hijacks the connection. func (s *statusCodeWithoutCloseNotify) Hijack() (net.Conn, *bufio.ReadWriter, error) { return s.ResponseWriter.(http.Hijacker).Hijack() } diff --git a/pkg/middlewares/tracing/wrapper.go b/pkg/middlewares/tracing/wrapper.go index 1e4204914..9363d9e07 100644 --- a/pkg/middlewares/tracing/wrapper.go +++ b/pkg/middlewares/tracing/wrapper.go @@ -35,7 +35,7 @@ func Wrap(ctx context.Context, constructor alice.Constructor) alice.Constructor } } -// NewWrapper returns a http.Handler struct +// NewWrapper returns a http.Handler struct. func NewWrapper(next http.Handler, name string, spanKind ext.SpanKindEnum) http.Handler { return &Wrapper{ next: next, diff --git a/pkg/provider/acme/account.go b/pkg/provider/acme/account.go index 1959745be..40b2c05a3 100644 --- a/pkg/provider/acme/account.go +++ b/pkg/provider/acme/account.go @@ -12,7 +12,7 @@ import ( "github.com/go-acme/lego/v3/registration" ) -// Account is used to store lets encrypt registration info +// Account is used to store lets encrypt registration info. type Account struct { Email string Registration *registration.Resource @@ -21,11 +21,11 @@ type Account struct { } const ( - // RegistrationURLPathV1Regexp is a regexp which match ACME registration URL in the V1 format + // RegistrationURLPathV1Regexp is a regexp which match ACME registration URL in the V1 format. RegistrationURLPathV1Regexp = `^.*/acme/reg/\d+$` ) -// NewAccount creates an account +// NewAccount creates an account. func NewAccount(ctx context.Context, email string, keyTypeValue string) (*Account, error) { keyType := GetKeyType(ctx, keyTypeValue) @@ -42,17 +42,17 @@ func NewAccount(ctx context.Context, email string, keyTypeValue string) (*Accoun }, nil } -// GetEmail returns email +// GetEmail returns email. func (a *Account) GetEmail() string { return a.Email } -// GetRegistration returns lets encrypt registration resource +// GetRegistration returns lets encrypt registration resource. func (a *Account) GetRegistration() *registration.Resource { return a.Registration } -// GetPrivateKey returns private key +// GetPrivateKey returns private key. func (a *Account) GetPrivateKey() crypto.PrivateKey { privateKey, err := x509.ParsePKCS1PrivateKey(a.PrivateKey) if err != nil { @@ -64,7 +64,7 @@ func (a *Account) GetPrivateKey() crypto.PrivateKey { return privateKey } -// GetKeyType used to determine which algo to used +// GetKeyType used to determine which algo to used. func GetKeyType(ctx context.Context, value string) certcrypto.KeyType { logger := log.FromContext(ctx) diff --git a/pkg/provider/acme/local_store.go b/pkg/provider/acme/local_store.go index 0b76064e3..f92bd0810 100644 --- a/pkg/provider/acme/local_store.go +++ b/pkg/provider/acme/local_store.go @@ -13,7 +13,7 @@ import ( var _ Store = (*LocalStore)(nil) -// LocalStore Stores implementation for local file +// LocalStore Stores implementation for local file. type LocalStore struct { saveDataChan chan map[string]*StoredData filename string @@ -22,7 +22,7 @@ type LocalStore struct { storedData map[string]*StoredData } -// NewLocalStore initializes a new LocalStore with a file name +// NewLocalStore initializes a new LocalStore with a file name. func NewLocalStore(filename string) *LocalStore { store := &LocalStore{filename: filename, saveDataChan: make(chan map[string]*StoredData)} store.listenSaveAction() @@ -93,7 +93,7 @@ func (s *LocalStore) get(resolverName string) (*StoredData, error) { return s.storedData[resolverName], nil } -// listenSaveAction listens to a chan to store ACME data in json format into LocalStore.filename +// listenSaveAction listens to a chan to store ACME data in json format into `LocalStore.filename`. func (s *LocalStore) listenSaveAction() { safe.Go(func() { logger := log.WithoutContext().WithField(log.ProviderName, "acme") @@ -111,7 +111,7 @@ func (s *LocalStore) listenSaveAction() { }) } -// GetAccount returns ACME Account +// GetAccount returns ACME Account. func (s *LocalStore) GetAccount(resolverName string) (*Account, error) { storedData, err := s.get(resolverName) if err != nil { @@ -121,7 +121,7 @@ func (s *LocalStore) GetAccount(resolverName string) (*Account, error) { return storedData.Account, nil } -// SaveAccount stores ACME Account +// SaveAccount stores ACME Account. func (s *LocalStore) SaveAccount(resolverName string, account *Account) error { storedData, err := s.get(resolverName) if err != nil { @@ -134,7 +134,7 @@ func (s *LocalStore) SaveAccount(resolverName string, account *Account) error { return nil } -// GetCertificates returns ACME Certificates list +// GetCertificates returns ACME Certificates list. func (s *LocalStore) GetCertificates(resolverName string) ([]*CertAndStore, error) { storedData, err := s.get(resolverName) if err != nil { @@ -144,7 +144,7 @@ func (s *LocalStore) GetCertificates(resolverName string) ([]*CertAndStore, erro return storedData.Certificates, nil } -// SaveCertificates stores ACME Certificates list +// SaveCertificates stores ACME Certificates list. func (s *LocalStore) SaveCertificates(resolverName string, certificates []*CertAndStore) error { storedData, err := s.get(resolverName) if err != nil { @@ -173,7 +173,7 @@ func NewLocalChallengeStore() *LocalChallengeStore { } } -// GetHTTPChallengeToken Get the http challenge token from the store +// GetHTTPChallengeToken Get the http challenge token from the store. func (s *LocalChallengeStore) GetHTTPChallengeToken(token, domain string) ([]byte, error) { s.lock.RLock() defer s.lock.RUnlock() @@ -193,7 +193,7 @@ func (s *LocalChallengeStore) GetHTTPChallengeToken(token, domain string) ([]byt return result, nil } -// SetHTTPChallengeToken Set the http challenge token in the store +// SetHTTPChallengeToken Set the http challenge token in the store. func (s *LocalChallengeStore) SetHTTPChallengeToken(token, domain string, keyAuth []byte) error { s.lock.Lock() defer s.lock.Unlock() @@ -210,7 +210,7 @@ func (s *LocalChallengeStore) SetHTTPChallengeToken(token, domain string, keyAut return nil } -// RemoveHTTPChallengeToken Remove the http challenge token in the store +// RemoveHTTPChallengeToken Remove the http challenge token in the store. func (s *LocalChallengeStore) RemoveHTTPChallengeToken(token, domain string) error { s.lock.Lock() defer s.lock.Unlock() @@ -228,7 +228,7 @@ func (s *LocalChallengeStore) RemoveHTTPChallengeToken(token, domain string) err return nil } -// AddTLSChallenge Add a certificate to the ACME TLS-ALPN-01 certificates storage +// AddTLSChallenge Add a certificate to the ACME TLS-ALPN-01 certificates storage. func (s *LocalChallengeStore) AddTLSChallenge(domain string, cert *Certificate) error { s.lock.Lock() defer s.lock.Unlock() @@ -241,7 +241,7 @@ func (s *LocalChallengeStore) AddTLSChallenge(domain string, cert *Certificate) return nil } -// GetTLSChallenge Get a certificate from the ACME TLS-ALPN-01 certificates storage +// GetTLSChallenge Get a certificate from the ACME TLS-ALPN-01 certificates storage. func (s *LocalChallengeStore) GetTLSChallenge(domain string) (*Certificate, error) { s.lock.Lock() defer s.lock.Unlock() @@ -253,7 +253,7 @@ func (s *LocalChallengeStore) GetTLSChallenge(domain string) (*Certificate, erro return s.storedData.TLSChallenges[domain], nil } -// RemoveTLSChallenge Remove a certificate from the ACME TLS-ALPN-01 certificates storage +// RemoveTLSChallenge Remove a certificate from the ACME TLS-ALPN-01 certificates storage. func (s *LocalChallengeStore) RemoveTLSChallenge(domain string) error { s.lock.Lock() defer s.lock.Unlock() diff --git a/pkg/provider/acme/local_store_unix.go b/pkg/provider/acme/local_store_unix.go index 0dbb787be..edcd200a3 100644 --- a/pkg/provider/acme/local_store_unix.go +++ b/pkg/provider/acme/local_store_unix.go @@ -7,7 +7,7 @@ import ( "os" ) -// CheckFile checks file permissions and content size +// CheckFile checks file permissions and content size. func CheckFile(name string) (bool, error) { f, err := os.Open(name) if err != nil { diff --git a/pkg/provider/acme/provider.go b/pkg/provider/acme/provider.go index e0fddd06f..0f9ef03de 100644 --- a/pkg/provider/acme/provider.go +++ b/pkg/provider/acme/provider.go @@ -28,11 +28,11 @@ import ( ) var ( - // oscpMustStaple enables OSCP stapling as from https://github.com/go-acme/lego/issues/270 + // oscpMustStaple enables OSCP stapling as from https://github.com/go-acme/lego/issues/270. oscpMustStaple = false ) -// Configuration holds ACME configuration provided by users +// Configuration holds ACME configuration provided by users. type Configuration struct { Email string `description:"Email address used for registration." json:"email,omitempty" toml:"email,omitempty" yaml:"email,omitempty"` CAServer string `description:"CA server to use." json:"caServer,omitempty" toml:"caServer,omitempty" yaml:"caServer,omitempty"` @@ -56,14 +56,14 @@ type CertAndStore struct { Store string } -// Certificate is a struct which contains all data needed from an ACME certificate +// Certificate is a struct which contains all data needed from an ACME certificate. type Certificate struct { Domain types.Domain `json:"domain,omitempty" toml:"domain,omitempty" yaml:"domain,omitempty"` Certificate []byte `json:"certificate,omitempty" toml:"certificate,omitempty" yaml:"certificate,omitempty"` Key []byte `json:"key,omitempty" toml:"key,omitempty" yaml:"key,omitempty"` } -// DNSChallenge contains DNS challenge Configuration +// DNSChallenge contains DNS challenge Configuration. type DNSChallenge struct { Provider string `description:"Use a DNS-01 based challenge provider rather than HTTPS." json:"provider,omitempty" toml:"provider,omitempty" yaml:"provider,omitempty"` DelayBeforeCheck types.Duration `description:"Assume DNS propagates after a delay in seconds rather than finding and querying nameservers." json:"delayBeforeCheck,omitempty" toml:"delayBeforeCheck,omitempty" yaml:"delayBeforeCheck,omitempty"` @@ -71,12 +71,12 @@ type DNSChallenge struct { DisablePropagationCheck bool `description:"Disable the DNS propagation checks before notifying ACME that the DNS challenge is ready. [not recommended]" json:"disablePropagationCheck,omitempty" toml:"disablePropagationCheck,omitempty" yaml:"disablePropagationCheck,omitempty"` } -// HTTPChallenge contains HTTP challenge Configuration +// HTTPChallenge contains HTTP challenge Configuration. type HTTPChallenge struct { EntryPoint string `description:"HTTP challenge EntryPoint" json:"entryPoint,omitempty" toml:"entryPoint,omitempty" yaml:"entryPoint,omitempty"` } -// TLSChallenge contains TLS challenge Configuration +// TLSChallenge contains TLS challenge Configuration. type TLSChallenge struct{} // Provider holds configurations of the provider. @@ -98,22 +98,22 @@ type Provider struct { resolvingDomainsMutex sync.RWMutex } -// SetTLSManager sets the tls manager to use +// SetTLSManager sets the tls manager to use. func (p *Provider) SetTLSManager(tlsManager *traefiktls.Manager) { p.tlsManager = tlsManager } -// SetConfigListenerChan initializes the configFromListenerChan +// SetConfigListenerChan initializes the configFromListenerChan. func (p *Provider) SetConfigListenerChan(configFromListenerChan chan dynamic.Configuration) { p.configFromListenerChan = configFromListenerChan } -// ListenConfiguration sets a new Configuration into the configFromListenerChan +// ListenConfiguration sets a new Configuration into the configFromListenerChan. func (p *Provider) ListenConfiguration(config dynamic.Configuration) { p.configFromListenerChan <- config } -// Init for compatibility reason the BaseProvider implements an empty Init +// Init for compatibility reason the BaseProvider implements an empty Init. func (p *Provider) Init() error { ctx := log.With(context.Background(), log.Str(log.ProviderName, p.ResolverName+".acme")) logger := log.FromContext(ctx) @@ -125,7 +125,7 @@ func (p *Provider) Init() error { var err error p.account, err = p.Store.GetAccount(p.ResolverName) if err != nil { - return fmt.Errorf("unable to get ACME account: %v", err) + return fmt.Errorf("unable to get ACME account: %w", err) } // Reset Account if caServer changed, thus registration URI can be updated @@ -136,7 +136,7 @@ func (p *Provider) Init() error { p.certificates, err = p.Store.GetCertificates(p.ResolverName) if err != nil { - return fmt.Errorf("unable to get ACME certificates : %v", err) + return fmt.Errorf("unable to get ACME certificates : %w", err) } // Init the currently resolved domain map @@ -442,7 +442,7 @@ func (p *Provider) resolveCertificate(ctx context.Context, domain types.Domain, client, err := p.getClient() if err != nil { - return nil, fmt.Errorf("cannot get ACME client %v", err) + return nil, fmt.Errorf("cannot get ACME client %w", err) } request := certificate.ObtainRequest{ @@ -453,7 +453,7 @@ func (p *Provider) resolveCertificate(ctx context.Context, domain types.Domain, cert, err := client.Certificate.Obtain(request) if err != nil { - return nil, fmt.Errorf("unable to generate a certificate for the domains %v: %v", uncheckedDomains, err) + return nil, fmt.Errorf("unable to generate a certificate for the domains %v: %w", uncheckedDomains, err) } if cert == nil { return nil, fmt.Errorf("domains %v do not generate a certificate", uncheckedDomains) @@ -498,7 +498,7 @@ func (p *Provider) addCertificateForDomain(domain types.Domain, certificate []by // deleteUnnecessaryDomains deletes from the configuration : // - Duplicated domains -// - Domains which are checked by wildcard domain +// - Domains which are checked by wildcard domain. func deleteUnnecessaryDomains(ctx context.Context, domains []types.Domain) []types.Domain { var newDomains []types.Domain @@ -657,7 +657,7 @@ func (p *Provider) renewCertificates(ctx context.Context) { } // Get provided certificate which check a domains list (Main and SANs) -// from static and dynamic provided certificates +// from static and dynamic provided certificates. func (p *Provider) getUncheckedDomains(ctx context.Context, domainsToCheck []string, tlsStore string) []string { p.resolvingDomainsMutex.RLock() defer p.resolvingDomainsMutex.RUnlock() @@ -716,7 +716,7 @@ func getX509Certificate(ctx context.Context, cert *Certificate) (*x509.Certifica return crt, err } -// getValidDomains checks if given domain is allowed to generate a ACME certificate and return it +// getValidDomains checks if given domain is allowed to generate a ACME certificate and return it. func (p *Provider) getValidDomains(ctx context.Context, domain types.Domain) ([]string, error) { domains := domain.ToStrArray() if len(domains) == 0 { diff --git a/pkg/provider/aggregator/aggregator.go b/pkg/provider/aggregator/aggregator.go index 526d0c620..faa5e784d 100644 --- a/pkg/provider/aggregator/aggregator.go +++ b/pkg/provider/aggregator/aggregator.go @@ -94,12 +94,12 @@ func (p *ProviderAggregator) AddProvider(provider provider.Provider) error { return nil } -// Init the provider +// Init the provider. func (p ProviderAggregator) Init() error { return nil } -// Provide calls the provide method of every providers +// Provide calls the provide method of every providers. func (p ProviderAggregator) Provide(configurationChan chan<- dynamic.Message, pool *safe.Pool) error { if p.fileProvider != nil { launchProvider(configurationChan, pool, p.fileProvider) diff --git a/pkg/provider/constraints/constraints_labels.go b/pkg/provider/constraints/constraints_labels.go index cbaa5086b..6f194ba33 100644 --- a/pkg/provider/constraints/constraints_labels.go +++ b/pkg/provider/constraints/constraints_labels.go @@ -18,7 +18,7 @@ type constraintLabelFunc func(map[string]string) bool // The expression must match any logical boolean combination of: // - `Label(labelName, labelValue)` // - `LabelRegex(labelName, regexValue)` -// - `MarathonConstraint(field:operator:value)` +// - `MarathonConstraint(field:operator:value)`. func MatchLabels(labels map[string]string, expr string) (bool, error) { if expr == "" { return true, nil diff --git a/pkg/provider/constraints/constraints_tags.go b/pkg/provider/constraints/constraints_tags.go index 2a2fa3ffa..cb29997a3 100644 --- a/pkg/provider/constraints/constraints_tags.go +++ b/pkg/provider/constraints/constraints_tags.go @@ -12,7 +12,7 @@ type constraintTagFunc func([]string) bool // MatchTags reports whether the expression matches with the given tags. // The expression must match any logical boolean combination of: // - `Tag(tagValue)` -// - `TagRegex(regexValue)` +// - `TagRegex(regexValue)`. func MatchTags(tags []string, expr string) (bool, error) { if expr == "" { return true, nil diff --git a/pkg/provider/consulcatalog/consul_catalog.go b/pkg/provider/consulcatalog/consul_catalog.go index 020505bf5..01b70579e 100644 --- a/pkg/provider/consulcatalog/consul_catalog.go +++ b/pkg/provider/consulcatalog/consul_catalog.go @@ -89,7 +89,7 @@ func (p *Provider) SetDefaults() { func (p *Provider) Init() error { defaultRuleTpl, err := provider.MakeDefaultRuleTemplate(p.DefaultRule, nil) if err != nil { - return fmt.Errorf("error while parsing default rule: %v", err) + return fmt.Errorf("error while parsing default rule: %w", err) } p.defaultRuleTpl = defaultRuleTpl @@ -107,7 +107,7 @@ func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe. p.client, err = createClient(p.Endpoint) if err != nil { - return fmt.Errorf("error create consul client, %v", err) + return fmt.Errorf("error create consul client, %w", err) } ticker := time.NewTicker(time.Duration(p.RefreshInterval)) diff --git a/pkg/provider/docker/docker.go b/pkg/provider/docker/docker.go index 8e5c769ff..8ca9405fe 100644 --- a/pkg/provider/docker/docker.go +++ b/pkg/provider/docker/docker.go @@ -73,7 +73,7 @@ func (p *Provider) SetDefaults() { func (p *Provider) Init() error { defaultRuleTpl, err := provider.MakeDefaultRuleTemplate(p.DefaultRule, nil) if err != nil { - return fmt.Errorf("error while parsing default rule: %v", err) + return fmt.Errorf("error while parsing default rule: %w", err) } p.defaultRuleTpl = defaultRuleTpl diff --git a/pkg/provider/docker/label.go b/pkg/provider/docker/label.go index 131d852a3..34b044803 100644 --- a/pkg/provider/docker/label.go +++ b/pkg/provider/docker/label.go @@ -11,7 +11,8 @@ const ( labelDockerComposeService = "com.docker.compose.service" ) -// configuration Contains information from the labels that are globals (not related to the dynamic configuration) or specific to the provider. +// configuration Contains information from the labels that are globals (not related to the dynamic configuration) +// or specific to the provider. type configuration struct { Enable bool Docker specificConfiguration @@ -38,8 +39,8 @@ func (p *Provider) getConfiguration(container dockerData) (configuration, error) return conf, nil } -// getStringMultipleStrict get multiple string values associated to several labels -// Fail if one label is missing +// getStringMultipleStrict get multiple string values associated to several labels. +// Fail if one label is missing. func getStringMultipleStrict(labels map[string]string, labelNames ...string) (map[string]string, error) { foundLabels := map[string]string{} for _, name := range labelNames { @@ -53,7 +54,7 @@ func getStringMultipleStrict(labels map[string]string, labelNames ...string) (ma return foundLabels, nil } -// getStringValue get string value associated to a label +// getStringValue get string value associated to a label. func getStringValue(labels map[string]string, labelName string, defaultValue string) string { if value, ok := labels[labelName]; ok && len(value) > 0 { return value diff --git a/pkg/provider/file/file.go b/pkg/provider/file/file.go index bc4a4e0c5..879023a00 100644 --- a/pkg/provider/file/file.go +++ b/pkg/provider/file/file.go @@ -40,7 +40,7 @@ func (p *Provider) SetDefaults() { p.Filename = "" } -// Init the provider +// Init the provider. func (p *Provider) Init() error { return nil } @@ -75,8 +75,8 @@ func (p *Provider) Provide(configurationChan chan<- dynamic.Message, pool *safe. return nil } -// BuildConfiguration loads configuration either from file or a directory specified by 'Filename'/'Directory' -// and returns a 'Configuration' object +// BuildConfiguration loads configuration either from file or a directory +// specified by 'Filename'/'Directory' and returns a 'Configuration' object. func (p *Provider) BuildConfiguration() (*dynamic.Configuration, error) { ctx := log.With(context.Background(), log.Str(log.ProviderName, providerName)) @@ -94,12 +94,12 @@ func (p *Provider) BuildConfiguration() (*dynamic.Configuration, error) { func (p *Provider) addWatcher(pool *safe.Pool, directory string, configurationChan chan<- dynamic.Message, callback func(chan<- dynamic.Message, fsnotify.Event)) error { watcher, err := fsnotify.NewWatcher() if err != nil { - return fmt.Errorf("error creating file watcher: %s", err) + return fmt.Errorf("error creating file watcher: %w", err) } err = watcher.Add(directory) if err != nil { - return fmt.Errorf("error adding file watcher: %s", err) + return fmt.Errorf("error adding file watcher: %w", err) } // Process events @@ -201,7 +201,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) if err != nil { - return configuration, fmt.Errorf("unable to read directory %s: %v", directory, err) + return configuration, fmt.Errorf("unable to read directory %s: %w", directory, err) } if configuration == nil { @@ -234,7 +234,7 @@ func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory st if item.IsDir() { configuration, err = p.loadFileConfigFromDirectory(ctx, filepath.Join(directory, item.Name()), configuration) if err != nil { - return configuration, fmt.Errorf("unable to load content configuration from subdirectory %s: %v", item, err) + return configuration, fmt.Errorf("unable to load content configuration from subdirectory %s: %w", item, err) } continue } @@ -249,7 +249,7 @@ func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory st var c *dynamic.Configuration c, err = p.loadFileConfig(ctx, filepath.Join(directory, item.Name()), true) if err != nil { - return configuration, fmt.Errorf("%s: %v", filepath.Join(directory, item.Name()), err) + return configuration, fmt.Errorf("%s: %w", filepath.Join(directory, item.Name()), err) } for name, conf := range c.HTTP.Routers { @@ -354,7 +354,7 @@ func (p *Provider) loadFileConfigFromDirectory(ctx context.Context, directory st func (p *Provider) CreateConfiguration(ctx context.Context, filename string, funcMap template.FuncMap, templateObjects interface{}) (*dynamic.Configuration, error) { tmplContent, err := readFile(filename) if err != nil { - return nil, fmt.Errorf("error reading configuration file: %s - %s", filename, err) + return nil, fmt.Errorf("error reading configuration file: %s - %w", filename, err) } var defaultFuncMap = sprig.TxtFuncMap() @@ -391,7 +391,7 @@ func (p *Provider) CreateConfiguration(ctx context.Context, filename string, fun func (p *Provider) DecodeConfiguration(filename string) (*dynamic.Configuration, error) { content, err := readFile(filename) if err != nil { - return nil, fmt.Errorf("error reading configuration file: %s - %s", filename, err) + return nil, fmt.Errorf("error reading configuration file: %s - %w", filename, err) } return p.decodeConfiguration(filename, content) diff --git a/pkg/provider/file/file_test.go b/pkg/provider/file/file_test.go index b89007c1d..fa7fd39ed 100644 --- a/pkg/provider/file/file_test.go +++ b/pkg/provider/file/file_test.go @@ -280,7 +280,7 @@ func createProvider(t *testing.T, test ProvideTestCase, watch bool) (*Provider, } } -// createTempDir Helper +// createTempDir Helper. func createTempDir(t *testing.T, dir string) string { t.Helper() diff --git a/pkg/provider/kubernetes/crd/client.go b/pkg/provider/kubernetes/crd/client.go index 4a36bfa93..e13e8a34c 100644 --- a/pkg/provider/kubernetes/crd/client.go +++ b/pkg/provider/kubernetes/crd/client.go @@ -101,7 +101,7 @@ func newClientImpl(csKube *kubernetes.Clientset, csCrd *versioned.Clientset) *cl func newInClusterClient(endpoint string) (*clientWrapper, error) { config, err := rest.InClusterConfig() if err != nil { - return nil, fmt.Errorf("failed to create in-cluster configuration: %v", err) + return nil, fmt.Errorf("failed to create in-cluster configuration: %w", err) } if endpoint != "" { @@ -135,7 +135,7 @@ func newExternalClusterClient(endpoint, token, caFilePath string) (*clientWrappe if caFilePath != "" { caData, err := ioutil.ReadFile(caFilePath) if err != nil { - return nil, fmt.Errorf("failed to read CA file %s: %v", caFilePath, err) + return nil, fmt.Errorf("failed to read CA file %s: %w", caFilePath, err) } config.TLSClientConfig = rest.TLSClientConfig{CAData: caData} diff --git a/pkg/provider/kubernetes/crd/kubernetes.go b/pkg/provider/kubernetes/crd/kubernetes.go index 0ddaf4a6f..ddd7f4a98 100644 --- a/pkg/provider/kubernetes/crd/kubernetes.go +++ b/pkg/provider/kubernetes/crd/kubernetes.go @@ -325,7 +325,7 @@ func createForwardAuthMiddleware(k8sClient Client, namespace string, auth *v1alp if len(auth.TLS.CASecret) > 0 { caSecret, err := loadCASecret(namespace, auth.TLS.CASecret, k8sClient) if err != nil { - return nil, fmt.Errorf("failed to load auth ca secret: %v", err) + return nil, fmt.Errorf("failed to load auth ca secret: %w", err) } forwardAuth.TLS.CA = caSecret } @@ -333,7 +333,7 @@ func createForwardAuthMiddleware(k8sClient Client, namespace string, auth *v1alp if len(auth.TLS.CertSecret) > 0 { authSecretCert, authSecretKey, err := loadAuthTLSSecret(namespace, auth.TLS.CertSecret, k8sClient) if err != nil { - return nil, fmt.Errorf("failed to load auth secret: %v", err) + return nil, fmt.Errorf("failed to load auth secret: %w", err) } forwardAuth.TLS.Cert = authSecretCert forwardAuth.TLS.Key = authSecretKey @@ -345,7 +345,7 @@ func createForwardAuthMiddleware(k8sClient Client, namespace string, auth *v1alp func loadCASecret(namespace, secretName string, k8sClient Client) (string, error) { secret, ok, err := k8sClient.GetSecret(namespace, secretName) if err != nil { - return "", fmt.Errorf("failed to fetch secret '%s/%s': %v", namespace, secretName, err) + return "", fmt.Errorf("failed to fetch secret '%s/%s': %w", namespace, secretName, err) } if !ok { return "", fmt.Errorf("secret '%s/%s' not found", namespace, secretName) @@ -366,7 +366,7 @@ func loadCASecret(namespace, secretName string, k8sClient Client) (string, error func loadAuthTLSSecret(namespace, secretName string, k8sClient Client) (string, string, error) { secret, exists, err := k8sClient.GetSecret(namespace, secretName) if err != nil { - return "", "", fmt.Errorf("failed to fetch secret '%s/%s': %s", namespace, secretName, err) + return "", "", fmt.Errorf("failed to fetch secret '%s/%s': %w", namespace, secretName, err) } if !exists { return "", "", fmt.Errorf("secret '%s/%s' does not exist", namespace, secretName) @@ -424,7 +424,7 @@ func getAuthCredentials(k8sClient Client, authSecret, namespace string) ([]strin auth, err := loadAuthCredentials(namespace, authSecret, k8sClient) if err != nil { - return nil, fmt.Errorf("failed to load auth credentials: %v", err) + return nil, fmt.Errorf("failed to load auth credentials: %w", err) } return auth, nil @@ -433,7 +433,7 @@ func getAuthCredentials(k8sClient Client, authSecret, namespace string) ([]strin func loadAuthCredentials(namespace, secretName string, k8sClient Client) ([]string, error) { secret, ok, err := k8sClient.GetSecret(namespace, secretName) if err != nil { - return nil, fmt.Errorf("failed to fetch secret '%s/%s': %v", namespace, secretName, err) + return nil, fmt.Errorf("failed to fetch secret '%s/%s': %w", namespace, secretName, err) } if !ok { return nil, fmt.Errorf("secret '%s/%s' not found", namespace, secretName) @@ -459,7 +459,7 @@ func loadAuthCredentials(namespace, secretName string, k8sClient Client) ([]stri } } if err := scanner.Err(); err != nil { - return nil, fmt.Errorf("error reading secret for %s/%s: %v", namespace, secretName, err) + return nil, fmt.Errorf("error reading secret for %s/%s: %w", namespace, secretName, err) } if len(credentials) == 0 { return nil, fmt.Errorf("secret '%s/%s' does not contain any credentials", namespace, secretName) @@ -641,7 +641,7 @@ func shouldProcessIngress(ingressClass string, ingressClassAnnotation string) bo func getTLS(k8sClient Client, secretName, namespace string) (*tls.CertAndStores, error) { secret, exists, err := k8sClient.GetSecret(namespace, secretName) if err != nil { - return nil, fmt.Errorf("failed to fetch secret %s/%s: %v", namespace, secretName, err) + return nil, fmt.Errorf("failed to fetch secret %s/%s: %w", namespace, secretName, err) } if !exists { return nil, fmt.Errorf("secret %s/%s does not exist", namespace, secretName) diff --git a/pkg/provider/kubernetes/crd/traefik/v1alpha1/middleware.go b/pkg/provider/kubernetes/crd/traefik/v1alpha1/middleware.go index 2fa83438d..437546bdb 100644 --- a/pkg/provider/kubernetes/crd/traefik/v1alpha1/middleware.go +++ b/pkg/provider/kubernetes/crd/traefik/v1alpha1/middleware.go @@ -55,7 +55,7 @@ type ErrorPage struct { // +k8s:deepcopy-gen=true -// Chain holds a chain of middlewares +// Chain holds a chain of middlewares. type Chain struct { Middlewares []MiddlewareRef `json:"middlewares,omitempty"` } diff --git a/pkg/provider/kubernetes/crd/traefik/v1alpha1/tlsoption.go b/pkg/provider/kubernetes/crd/traefik/v1alpha1/tlsoption.go index ed0e0df62..6c6b67ad8 100644 --- a/pkg/provider/kubernetes/crd/traefik/v1alpha1/tlsoption.go +++ b/pkg/provider/kubernetes/crd/traefik/v1alpha1/tlsoption.go @@ -17,7 +17,7 @@ type TLSOption struct { // +k8s:deepcopy-gen=true -// TLSOptionSpec configures TLS for an entry point +// TLSOptionSpec configures TLS for an entry point. type TLSOptionSpec struct { MinVersion string `json:"minVersion,omitempty"` MaxVersion string `json:"maxVersion,omitempty"` diff --git a/pkg/provider/kubernetes/ingress/client.go b/pkg/provider/kubernetes/ingress/client.go index 872099c71..5a569f5dc 100644 --- a/pkg/provider/kubernetes/ingress/client.go +++ b/pkg/provider/kubernetes/ingress/client.go @@ -68,7 +68,7 @@ type clientWrapper struct { func newInClusterClient(endpoint string) (*clientWrapper, error) { config, err := rest.InClusterConfig() if err != nil { - return nil, fmt.Errorf("failed to create in-cluster configuration: %s", err) + return nil, fmt.Errorf("failed to create in-cluster configuration: %w", err) } if endpoint != "" { @@ -102,7 +102,7 @@ func newExternalClusterClient(endpoint, token, caFilePath string) (*clientWrappe if caFilePath != "" { caData, err := ioutil.ReadFile(caFilePath) if err != nil { - return nil, fmt.Errorf("failed to read CA file %s: %s", caFilePath, err) + return nil, fmt.Errorf("failed to read CA file %s: %w", caFilePath, err) } config.TLSClientConfig = rest.TLSClientConfig{CAData: caData} @@ -219,7 +219,7 @@ func (c *clientWrapper) UpdateIngressStatus(src *networkingv1beta1.Ingress, ip, ing, err := c.factories[c.lookupNamespace(src.Namespace)].Networking().V1beta1().Ingresses().Lister().Ingresses(src.Namespace).Get(src.Name) if err != nil { - return fmt.Errorf("failed to get ingress %s/%s: %v", src.Namespace, src.Name, err) + return fmt.Errorf("failed to get ingress %s/%s: %w", src.Namespace, src.Name, err) } if len(ing.Status.LoadBalancer.Ingress) > 0 { @@ -238,7 +238,7 @@ func (c *clientWrapper) UpdateIngressStatus(src *networkingv1beta1.Ingress, ip, _, err = c.clientset.NetworkingV1beta1().Ingresses(ingCopy.Namespace).UpdateStatus(ctx, ingCopy, metav1.UpdateOptions{}) if err != nil { - return fmt.Errorf("failed to update ingress status %s/%s: %v", src.Namespace, src.Name, err) + return fmt.Errorf("failed to update ingress status %s/%s: %w", src.Namespace, src.Name, err) } log.Infof("Updated status on ingress %s/%s", src.Namespace, src.Name) @@ -248,7 +248,7 @@ func (c *clientWrapper) UpdateIngressStatus(src *networkingv1beta1.Ingress, ip, func (c *clientWrapper) updateIngressStatusOld(src *networkingv1beta1.Ingress, ip, hostname string) error { ing, err := c.factories[c.lookupNamespace(src.Namespace)].Extensions().V1beta1().Ingresses().Lister().Ingresses(src.Namespace).Get(src.Name) if err != nil { - return fmt.Errorf("failed to get ingress %s/%s: %v", src.Namespace, src.Name, err) + return fmt.Errorf("failed to get ingress %s/%s: %w", src.Namespace, src.Name, err) } if len(ing.Status.LoadBalancer.Ingress) > 0 { @@ -267,7 +267,7 @@ func (c *clientWrapper) updateIngressStatusOld(src *networkingv1beta1.Ingress, i _, err = c.clientset.ExtensionsV1beta1().Ingresses(ingCopy.Namespace).UpdateStatus(ctx, ingCopy, metav1.UpdateOptions{}) if err != nil { - return fmt.Errorf("failed to update ingress status %s/%s: %v", src.Namespace, src.Name, err) + return fmt.Errorf("failed to update ingress status %s/%s: %w", src.Namespace, src.Name, err) } log.Infof("Updated status on ingress %s/%s", src.Namespace, src.Name) diff --git a/pkg/provider/kubernetes/ingress/kubernetes.go b/pkg/provider/kubernetes/ingress/kubernetes.go index ce27491d5..149ab47e3 100644 --- a/pkg/provider/kubernetes/ingress/kubernetes.go +++ b/pkg/provider/kubernetes/ingress/kubernetes.go @@ -46,7 +46,7 @@ type Provider struct { lastConfiguration safe.Safe } -// EndpointIngress holds the endpoint information for the Kubernetes provider +// EndpointIngress holds the endpoint information for the Kubernetes provider. type EndpointIngress struct { IP string `description:"IP used for Kubernetes Ingress endpoints." json:"ip,omitempty" toml:"ip,omitempty" yaml:"ip,omitempty"` Hostname string `description:"Hostname used for Kubernetes Ingress endpoints." json:"hostname,omitempty" toml:"hostname,omitempty" yaml:"hostname,omitempty"` @@ -306,7 +306,7 @@ func (p *Provider) updateIngressStatus(ing *v1beta1.Ingress, k8sClient Client) e service, exists, err := k8sClient.GetService(serviceNamespace, serviceName) if err != nil { - return fmt.Errorf("cannot get service %s, received error: %s", p.IngressEndpoint.PublishedService, err) + return fmt.Errorf("cannot get service %s, received error: %w", p.IngressEndpoint.PublishedService, err) } if exists && service.Status.LoadBalancer.Ingress == nil { @@ -346,7 +346,7 @@ func getCertificates(ctx context.Context, ingress *v1beta1.Ingress, k8sClient Cl if _, tlsExists := tlsConfigs[configKey]; !tlsExists { secret, exists, err := k8sClient.GetSecret(ingress.Namespace, t.SecretName) if err != nil { - return fmt.Errorf("failed to fetch secret %s/%s: %v", ingress.Namespace, t.SecretName, err) + return fmt.Errorf("failed to fetch secret %s/%s: %w", ingress.Namespace, t.SecretName, err) } if !exists { return fmt.Errorf("secret %s/%s does not exist", ingress.Namespace, t.SecretName) diff --git a/pkg/provider/kv/consul/consul.go b/pkg/provider/kv/consul/consul.go index 8cefad995..77eb44bb4 100644 --- a/pkg/provider/kv/consul/consul.go +++ b/pkg/provider/kv/consul/consul.go @@ -19,7 +19,7 @@ func (p *Provider) SetDefaults() { p.Endpoints = []string{"127.0.0.1:8500"} } -// Init the provider +// Init the provider. func (p *Provider) Init() error { return p.Provider.Init(store.CONSUL, "consul") } diff --git a/pkg/provider/kv/etcd/etcd.go b/pkg/provider/kv/etcd/etcd.go index 5d104c742..3264140b3 100644 --- a/pkg/provider/kv/etcd/etcd.go +++ b/pkg/provider/kv/etcd/etcd.go @@ -19,7 +19,7 @@ func (p *Provider) SetDefaults() { p.Endpoints = []string{"127.0.0.1:2379"} } -// Init the provider +// Init the provider. func (p *Provider) Init() error { return p.Provider.Init(store.ETCDV3, "etcd") } diff --git a/pkg/provider/kv/kv.go b/pkg/provider/kv/kv.go index b0b4d11a3..a661b3e94 100644 --- a/pkg/provider/kv/kv.go +++ b/pkg/provider/kv/kv.go @@ -41,7 +41,7 @@ func (p *Provider) SetDefaults() { p.RootKey = "traefik" } -// Init the provider +// Init the provider. func (p *Provider) Init(storeType store.Backend, name string) error { ctx := log.With(context.Background(), log.Str(log.ProviderName, name)) diff --git a/pkg/provider/kv/kv_mock_test.go b/pkg/provider/kv/kv_mock_test.go index 0d63d8825..c33cee3d2 100644 --- a/pkg/provider/kv/kv_mock_test.go +++ b/pkg/provider/kv/kv_mock_test.go @@ -14,13 +14,13 @@ func newProviderMock(kvPairs []*store.KVPair) *Provider { } } -// Override Get/List to return a error +// Override Get/List to return a error. type KvError struct { Get error List error } -// Extremely limited mock store so we can test initialization +// Extremely limited mock store so we can test initialization. type Mock struct { Error KvError KVPairs []*store.KVPair @@ -61,7 +61,7 @@ func (s *Mock) Delete(key string) error { return errors.New("method Delete not supported") } -// Exists mock +// Exists mock. func (s *Mock) Exists(key string, options *store.ReadOptions) (bool, error) { if err := s.Error.Get; err != nil { return false, err @@ -74,22 +74,22 @@ func (s *Mock) Exists(key string, options *store.ReadOptions) (bool, error) { return false, store.ErrKeyNotFound } -// Watch mock +// Watch mock. func (s *Mock) Watch(key string, stopCh <-chan struct{}, options *store.ReadOptions) (<-chan *store.KVPair, error) { return nil, errors.New("method Watch not supported") } -// WatchTree mock +// WatchTree mock. func (s *Mock) WatchTree(prefix string, stopCh <-chan struct{}, options *store.ReadOptions) (<-chan []*store.KVPair, error) { return s.WatchTreeMethod(), nil } -// NewLock mock +// NewLock mock. func (s *Mock) NewLock(key string, options *store.LockOptions) (store.Locker, error) { return nil, errors.New("method NewLock not supported") } -// List mock +// List mock. func (s *Mock) List(prefix string, options *store.ReadOptions) ([]*store.KVPair, error) { if err := s.Error.List; err != nil { return nil, err @@ -103,20 +103,20 @@ func (s *Mock) List(prefix string, options *store.ReadOptions) ([]*store.KVPair, return kv, nil } -// DeleteTree mock +// DeleteTree mock. func (s *Mock) DeleteTree(prefix string) error { return errors.New("method DeleteTree not supported") } -// AtomicPut mock +// AtomicPut mock. func (s *Mock) AtomicPut(key string, value []byte, previous *store.KVPair, opts *store.WriteOptions) (bool, *store.KVPair, error) { return false, nil, errors.New("method AtomicPut not supported") } -// AtomicDelete mock +// AtomicDelete mock. func (s *Mock) AtomicDelete(key string, previous *store.KVPair) (bool, error) { return false, errors.New("method AtomicDelete not supported") } -// Close mock +// Close mock. func (s *Mock) Close() {} diff --git a/pkg/provider/kv/redis/redis.go b/pkg/provider/kv/redis/redis.go index 10ec299b8..c4b33a67e 100644 --- a/pkg/provider/kv/redis/redis.go +++ b/pkg/provider/kv/redis/redis.go @@ -19,7 +19,7 @@ func (p *Provider) SetDefaults() { p.Endpoints = []string{"127.0.0.1:6379"} } -// Init the provider +// Init the provider. func (p *Provider) Init() error { return p.Provider.Init(store.REDIS, "redis") } diff --git a/pkg/provider/kv/zk/zk.go b/pkg/provider/kv/zk/zk.go index 26c7d8956..f71388e54 100644 --- a/pkg/provider/kv/zk/zk.go +++ b/pkg/provider/kv/zk/zk.go @@ -19,7 +19,7 @@ func (p *Provider) SetDefaults() { p.Endpoints = []string{"127.0.0.1:2181"} } -// Init the provider +// Init the provider. func (p *Provider) Init() error { return p.Provider.Init(store.ZK, "zookeeper") } diff --git a/pkg/provider/marathon/config.go b/pkg/provider/marathon/config.go index 6d16efa7c..f1382fd68 100644 --- a/pkg/provider/marathon/config.go +++ b/pkg/provider/marathon/config.go @@ -362,7 +362,7 @@ func (p *Provider) getServerHost(task marathon.Task, app marathon.Application, e func getPort(task marathon.Task, app marathon.Application, serverPort string) (string, error) { port, err := processPorts(app, task, serverPort) if err != nil { - return "", fmt.Errorf("unable to process ports for %s %s: %v", app.ID, task.ID, err) + return "", fmt.Errorf("unable to process ports for %s %s: %w", app.ID, task.ID, err) } return strconv.Itoa(port), nil diff --git a/pkg/provider/marathon/marathon.go b/pkg/provider/marathon/marathon.go index c11b7a6ee..2c0f13670 100644 --- a/pkg/provider/marathon/marathon.go +++ b/pkg/provider/marathon/marathon.go @@ -77,13 +77,13 @@ func (p *Provider) SetDefaults() { p.DefaultRule = DefaultTemplateRule } -// Basic holds basic authentication specific configurations +// Basic holds basic authentication specific configurations. type Basic struct { HTTPBasicAuthUser string `description:"Basic authentication User." json:"httpBasicAuthUser,omitempty" toml:"httpBasicAuthUser,omitempty" yaml:"httpBasicAuthUser,omitempty"` HTTPBasicPassword string `description:"Basic authentication Password." json:"httpBasicPassword,omitempty" toml:"httpBasicPassword,omitempty" yaml:"httpBasicPassword,omitempty"` } -// Init the provider +// Init the provider. func (p *Provider) Init() error { fm := template.FuncMap{ "strsToItfs": func(values []string) []interface{} { @@ -97,7 +97,7 @@ func (p *Provider) Init() error { defaultRuleTpl, err := provider.MakeDefaultRuleTemplate(p.DefaultRule, fm) if err != nil { - return fmt.Errorf("error while parsing default rule: %v", err) + return fmt.Errorf("error while parsing default rule: %w", err) } p.defaultRuleTpl = defaultRuleTpl diff --git a/pkg/provider/rancher/rancher.go b/pkg/provider/rancher/rancher.go index b6fbbcd0e..b0329e894 100644 --- a/pkg/provider/rancher/rancher.go +++ b/pkg/provider/rancher/rancher.go @@ -20,13 +20,13 @@ const ( DefaultTemplateRule = "Host(`{{ normalize .Name }}`)" ) -// Health +// Health. const ( healthy = "healthy" updatingHealthy = "updating-healthy" ) -// State +// States. const ( active = "active" running = "running" @@ -75,7 +75,7 @@ type rancherData struct { func (p *Provider) Init() error { defaultRuleTpl, err := provider.MakeDefaultRuleTemplate(p.DefaultRule, nil) if err != nil { - return fmt.Errorf("error while parsing default rule: %v", err) + return fmt.Errorf("error while parsing default rule: %w", err) } p.defaultRuleTpl = defaultRuleTpl diff --git a/pkg/provider/rest/rest.go b/pkg/provider/rest/rest.go index 350228fde..09d989da8 100644 --- a/pkg/provider/rest/rest.go +++ b/pkg/provider/rest/rest.go @@ -31,7 +31,7 @@ func (p *Provider) Init() error { return nil } -// CreateRouter creates a router for the Rest API +// CreateRouter creates a router for the Rest API. func (p *Provider) CreateRouter() *mux.Router { router := mux.NewRouter() router.Methods(http.MethodPut).Path("/api/providers/{provider}").Handler(p) diff --git a/pkg/provider/traefik/internal.go b/pkg/provider/traefik/internal.go index d78c28657..0c25420c5 100644 --- a/pkg/provider/traefik/internal.go +++ b/pkg/provider/traefik/internal.go @@ -144,7 +144,7 @@ func (i *Provider) getEntryPointPort(name string, def *static.Redirections) (str _, port, err := net.SplitHostPort(dst.Address) if err != nil { - return "", fmt.Errorf("invalid entry point %q address %q: %v", + return "", fmt.Errorf("invalid entry point %q address %q: %w", name, i.staticCfg.EntryPoints[def.EntryPoint.To].Address, err) } diff --git a/pkg/rules/parser.go b/pkg/rules/parser.go index dbf00f186..99b410e52 100644 --- a/pkg/rules/parser.go +++ b/pkg/rules/parser.go @@ -9,7 +9,7 @@ import ( type treeBuilder func() *tree -// ParseDomains extract domains from rule +// ParseDomains extract domains from rule. func ParseDomains(rule string) ([]string, error) { parser, err := newParser() if err != nil { @@ -29,8 +29,8 @@ func ParseDomains(rule string) ([]string, error) { return lower(parseDomain(buildTree())), nil } -// ParseHostSNI extracts the HostSNIs declared in a rule -// This is a first naive implementation used in TCP routing +// ParseHostSNI extracts the HostSNIs declared in a rule. +// This is a first naive implementation used in TCP routing. func ParseHostSNI(rule string) ([]string, error) { parser, err := newTCPParser() if err != nil { diff --git a/pkg/rules/rules.go b/pkg/rules/rules.go index 441c4b668..797a669eb 100644 --- a/pkg/rules/rules.go +++ b/pkg/rules/rules.go @@ -22,7 +22,7 @@ var funcs = map[string]func(*mux.Route, ...string) error{ "Query": query, } -// Router handle routing with rules +// Router handle routing with rules. type Router struct { *mux.Router parser predicate.Parser @@ -45,7 +45,7 @@ func NewRouter() (*Router, error) { func (r *Router) AddRoute(rule string, priority int, handler http.Handler) error { parse, err := r.parser.Parse(rule) if err != nil { - return fmt.Errorf("error while parsing rule %s: %v", rule, err) + return fmt.Errorf("error while parsing rule %s: %w", rule, err) } buildTree, ok := parse.(treeBuilder) diff --git a/pkg/safe/routine.go b/pkg/safe/routine.go index 6a3405aef..06fae8f55 100644 --- a/pkg/safe/routine.go +++ b/pkg/safe/routine.go @@ -12,14 +12,14 @@ import ( type routineCtx func(ctx context.Context) -// Pool is a pool of go routines +// Pool is a pool of go routines. type Pool struct { waitGroup sync.WaitGroup ctx context.Context cancel context.CancelFunc } -// NewPool creates a Pool +// NewPool creates a Pool. func NewPool(parentCtx context.Context) *Pool { ctx, cancel := context.WithCancel(parentCtx) return &Pool{ @@ -28,7 +28,7 @@ func NewPool(parentCtx context.Context) *Pool { } } -// GoCtx starts a recoverable goroutine with a context +// GoCtx starts a recoverable goroutine with a context. func (p *Pool) GoCtx(goroutine routineCtx) { p.waitGroup.Add(1) Go(func() { @@ -37,18 +37,18 @@ func (p *Pool) GoCtx(goroutine routineCtx) { }) } -// Stop stops all started routines, waiting for their termination +// Stop stops all started routines, waiting for their termination. func (p *Pool) Stop() { p.cancel() p.waitGroup.Wait() } -// Go starts a recoverable goroutine +// Go starts a recoverable goroutine. func Go(goroutine func()) { GoWithRecover(goroutine, defaultRecoverGoroutine) } -// GoWithRecover starts a recoverable goroutine using given customRecover() function +// GoWithRecover starts a recoverable goroutine using given customRecover() function. func GoWithRecover(goroutine func(), customRecover func(err interface{})) { go func() { defer func() { @@ -66,13 +66,13 @@ func defaultRecoverGoroutine(err interface{}) { logger.Errorf("Stack: %s", debug.Stack()) } -// OperationWithRecover wrap a backoff operation in a Recover +// OperationWithRecover wrap a backoff operation in a Recover. func OperationWithRecover(operation backoff.Operation) backoff.Operation { return func() (err error) { defer func() { if res := recover(); res != nil { defaultRecoverGoroutine(res) - err = fmt.Errorf("panic in operation: %s", err) + err = fmt.Errorf("panic in operation: %w", err) } }() return operation() diff --git a/pkg/safe/safe.go b/pkg/safe/safe.go index e171d34e5..8b44beb3f 100644 --- a/pkg/safe/safe.go +++ b/pkg/safe/safe.go @@ -4,25 +4,25 @@ import ( "sync" ) -// Safe contains a thread-safe value +// Safe contains a thread-safe value. type Safe struct { value interface{} lock sync.RWMutex } -// New create a new Safe instance given a value +// New create a new Safe instance given a value. func New(value interface{}) *Safe { return &Safe{value: value, lock: sync.RWMutex{}} } -// Get returns the value +// Get returns the value. func (s *Safe) Get() interface{} { s.lock.RLock() defer s.lock.RUnlock() return s.value } -// Set sets a new value +// Set sets a new value. func (s *Safe) Set(value interface{}) { s.lock.Lock() defer s.lock.Unlock() diff --git a/pkg/server/configurationwatcher.go b/pkg/server/configurationwatcher.go index 3434e727a..eb3f56f67 100644 --- a/pkg/server/configurationwatcher.go +++ b/pkg/server/configurationwatcher.go @@ -69,7 +69,7 @@ func (c *ConfigurationWatcher) Stop() { close(c.configurationValidatedChan) } -// AddListener adds a new listener function used when new configuration is provided +// AddListener adds a new listener function used when new configuration is provided. func (c *ConfigurationWatcher) AddListener(listener func(dynamic.Configuration)) { if c.configurationListeners == nil { c.configurationListeners = make([]func(dynamic.Configuration), 0) diff --git a/pkg/server/cookie/cookie.go b/pkg/server/cookie/cookie.go index 5ac3339be..6b95c41b5 100644 --- a/pkg/server/cookie/cookie.go +++ b/pkg/server/cookie/cookie.go @@ -10,7 +10,7 @@ import ( const cookieNameLength = 6 -// GetName of a cookie +// GetName of a cookie. func GetName(cookieName string, backendName string) string { if len(cookieName) != 0 { return sanitizeName(cookieName) @@ -19,7 +19,7 @@ func GetName(cookieName string, backendName string) string { return GenerateName(backendName) } -// GenerateName Generate a hashed name +// GenerateName Generate a hashed name. func GenerateName(backendName string) string { data := []byte("_TRAEFIK_BACKEND_" + backendName) @@ -33,7 +33,7 @@ func GenerateName(backendName string) string { return fmt.Sprintf("_%x", hash.Sum(nil))[:cookieNameLength] } -// sanitizeName According to [RFC 2616](https://www.ietf.org/rfc/rfc2616.txt) section 2.2 +// sanitizeName According to [RFC 2616](https://www.ietf.org/rfc/rfc2616.txt) section 2.2. func sanitizeName(backend string) string { sanitizer := func(r rune) rune { switch r { diff --git a/pkg/server/middleware/middlewares.go b/pkg/server/middleware/middlewares.go index aa4cf6daa..c1398d831 100644 --- a/pkg/server/middleware/middlewares.go +++ b/pkg/server/middleware/middlewares.go @@ -37,7 +37,7 @@ const ( middlewareStackKey middlewareStackType = iota ) -// Builder the middleware builder +// Builder the middleware builder. type Builder struct { configs map[string]*runtime.MiddlewareInfo serviceBuilder serviceBuilder @@ -47,12 +47,12 @@ type serviceBuilder interface { BuildHTTP(ctx context.Context, serviceName string, responseModifier func(*http.Response) error) (http.Handler, error) } -// NewBuilder creates a new Builder +// NewBuilder creates a new Builder. func NewBuilder(configs map[string]*runtime.MiddlewareInfo, serviceBuilder serviceBuilder) *Builder { return &Builder{configs: configs, serviceBuilder: serviceBuilder} } -// BuildChain creates a middleware chain +// BuildChain creates a middleware chain. func (b *Builder) BuildChain(ctx context.Context, middlewares []string) *alice.Chain { chain := alice.New() for _, name := range middlewares { @@ -99,7 +99,7 @@ func checkRecursion(ctx context.Context, middlewareName string) (context.Context return context.WithValue(ctx, middlewareStackKey, append(currentStack, middlewareName)), nil } -// it is the responsibility of the caller to make sure that b.configs[middlewareName].Middleware exists +// it is the responsibility of the caller to make sure that b.configs[middlewareName].Middleware exists. func (b *Builder) buildConstructor(ctx context.Context, middlewareName string) (alice.Constructor, error) { config := b.configs[middlewareName] if config == nil || config.Middleware == nil { diff --git a/pkg/server/provider/provider.go b/pkg/server/provider/provider.go index a6f3c83e4..e98063ce3 100644 --- a/pkg/server/provider/provider.go +++ b/pkg/server/provider/provider.go @@ -13,7 +13,7 @@ const ( key contextKey = iota ) -// AddInContext Adds the provider name in the context +// AddInContext Adds the provider name in the context. func AddInContext(ctx context.Context, elementName string) context.Context { parts := strings.Split(elementName, "@") if len(parts) == 1 { @@ -39,7 +39,7 @@ func GetQualifiedName(ctx context.Context, elementName string) string { return elementName } -// MakeQualifiedName Creates a qualified name for an element +// MakeQualifiedName Creates a qualified name for an element. func MakeQualifiedName(providerName string, elementName string) string { return elementName + "@" + providerName } diff --git a/pkg/server/router/router.go b/pkg/server/router/router.go index f6cf6158a..3392e94ff 100644 --- a/pkg/server/router/router.go +++ b/pkg/server/router/router.go @@ -33,7 +33,7 @@ type serviceManager interface { LaunchHealthCheck() } -// Manager A route/router manager +// Manager A route/router manager. type Manager struct { routerHandlers map[string]http.Handler serviceManager serviceManager @@ -43,7 +43,7 @@ type Manager struct { conf *runtime.Configuration } -// NewManager Creates a new Manager +// NewManager Creates a new Manager. func NewManager(conf *runtime.Configuration, serviceManager serviceManager, middlewaresBuilder middlewareBuilder, @@ -68,7 +68,7 @@ func (m *Manager) getHTTPRouters(ctx context.Context, entryPoints []string, tls return make(map[string]map[string]*runtime.RouterInfo) } -// BuildHandlers Builds handler for all entry points +// BuildHandlers Builds handler for all entry points. func (m *Manager) BuildHandlers(rootCtx context.Context, entryPoints []string, tls bool) map[string]http.Handler { entryPointHandlers := make(map[string]http.Handler) diff --git a/pkg/server/router/tcp/router.go b/pkg/server/router/tcp/router.go index ed56193f5..11a44aa88 100644 --- a/pkg/server/router/tcp/router.go +++ b/pkg/server/router/tcp/router.go @@ -21,7 +21,7 @@ const ( defaultTLSStoreName = "default" ) -// NewManager Creates a new Manager +// NewManager Creates a new Manager. func NewManager(conf *runtime.Configuration, serviceManager *tcpservice.Manager, httpHandlers map[string]http.Handler, @@ -37,7 +37,7 @@ func NewManager(conf *runtime.Configuration, } } -// Manager is a route/router manager +// Manager is a route/router manager. type Manager struct { serviceManager *tcpservice.Manager httpHandlers map[string]http.Handler @@ -62,7 +62,7 @@ func (m *Manager) getHTTPRouters(ctx context.Context, entryPoints []string, tls return make(map[string]map[string]*runtime.RouterInfo) } -// BuildHandlers builds the handlers for the given entrypoints +// BuildHandlers builds the handlers for the given entrypoints. func (m *Manager) BuildHandlers(rootCtx context.Context, entryPoints []string) map[string]*tcp.Router { entryPointsRouters := m.getTCPRouters(rootCtx, entryPoints) entryPointsRoutersHTTP := m.getHTTPRouters(rootCtx, entryPoints, true) @@ -117,7 +117,7 @@ func (m *Manager) buildEntryPointHandler(ctx context.Context, configs map[string domains, err := rules.ParseDomains(routerHTTPConfig.Rule) if err != nil { - routerErr := fmt.Errorf("invalid rule %s, error: %v", routerHTTPConfig.Rule, err) + routerErr := fmt.Errorf("invalid rule %s, error: %w", routerHTTPConfig.Rule, err) routerHTTPConfig.AddError(routerErr, true) logger.Debug(routerErr) continue diff --git a/pkg/server/router/udp/router.go b/pkg/server/router/udp/router.go index cffeb513b..ea67f2564 100644 --- a/pkg/server/router/udp/router.go +++ b/pkg/server/router/udp/router.go @@ -12,7 +12,7 @@ import ( "github.com/containous/traefik/v2/pkg/udp" ) -// NewManager Creates a new Manager +// NewManager Creates a new Manager. func NewManager(conf *runtime.Configuration, serviceManager *udpservice.Manager, ) *Manager { @@ -22,7 +22,7 @@ func NewManager(conf *runtime.Configuration, } } -// Manager is a route/router manager +// Manager is a route/router manager. type Manager struct { serviceManager *udpservice.Manager conf *runtime.Configuration @@ -36,7 +36,7 @@ func (m *Manager) getUDPRouters(ctx context.Context, entryPoints []string) map[s return make(map[string]map[string]*runtime.UDPRouterInfo) } -// BuildHandlers builds the handlers for the given entrypoints +// BuildHandlers builds the handlers for the given entrypoints. func (m *Manager) BuildHandlers(rootCtx context.Context, entryPoints []string) map[string]udp.Handler { entryPointsRouters := m.getUDPRouters(rootCtx, entryPoints) diff --git a/pkg/server/routerfactory.go b/pkg/server/routerfactory.go index 6da1e7b68..1a2dfdc1c 100644 --- a/pkg/server/routerfactory.go +++ b/pkg/server/routerfactory.go @@ -31,7 +31,7 @@ type RouterFactory struct { tlsManager *tls.Manager } -// NewRouterFactory creates a new RouterFactory +// NewRouterFactory creates a new RouterFactory. func NewRouterFactory(staticConfiguration static.Configuration, managerFactory *service.ManagerFactory, tlsManager *tls.Manager, chainBuilder *middleware.ChainBuilder) *RouterFactory { var entryPointsTCP, entryPointsUDP []string for name, cfg := range staticConfiguration.EntryPoints { @@ -57,7 +57,7 @@ func NewRouterFactory(staticConfiguration static.Configuration, managerFactory * } } -// CreateRouters creates new TCPRouters and UDPRouters +// CreateRouters creates new TCPRouters and UDPRouters. func (f *RouterFactory) CreateRouters(conf dynamic.Configuration) (map[string]*tcpCore.Router, map[string]udpCore.Handler) { ctx := context.Background() diff --git a/pkg/server/server.go b/pkg/server/server.go index 2378f79ca..1617d08ca 100644 --- a/pkg/server/server.go +++ b/pkg/server/server.go @@ -13,7 +13,7 @@ import ( "github.com/containous/traefik/v2/pkg/server/middleware" ) -// Server is the reverse-proxy/load-balancer engine +// Server is the reverse-proxy/load-balancer engine. type Server struct { watcher *ConfigurationWatcher tcpEntryPoints TCPEntryPoints @@ -47,7 +47,7 @@ func NewServer(routinesPool *safe.Pool, entryPoints TCPEntryPoints, entryPointsU return srv } -// Start starts the server and Stop/Close it when context is Done +// Start starts the server and Stop/Close it when context is Done. func (s *Server) Start(ctx context.Context) { go func() { <-ctx.Done() @@ -69,7 +69,7 @@ func (s *Server) Wait() { <-s.stopChan } -// Stop stops the server +// Stop stops the server. func (s *Server) Stop() { defer log.WithoutContext().Info("Server stopped") @@ -79,7 +79,7 @@ func (s *Server) Stop() { s.stopChan <- true } -// Close destroys the server +// Close destroys the server. func (s *Server) Close() { ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) diff --git a/pkg/server/server_entrypoint_tcp.go b/pkg/server/server_entrypoint_tcp.go index 6100396f9..a498d6d6d 100644 --- a/pkg/server/server_entrypoint_tcp.go +++ b/pkg/server/server_entrypoint_tcp.go @@ -37,18 +37,18 @@ func newHTTPForwarder(ln net.Listener) *httpForwarder { } } -// ServeTCP uses the connection to serve it later in "Accept" +// ServeTCP uses the connection to serve it later in "Accept". func (h *httpForwarder) ServeTCP(conn tcp.WriteCloser) { h.connChan <- conn } -// Accept retrieves a served connection in ServeTCP +// Accept retrieves a served connection in ServeTCP. func (h *httpForwarder) Accept() (net.Conn, error) { conn := <-h.connChan return conn, nil } -// TCPEntryPoints holds a map of TCPEntryPoint (the entrypoint names being the keys) +// TCPEntryPoints holds a map of TCPEntryPoint (the entrypoint names being the keys). type TCPEntryPoints map[string]*TCPEntryPoint // NewTCPEntryPoints creates a new TCPEntryPoints. @@ -57,7 +57,7 @@ func NewTCPEntryPoints(entryPointsConfig static.EntryPoints) (TCPEntryPoints, er for entryPointName, config := range entryPointsConfig { protocol, err := config.GetProtocol() if err != nil { - return nil, fmt.Errorf("error while building entryPoint %s: %v", entryPointName, err) + return nil, fmt.Errorf("error while building entryPoint %s: %w", entryPointName, err) } if protocol != "tcp" { @@ -68,7 +68,7 @@ func NewTCPEntryPoints(entryPointsConfig static.EntryPoints) (TCPEntryPoints, er serverEntryPointsTCP[entryPointName], err = NewTCPEntryPoint(ctx, config) if err != nil { - return nil, fmt.Errorf("error while building entryPoint %s: %v", entryPointName, err) + return nil, fmt.Errorf("error while building entryPoint %s: %w", entryPointName, err) } } return serverEntryPointsTCP, nil @@ -109,7 +109,7 @@ func (eps TCPEntryPoints) Switch(routersTCP map[string]*tcp.Router) { } } -// TCPEntryPoint is the TCP server +// TCPEntryPoint is the TCP server. type TCPEntryPoint struct { listener net.Listener switcher *tcp.HandlerSwitcher @@ -119,27 +119,27 @@ type TCPEntryPoint struct { httpsServer *httpServer } -// NewTCPEntryPoint creates a new TCPEntryPoint +// NewTCPEntryPoint creates a new TCPEntryPoint. func NewTCPEntryPoint(ctx context.Context, configuration *static.EntryPoint) (*TCPEntryPoint, error) { tracker := newConnectionTracker() listener, err := buildListener(ctx, configuration) if err != nil { - return nil, fmt.Errorf("error preparing server: %v", err) + return nil, fmt.Errorf("error preparing server: %w", err) } router := &tcp.Router{} httpServer, err := createHTTPServer(ctx, listener, configuration, true) if err != nil { - return nil, fmt.Errorf("error preparing httpServer: %v", err) + return nil, fmt.Errorf("error preparing httpServer: %w", err) } router.HTTPForwarder(httpServer.Forwarder) httpsServer, err := createHTTPServer(ctx, listener, configuration, false) if err != nil { - return nil, fmt.Errorf("error preparing httpsServer: %v", err) + return nil, fmt.Errorf("error preparing httpsServer: %w", err) } router.HTTPSForwarder(httpsServer.Forwarder) @@ -201,7 +201,7 @@ func (e *TCPEntryPoint) Start(ctx context.Context) { } } -// Shutdown stops the TCP connections +// Shutdown stops the TCP connections. func (e *TCPEntryPoint) Shutdown(ctx context.Context) { logger := log.FromContext(ctx) @@ -381,7 +381,7 @@ func buildListener(ctx context.Context, entryPoint *static.EntryPoint) (net.List listener, err := net.Listen("tcp", entryPoint.GetAddress()) if err != nil { - return nil, fmt.Errorf("error opening listener: %v", err) + return nil, fmt.Errorf("error opening listener: %w", err) } listener = tcpKeepAliveListener{listener.(*net.TCPListener)} @@ -389,7 +389,7 @@ func buildListener(ctx context.Context, entryPoint *static.EntryPoint) (net.List if entryPoint.ProxyProtocol != nil { listener, err = buildProxyProtocolListener(ctx, entryPoint, listener) if err != nil { - return nil, fmt.Errorf("error creating proxy protocol listener: %v", err) + return nil, fmt.Errorf("error creating proxy protocol listener: %w", err) } } return listener, nil @@ -406,14 +406,14 @@ type connectionTracker struct { lock sync.RWMutex } -// AddConnection add a connection in the tracked connections list +// AddConnection add a connection in the tracked connections list. func (c *connectionTracker) AddConnection(conn net.Conn) { c.lock.Lock() defer c.lock.Unlock() c.conns[conn] = struct{}{} } -// RemoveConnection remove a connection from the tracked connections list +// RemoveConnection remove a connection from the tracked connections list. func (c *connectionTracker) RemoveConnection(conn net.Conn) { c.lock.Lock() defer c.lock.Unlock() @@ -426,7 +426,7 @@ func (c *connectionTracker) isEmpty() bool { return len(c.conns) == 0 } -// Shutdown wait for the connection closing +// Shutdown wait for the connection closing. func (c *connectionTracker) Shutdown(ctx context.Context) error { ticker := time.NewTicker(500 * time.Millisecond) defer ticker.Stop() @@ -442,7 +442,7 @@ func (c *connectionTracker) Shutdown(ctx context.Context) error { } } -// Close close all the connections in the tracked connections list +// Close close all the connections in the tracked connections list. func (c *connectionTracker) Close() { c.lock.Lock() defer c.lock.Unlock() diff --git a/pkg/server/server_entrypoint_udp.go b/pkg/server/server_entrypoint_udp.go index 7181cc3aa..c13e3fe0d 100644 --- a/pkg/server/server_entrypoint_udp.go +++ b/pkg/server/server_entrypoint_udp.go @@ -21,7 +21,7 @@ func NewUDPEntryPoints(cfg static.EntryPoints) (UDPEntryPoints, error) { for entryPointName, entryPoint := range cfg { protocol, err := entryPoint.GetProtocol() if err != nil { - return nil, fmt.Errorf("error while building entryPoint %s: %v", entryPointName, err) + return nil, fmt.Errorf("error while building entryPoint %s: %w", entryPointName, err) } if protocol != "udp" { @@ -30,7 +30,7 @@ func NewUDPEntryPoints(cfg static.EntryPoints) (UDPEntryPoints, error) { ep, err := NewUDPEntryPoint(entryPoint) if err != nil { - return nil, fmt.Errorf("error while building entryPoint %s: %v", entryPointName, err) + return nil, fmt.Errorf("error while building entryPoint %s: %w", entryPointName, err) } entryPoints[entryPointName] = ep } diff --git a/pkg/server/service/proxy.go b/pkg/server/service/proxy.go index 3c7da58ac..21a67329f 100644 --- a/pkg/server/service/proxy.go +++ b/pkg/server/service/proxy.go @@ -15,10 +15,10 @@ import ( "github.com/containous/traefik/v2/pkg/types" ) -// StatusClientClosedRequest non-standard HTTP status code for client disconnection +// StatusClientClosedRequest non-standard HTTP status code for client disconnection. const StatusClientClosedRequest = 499 -// StatusClientClosedRequestText non-standard HTTP status for client disconnection +// StatusClientClosedRequestText non-standard HTTP status for client disconnection. const StatusClientClosedRequestText = "Client Closed Request" func buildProxy(passHostHeader *bool, responseForwarding *dynamic.ResponseForwarding, defaultRoundTripper http.RoundTripper, bufferPool httputil.BufferPool, responseModifier func(*http.Response) error) (http.Handler, error) { @@ -26,7 +26,7 @@ func buildProxy(passHostHeader *bool, responseForwarding *dynamic.ResponseForwar if responseForwarding != nil { err := flushInterval.Set(responseForwarding.FlushInterval) if err != nil { - return nil, fmt.Errorf("error creating flush interval: %v", err) + return nil, fmt.Errorf("error creating flush interval: %w", err) } } if flushInterval == 0 { diff --git a/pkg/server/service/service.go b/pkg/server/service/service.go index c2288d161..2c641cb0e 100644 --- a/pkg/server/service/service.go +++ b/pkg/server/service/service.go @@ -35,7 +35,7 @@ const ( const defaultMaxBodySize int64 = -1 -// NewManager creates a new Manager +// NewManager creates a new Manager. func NewManager(configs map[string]*runtime.ServiceInfo, defaultRoundTripper http.RoundTripper, metricsRegistry metrics.Registry, routinePool *safe.Pool) *Manager { return &Manager{ routinePool: routinePool, @@ -47,7 +47,7 @@ func NewManager(configs map[string]*runtime.ServiceInfo, defaultRoundTripper htt } } -// Manager The service manager +// Manager The service manager. type Manager struct { routinePool *safe.Pool metricsRegistry metrics.Registry @@ -314,7 +314,7 @@ func (m *Manager) getLoadBalancer(ctx context.Context, serviceName string, servi lbsu := healthcheck.NewLBStatusUpdater(lb, m.configs[serviceName]) if err := m.upsertServers(ctx, lbsu, service.Servers); err != nil { - return nil, fmt.Errorf("error configuring load balancer for service %s: %v", serviceName, err) + return nil, fmt.Errorf("error configuring load balancer for service %s: %w", serviceName, err) } return lbsu, nil @@ -326,13 +326,13 @@ func (m *Manager) upsertServers(ctx context.Context, lb healthcheck.BalancerHand for name, srv := range servers { u, err := url.Parse(srv.URL) if err != nil { - return fmt.Errorf("error parsing server URL %s: %v", srv.URL, err) + return fmt.Errorf("error parsing server URL %s: %w", srv.URL, err) } logger.WithField(log.ServerName, name).Debugf("Creating server %d %s", name, u) if err := lb.UpsertServer(u, roundrobin.Weight(1)); err != nil { - return fmt.Errorf("error adding server %s to load balancer: %v", srv.URL, err) + return fmt.Errorf("error adding server %s to load balancer: %w", srv.URL, err) } // FIXME Handle Metrics diff --git a/pkg/server/service/tcp/service.go b/pkg/server/service/tcp/service.go index 7bb4e8d10..2bb8bb1c3 100644 --- a/pkg/server/service/tcp/service.go +++ b/pkg/server/service/tcp/service.go @@ -13,12 +13,12 @@ import ( "github.com/containous/traefik/v2/pkg/tcp" ) -// Manager is the TCPHandlers factory +// Manager is the TCPHandlers factory. type Manager struct { configs map[string]*runtime.TCPServiceInfo } -// NewManager creates a new manager +// NewManager creates a new manager. func NewManager(conf *runtime.Configuration) *Manager { return &Manager{ configs: conf.TCPServices, diff --git a/pkg/server/service/udp/service.go b/pkg/server/service/udp/service.go index 9ed896552..371833f73 100644 --- a/pkg/server/service/udp/service.go +++ b/pkg/server/service/udp/service.go @@ -17,7 +17,7 @@ type Manager struct { configs map[string]*runtime.UDPServiceInfo } -// NewManager creates a new manager +// NewManager creates a new manager. func NewManager(conf *runtime.Configuration) *Manager { return &Manager{ configs: conf.UDPServices, diff --git a/pkg/tcp/handler.go b/pkg/tcp/handler.go index 88aefe8de..ef8b921e7 100644 --- a/pkg/tcp/handler.go +++ b/pkg/tcp/handler.go @@ -4,7 +4,7 @@ import ( "net" ) -// Handler is the TCP Handlers interface +// Handler is the TCP Handlers interface. type Handler interface { ServeTCP(conn WriteCloser) } @@ -13,7 +13,7 @@ type Handler interface { // ordinary functions as handlers. type HandlerFunc func(conn WriteCloser) -// ServeTCP serves tcp +// ServeTCP serves tcp. func (f HandlerFunc) ServeTCP(conn WriteCloser) { f(conn) } diff --git a/pkg/tcp/proxy.go b/pkg/tcp/proxy.go index 0764fea5c..db81336ff 100644 --- a/pkg/tcp/proxy.go +++ b/pkg/tcp/proxy.go @@ -8,13 +8,13 @@ import ( "github.com/containous/traefik/v2/pkg/log" ) -// Proxy forwards a TCP request to a TCP service +// Proxy forwards a TCP request to a TCP service. type Proxy struct { target *net.TCPAddr terminationDelay time.Duration } -// NewProxy creates a new Proxy +// NewProxy creates a new Proxy. func NewProxy(address string, terminationDelay time.Duration) (*Proxy, error) { tcpAddr, err := net.ResolveTCPAddr("tcp", address) if err != nil { @@ -24,7 +24,7 @@ func NewProxy(address string, terminationDelay time.Duration) (*Proxy, error) { return &Proxy{target: tcpAddr, terminationDelay: terminationDelay}, nil } -// ServeTCP forwards the connection to a service +// ServeTCP forwards the connection to a service. func (p *Proxy) ServeTCP(conn WriteCloser) { log.Debugf("Handling connection from %s", conn.RemoteAddr()) diff --git a/pkg/tcp/router.go b/pkg/tcp/router.go index 7ed7d6c91..c66e987ce 100644 --- a/pkg/tcp/router.go +++ b/pkg/tcp/router.go @@ -13,7 +13,7 @@ import ( "github.com/containous/traefik/v2/pkg/log" ) -// Router is a TCP router +// Router is a TCP router. type Router struct { routingTable map[string]Handler httpForwarder Handler @@ -25,7 +25,7 @@ type Router struct { hostHTTPTLSConfig map[string]*tls.Config // TLS configs keyed by SNI } -// ServeTCP forwards the connection to the right TCP/HTTP handler +// ServeTCP forwards the connection to the right TCP/HTTP handler. func (r *Router) ServeTCP(conn WriteCloser) { // FIXME -- Check if ProxyProtocol changes the first bytes of the request @@ -86,7 +86,7 @@ func (r *Router) ServeTCP(conn WriteCloser) { } } -// AddRoute defines a handler for a given sniHost (* is the only valid option) +// AddRoute defines a handler for a given sniHost (* is the only valid option). func (r *Router) AddRoute(sniHost string, target Handler) { if r.routingTable == nil { r.routingTable = map[string]Handler{} @@ -94,7 +94,7 @@ func (r *Router) AddRoute(sniHost string, target Handler) { r.routingTable[strings.ToLower(sniHost)] = target } -// AddRouteTLS defines a handler for a given sniHost and sets the matching tlsConfig +// AddRouteTLS defines a handler for a given sniHost and sets the matching tlsConfig. func (r *Router) AddRouteTLS(sniHost string, target Handler, config *tls.Config) { r.AddRoute(sniHost, &TLSHandler{ Next: target, @@ -102,7 +102,7 @@ func (r *Router) AddRouteTLS(sniHost string, target Handler, config *tls.Config) }) } -// AddRouteHTTPTLS defines a handler for a given sniHost and sets the matching tlsConfig +// AddRouteHTTPTLS defines a handler for a given sniHost and sets the matching tlsConfig. func (r *Router) AddRouteHTTPTLS(sniHost string, config *tls.Config) { if r.hostHTTPTLSConfig == nil { r.hostHTTPTLSConfig = map[string]*tls.Config{} @@ -110,12 +110,12 @@ func (r *Router) AddRouteHTTPTLS(sniHost string, config *tls.Config) { r.hostHTTPTLSConfig[sniHost] = config } -// AddCatchAllNoTLS defines the fallback tcp handler +// AddCatchAllNoTLS defines the fallback tcp handler. func (r *Router) AddCatchAllNoTLS(handler Handler) { r.catchAllNoTLS = handler } -// GetConn creates a connection proxy with a peeked string +// GetConn creates a connection proxy with a peeked string. func (r *Router) GetConn(conn WriteCloser, peeked string) WriteCloser { // FIXME should it really be on Router ? conn = &Conn{ @@ -125,22 +125,22 @@ func (r *Router) GetConn(conn WriteCloser, peeked string) WriteCloser { return conn } -// GetHTTPHandler gets the attached http handler +// GetHTTPHandler gets the attached http handler. func (r *Router) GetHTTPHandler() http.Handler { return r.httpHandler } -// GetHTTPSHandler gets the attached https handler +// GetHTTPSHandler gets the attached https handler. func (r *Router) GetHTTPSHandler() http.Handler { return r.httpsHandler } -// HTTPForwarder sets the tcp handler that will forward the connections to an http handler +// HTTPForwarder sets the tcp handler that will forward the connections to an http handler. func (r *Router) HTTPForwarder(handler Handler) { r.httpForwarder = handler } -// HTTPSForwarder sets the tcp handler that will forward the TLS connections to an http handler +// HTTPSForwarder sets the tcp handler that will forward the TLS connections to an http handler. func (r *Router) HTTPSForwarder(handler Handler) { for sniHost, tlsConf := range r.hostHTTPTLSConfig { r.AddRouteTLS(sniHost, handler, tlsConf) @@ -152,18 +152,18 @@ func (r *Router) HTTPSForwarder(handler Handler) { } } -// HTTPHandler attaches http handlers on the router +// HTTPHandler attaches http handlers on the router. func (r *Router) HTTPHandler(handler http.Handler) { r.httpHandler = handler } -// HTTPSHandler attaches https handlers on the router +// HTTPSHandler attaches https handlers on the router. func (r *Router) HTTPSHandler(handler http.Handler, config *tls.Config) { r.httpsHandler = handler r.httpsTLSConfig = config } -// Conn is a connection proxy that handles Peeked bytes +// Conn is a connection proxy that handles Peeked bytes. type Conn struct { // Peeked are the bytes that have been read from Conn for the // purposes of route matching, but have not yet been consumed @@ -177,7 +177,7 @@ type Conn struct { WriteCloser } -// Read reads bytes from the connection (using the buffer prior to actually reading) +// Read reads bytes from the connection (using the buffer prior to actually reading). func (c *Conn) Read(p []byte) (n int, err error) { if len(c.Peeked) > 0 { n = copy(p, c.Peeked) @@ -259,8 +259,8 @@ type sniSniffConn struct { net.Conn // nil; crash on any unexpected use } -// Read reads from the underlying reader +// Read reads from the underlying reader. func (c sniSniffConn) Read(p []byte) (int, error) { return c.r.Read(p) } -// Write crashes all the time +// Write crashes all the time. func (sniSniffConn) Write(p []byte) (int, error) { return 0, io.EOF } diff --git a/pkg/tcp/switcher.go b/pkg/tcp/switcher.go index 16c4c0cbf..a6d612267 100644 --- a/pkg/tcp/switcher.go +++ b/pkg/tcp/switcher.go @@ -4,12 +4,12 @@ import ( "github.com/containous/traefik/v2/pkg/safe" ) -// HandlerSwitcher is a TCP handler switcher +// HandlerSwitcher is a TCP handler switcher. type HandlerSwitcher struct { router safe.Safe } -// ServeTCP forwards the TCP connection to the current active handler +// ServeTCP forwards the TCP connection to the current active handler. func (s *HandlerSwitcher) ServeTCP(conn WriteCloser) { handler := s.router.Get() h, ok := handler.(Handler) @@ -20,7 +20,7 @@ func (s *HandlerSwitcher) ServeTCP(conn WriteCloser) { } } -// Switch sets the new TCP handler to use for new connections +// Switch sets the new TCP handler to use for new connections. func (s *HandlerSwitcher) Switch(handler Handler) { s.router.Set(handler) } diff --git a/pkg/tcp/tls.go b/pkg/tcp/tls.go index 6debaad3d..207aebb15 100644 --- a/pkg/tcp/tls.go +++ b/pkg/tcp/tls.go @@ -4,13 +4,13 @@ import ( "crypto/tls" ) -// TLSHandler handles TLS connections +// TLSHandler handles TLS connections. type TLSHandler struct { Next Handler Config *tls.Config } -// ServeTCP terminates the TLS connection +// ServeTCP terminates the TLS connection. func (t *TLSHandler) ServeTCP(conn WriteCloser) { t.Next.ServeTCP(tls.Server(conn, t.Config)) } diff --git a/pkg/tcp/wrr_load_balancer.go b/pkg/tcp/wrr_load_balancer.go index bfa69d924..466bf36e1 100644 --- a/pkg/tcp/wrr_load_balancer.go +++ b/pkg/tcp/wrr_load_balancer.go @@ -12,7 +12,7 @@ type server struct { weight int } -// WRRLoadBalancer is a naive RoundRobin load balancer for TCP services +// WRRLoadBalancer is a naive RoundRobin load balancer for TCP services. type WRRLoadBalancer struct { servers []server lock sync.RWMutex @@ -20,14 +20,14 @@ type WRRLoadBalancer struct { index int } -// NewWRRLoadBalancer creates a new WRRLoadBalancer +// NewWRRLoadBalancer creates a new WRRLoadBalancer. func NewWRRLoadBalancer() *WRRLoadBalancer { return &WRRLoadBalancer{ index: -1, } } -// ServeTCP forwards the connection to the right service +// ServeTCP forwards the connection to the right service. func (b *WRRLoadBalancer) ServeTCP(conn WriteCloser) { if len(b.servers) == 0 { log.WithoutContext().Error("no available server") @@ -42,13 +42,13 @@ func (b *WRRLoadBalancer) ServeTCP(conn WriteCloser) { next.ServeTCP(conn) } -// AddServer appends a server to the existing list +// AddServer appends a server to the existing list. func (b *WRRLoadBalancer) AddServer(serverHandler Handler) { w := 1 b.AddWeightServer(serverHandler, &w) } -// AddWeightServer appends a server to the existing list with a weight +// AddWeightServer appends a server to the existing list with a weight. func (b *WRRLoadBalancer) AddWeightServer(serverHandler Handler, weight *int) { w := 1 if weight != nil { diff --git a/pkg/testhelpers/helpers.go b/pkg/testhelpers/helpers.go index d0535d17f..c3ab03527 100644 --- a/pkg/testhelpers/helpers.go +++ b/pkg/testhelpers/helpers.go @@ -7,7 +7,7 @@ import ( "net/url" ) -// MustNewRequest creates a new http get request or panics if it can't +// MustNewRequest creates a new http get request or panics if it can't. func MustNewRequest(method, urlStr string, body io.Reader) *http.Request { request, err := http.NewRequest(method, urlStr, body) if err != nil { @@ -16,7 +16,7 @@ func MustNewRequest(method, urlStr string, body io.Reader) *http.Request { return request } -// MustParseURL parses a URL or panics if it can't +// MustParseURL parses a URL or panics if it can't. func MustParseURL(rawURL string) *url.URL { u, err := url.Parse(rawURL) if err != nil { diff --git a/pkg/tls/certificate.go b/pkg/tls/certificate.go index 041c98b3e..de970cac9 100644 --- a/pkg/tls/certificate.go +++ b/pkg/tls/certificate.go @@ -14,7 +14,7 @@ import ( ) var ( - // MinVersion Map of allowed TLS minimum versions + // MinVersion Map of allowed TLS minimum versions. MinVersion = map[string]uint16{ `VersionTLS10`: tls.VersionTLS10, `VersionTLS11`: tls.VersionTLS11, @@ -22,7 +22,7 @@ var ( `VersionTLS13`: tls.VersionTLS13, } - // MaxVersion Map of allowed TLS maximum versions + // MaxVersion Map of allowed TLS maximum versions. MaxVersion = map[string]uint16{ `VersionTLS10`: tls.VersionTLS10, `VersionTLS11`: tls.VersionTLS11, @@ -46,24 +46,24 @@ var ( ) // Certificate holds a SSL cert/key pair -// Certs and Key could be either a file path, or the file content itself +// Certs and Key could be either a file path, or the file content itself. type Certificate struct { CertFile FileOrContent `json:"certFile,omitempty" toml:"certFile,omitempty" yaml:"certFile,omitempty"` KeyFile FileOrContent `json:"keyFile,omitempty" toml:"keyFile,omitempty" yaml:"keyFile,omitempty"` } // Certificates defines traefik certificates type -// Certs and Keys could be either a file path, or the file content itself +// Certs and Keys could be either a file path, or the file content itself. type Certificates []Certificate -// FileOrContent hold a file path or content +// FileOrContent hold a file path or content. type FileOrContent string func (f FileOrContent) String() string { return string(f) } -// IsPath returns true if the FileOrContent is a file path, otherwise returns false +// IsPath returns true if the FileOrContent is a file path, otherwise returns false. func (f FileOrContent) IsPath() bool { _, err := os.Stat(f.String()) return err == nil @@ -83,7 +83,7 @@ func (f FileOrContent) Read() ([]byte, error) { return content, nil } -// CreateTLSConfig creates a TLS config from Certificate structures +// CreateTLSConfig creates a TLS config from Certificate structures. func (c *Certificates) CreateTLSConfig(entryPointName string) (*tls.Config, error) { config := &tls.Config{} domainsCertificates := make(map[string]map[string]*tls.Certificate) @@ -115,7 +115,7 @@ func (c *Certificates) CreateTLSConfig(entryPointName string) (*tls.Config, erro return config, nil } -// isEmpty checks if the certificates list is empty +// isEmpty checks if the certificates list is empty. func (c *Certificates) isEmpty() bool { if len(*c) == 0 { return true @@ -134,16 +134,16 @@ func (c *Certificates) isEmpty() bool { func (c *Certificate) AppendCertificate(certs map[string]map[string]*tls.Certificate, ep string) error { certContent, err := c.CertFile.Read() if err != nil { - return fmt.Errorf("unable to read CertFile : %v", err) + return fmt.Errorf("unable to read CertFile : %w", err) } keyContent, err := c.KeyFile.Read() if err != nil { - return fmt.Errorf("unable to read KeyFile : %v", err) + return fmt.Errorf("unable to read KeyFile : %w", err) } tlsCert, err := tls.X509KeyPair(certContent, keyContent) if err != nil { - return fmt.Errorf("unable to generate TLS certificate : %v", err) + return fmt.Errorf("unable to generate TLS certificate : %w", err) } parsedCert, _ := x509.ParseCertificate(tlsCert.Certificate[0]) @@ -190,7 +190,7 @@ func (c *Certificate) AppendCertificate(certs map[string]map[string]*tls.Certifi return err } -// GetTruncatedCertificateName truncates the certificate name +// GetTruncatedCertificateName truncates the certificate name. func (c *Certificate) GetTruncatedCertificateName() string { certName := c.CertFile.String() @@ -233,7 +233,7 @@ func (c *Certificates) Set(value string) error { return nil } -// Type is type of the struct +// Type is type of the struct. func (c *Certificates) Type() string { return "certificates" } diff --git a/pkg/tls/certificate_store.go b/pkg/tls/certificate_store.go index 4c4ac2fc2..7f6116257 100644 --- a/pkg/tls/certificate_store.go +++ b/pkg/tls/certificate_store.go @@ -13,14 +13,14 @@ import ( "github.com/patrickmn/go-cache" ) -// CertificateStore store for dynamic and static certificates +// CertificateStore store for dynamic and static certificates. type CertificateStore struct { DynamicCerts *safe.Safe DefaultCertificate *tls.Certificate CertCache *cache.Cache } -// NewCertificateStore create a store for dynamic and static certificates +// NewCertificateStore create a store for dynamic and static certificates. func NewCertificateStore() *CertificateStore { return &CertificateStore{ DynamicCerts: &safe.Safe{}, @@ -54,7 +54,7 @@ func (c CertificateStore) getDefaultCertificateDomains() []string { return allCerts } -// GetAllDomains return a slice with all the certificate domain +// GetAllDomains return a slice with all the certificate domain. func (c CertificateStore) GetAllDomains() []string { allCerts := c.getDefaultCertificateDomains() @@ -67,7 +67,7 @@ func (c CertificateStore) GetAllDomains() []string { return allCerts } -// GetBestCertificate returns the best match certificate, and caches the response +// GetBestCertificate returns the best match certificate, and caches the response. func (c CertificateStore) GetBestCertificate(clientHello *tls.ClientHelloInfo) *tls.Certificate { domainToCheck := strings.ToLower(strings.TrimSpace(clientHello.ServerName)) if len(domainToCheck) == 0 { @@ -110,14 +110,14 @@ func (c CertificateStore) GetBestCertificate(clientHello *tls.ClientHelloInfo) * return nil } -// ResetCache clears the cache in the store +// ResetCache clears the cache in the store. func (c CertificateStore) ResetCache() { if c.CertCache != nil { c.CertCache.Flush() } } -// MatchDomain return true if a domain match the cert domain +// MatchDomain return true if a domain match the cert domain. func MatchDomain(domain string, certDomain string) bool { if domain == certDomain { return true diff --git a/pkg/tls/generate/generate.go b/pkg/tls/generate/generate.go index 8dbfa00aa..66d624d02 100644 --- a/pkg/tls/generate/generate.go +++ b/pkg/tls/generate/generate.go @@ -14,10 +14,10 @@ import ( "time" ) -// DefaultDomain Traefik domain for the default certificate +// DefaultDomain Traefik domain for the default certificate. const DefaultDomain = "TRAEFIK DEFAULT CERT" -// DefaultCertificate generates random TLS certificates +// DefaultCertificate generates random TLS certificates. func DefaultCertificate() (*tls.Certificate, error) { randomBytes := make([]byte, 100) _, err := rand.Read(randomBytes) @@ -41,7 +41,7 @@ func DefaultCertificate() (*tls.Certificate, error) { return &certificate, nil } -// KeyPair generates cert and key files +// KeyPair generates cert and key files. func KeyPair(domain string, expiration time.Time) ([]byte, []byte, error) { rsaPrivKey, err := rsa.GenerateKey(rand.Reader, 2048) if err != nil { @@ -56,7 +56,7 @@ func KeyPair(domain string, expiration time.Time) ([]byte, []byte, error) { return certPEM, keyPEM, nil } -// PemCert generates PEM cert file +// PemCert generates PEM cert file. func PemCert(privKey *rsa.PrivateKey, domain string, expiration time.Time) ([]byte, error) { derBytes, err := derCert(privKey, expiration, domain) if err != nil { diff --git a/pkg/tls/tls.go b/pkg/tls/tls.go index f4014d6bd..62e114329 100644 --- a/pkg/tls/tls.go +++ b/pkg/tls/tls.go @@ -14,7 +14,7 @@ type ClientAuth struct { // +k8s:deepcopy-gen=true -// Options configures TLS for an entry point +// Options configures TLS for an entry point. type Options struct { MinVersion string `json:"minVersion,omitempty" toml:"minVersion,omitempty" yaml:"minVersion,omitempty" export:"true"` MaxVersion string `json:"maxVersion,omitempty" toml:"maxVersion,omitempty" yaml:"maxVersion,omitempty" export:"true"` @@ -27,7 +27,7 @@ type Options struct { // +k8s:deepcopy-gen=true -// Store holds the options for a given Store +// Store holds the options for a given Store. type Store struct { DefaultCertificate *Certificate `json:"defaultCertificate,omitempty" toml:"defaultCertificate,omitempty" yaml:"defaultCertificate,omitempty"` } diff --git a/pkg/tls/tlsmanager.go b/pkg/tls/tlsmanager.go index d2c30b96a..767b4331e 100644 --- a/pkg/tls/tlsmanager.go +++ b/pkg/tls/tlsmanager.go @@ -18,7 +18,7 @@ import ( // DefaultTLSOptions the default TLS options. var DefaultTLSOptions = Options{} -// Manager is the TLS option/store/configuration factory +// Manager is the TLS option/store/configuration factory. type Manager struct { storesConfig map[string]Store stores map[string]*CertificateStore @@ -28,7 +28,7 @@ type Manager struct { lock sync.RWMutex } -// NewManager creates a new Manager +// NewManager creates a new Manager. func NewManager() *Manager { return &Manager{ stores: map[string]*CertificateStore{}, @@ -38,7 +38,7 @@ func NewManager() *Manager { } } -// UpdateConfigs updates the TLS* configuration options +// UpdateConfigs updates the TLS* configuration options. func (m *Manager) UpdateConfigs(ctx context.Context, stores map[string]Store, configs map[string]Options, certs []*CertAndStores) { m.lock.Lock() defer m.lock.Unlock() @@ -80,7 +80,7 @@ func (m *Manager) UpdateConfigs(ctx context.Context, stores map[string]Store, co } } -// Get gets the TLS configuration to use for a given store / configuration +// Get gets the TLS configuration to use for a given store / configuration. func (m *Manager) Get(storeName string, configName string) (*tls.Config, error) { m.lock.RLock() defer m.lock.RUnlock() @@ -141,7 +141,7 @@ func (m *Manager) getStore(storeName string) *CertificateStore { return m.stores[storeName] } -// GetStore gets the certificate store of a given name +// GetStore gets the certificate store of a given name. func (m *Manager) GetStore(storeName string) *CertificateStore { m.lock.RLock() defer m.lock.RUnlock() @@ -170,7 +170,7 @@ func buildCertificateStore(ctx context.Context, tlsStore Store) (*CertificateSto return certificateStore, nil } -// creates a TLS config that allows terminating HTTPS for multiple domains using SNI +// creates a TLS config that allows terminating HTTPS for multiple domains using SNI. func buildTLSConfig(tlsOption Options) (*tls.Config, error) { conf := &tls.Config{} @@ -268,17 +268,17 @@ func buildTLSConfig(tlsOption Options) (*tls.Config, error) { func buildDefaultCertificate(defaultCertificate *Certificate) (*tls.Certificate, error) { certFile, err := defaultCertificate.CertFile.Read() if err != nil { - return nil, fmt.Errorf("failed to get cert file content: %v", err) + return nil, fmt.Errorf("failed to get cert file content: %w", err) } keyFile, err := defaultCertificate.KeyFile.Read() if err != nil { - return nil, fmt.Errorf("failed to get key file content: %v", err) + return nil, fmt.Errorf("failed to get key file content: %w", err) } cert, err := tls.X509KeyPair(certFile, keyFile) if err != nil { - return nil, fmt.Errorf("failed to load X509 key pair: %v", err) + return nil, fmt.Errorf("failed to load X509 key pair: %w", err) } return &cert, nil } diff --git a/pkg/tracing/datadog/datadog.go b/pkg/tracing/datadog/datadog.go index 71589a92a..c7236bda2 100644 --- a/pkg/tracing/datadog/datadog.go +++ b/pkg/tracing/datadog/datadog.go @@ -10,10 +10,10 @@ import ( datadog "gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer" ) -// Name sets the name of this tracer +// Name sets the name of this tracer. const Name = "datadog" -// Config provides configuration settings for a datadog tracer +// Config provides configuration settings for a datadog tracer. type Config struct { LocalAgentHostPort string `description:"Set datadog-agent's host:port that the reporter will used." json:"localAgentHostPort,omitempty" toml:"localAgentHostPort,omitempty" yaml:"localAgentHostPort,omitempty"` GlobalTag string `description:"Key:Value tag to be set on all the spans." json:"globalTag,omitempty" toml:"globalTag,omitempty" yaml:"globalTag,omitempty" export:"true"` @@ -33,7 +33,7 @@ func (c *Config) SetDefaults() { c.PrioritySampling = false } -// Setup sets up the tracer +// Setup sets up the tracer. func (c *Config) Setup(serviceName string) (opentracing.Tracer, io.Closer, error) { tag := strings.SplitN(c.GlobalTag, ":", 2) diff --git a/pkg/tracing/haystack/haystack.go b/pkg/tracing/haystack/haystack.go index 644a27c87..4851fa9f2 100644 --- a/pkg/tracing/haystack/haystack.go +++ b/pkg/tracing/haystack/haystack.go @@ -10,10 +10,10 @@ import ( "github.com/opentracing/opentracing-go" ) -// Name sets the name of this tracer +// Name sets the name of this tracer. const Name = "haystack" -// Config provides configuration settings for a haystack tracer +// Config provides configuration settings for a haystack tracer. type Config struct { LocalAgentHost string `description:"Set haystack-agent's host that the reporter will used." json:"localAgentHost,omitempty" toml:"localAgentHost,omitempty" yaml:"localAgentHost,omitempty"` LocalAgentPort int `description:"Set haystack-agent's port that the reporter will used." json:"localAgentPort,omitempty" toml:"localAgentPort,omitempty" yaml:"localAgentPort,omitempty"` @@ -30,7 +30,7 @@ func (c *Config) SetDefaults() { c.LocalAgentPort = 35000 } -// Setup sets up the tracer +// Setup sets up the tracer. func (c *Config) Setup(serviceName string) (opentracing.Tracer, io.Closer, error) { tag := strings.SplitN(c.GlobalTag, ":", 2) diff --git a/pkg/tracing/haystack/logger.go b/pkg/tracing/haystack/logger.go index aa223fcb8..2f69167a1 100644 --- a/pkg/tracing/haystack/logger.go +++ b/pkg/tracing/haystack/logger.go @@ -4,22 +4,21 @@ import ( "github.com/containous/traefik/v2/pkg/log" ) -/*NullLogger does nothing*/ type haystackLogger struct { logger log.Logger } -/*Error prints the error message*/ +// Error prints the error message. func (l haystackLogger) Error(format string, v ...interface{}) { l.logger.Errorf(format, v) } -/*Info prints the info message*/ +// Info prints the info message. func (l haystackLogger) Info(format string, v ...interface{}) { l.logger.Infof(format, v) } -/*Debug prints the info message*/ +// Debug prints the info message. func (l haystackLogger) Debug(format string, v ...interface{}) { l.logger.Debug(format, v) } diff --git a/pkg/tracing/instana/instana.go b/pkg/tracing/instana/instana.go index 8bd86944e..370ea92a8 100644 --- a/pkg/tracing/instana/instana.go +++ b/pkg/tracing/instana/instana.go @@ -8,10 +8,10 @@ import ( "github.com/opentracing/opentracing-go" ) -// Name sets the name of this tracer +// Name sets the name of this tracer. const Name = "instana" -// Config provides configuration settings for a instana tracer +// Config provides configuration settings for a instana tracer. type Config struct { LocalAgentHost string `description:"Set instana-agent's host that the reporter will used." json:"localAgentHost,omitempty" toml:"localAgentHost,omitempty" yaml:"localAgentHost,omitempty"` LocalAgentPort int `description:"Set instana-agent's port that the reporter will used." json:"localAgentPort,omitempty" toml:"localAgentPort,omitempty" yaml:"localAgentPort,omitempty"` @@ -24,7 +24,7 @@ func (c *Config) SetDefaults() { c.LogLevel = "info" } -// Setup sets up the tracer +// Setup sets up the tracer. func (c *Config) Setup(serviceName string) (opentracing.Tracer, io.Closer, error) { // set default logLevel logLevel := instana.Info diff --git a/pkg/tracing/jaeger/jaeger.go b/pkg/tracing/jaeger/jaeger.go index 8adaa4406..d8f73eccc 100644 --- a/pkg/tracing/jaeger/jaeger.go +++ b/pkg/tracing/jaeger/jaeger.go @@ -52,7 +52,7 @@ func (c *Collector) SetDefaults() { c.Password = "" } -// Setup sets up the tracer +// Setup sets up the tracer. func (c *Config) Setup(componentName string) (opentracing.Tracer, io.Closer, error) { reporter := &jaegercfg.ReporterConfig{ LogSpans: true, diff --git a/pkg/tracing/jaeger/logger.go b/pkg/tracing/jaeger/logger.go index 2df321b8c..a8419e7e0 100644 --- a/pkg/tracing/jaeger/logger.go +++ b/pkg/tracing/jaeger/logger.go @@ -5,7 +5,7 @@ import ( "github.com/sirupsen/logrus" ) -// jaegerLogger is an implementation of the Logger interface that delegates to traefik log +// jaegerLogger is an implementation of the Logger interface that delegates to traefik log. type jaegerLogger struct { logger logrus.FieldLogger } @@ -20,7 +20,7 @@ func (l *jaegerLogger) Error(msg string) { l.logger.Errorf("Tracing jaeger error: %s", msg) } -// Infof logs a message at debug priority +// Infof logs a message at debug priority. func (l *jaegerLogger) Infof(msg string, args ...interface{}) { l.logger.Debugf(msg, args...) } diff --git a/pkg/tracing/tracing.go b/pkg/tracing/tracing.go index 9eddc8933..33005124a 100644 --- a/pkg/tracing/tracing.go +++ b/pkg/tracing/tracing.go @@ -94,7 +94,7 @@ func (t *Tracing) IsEnabled() bool { return t != nil && t.tracer != nil } -// Close tracer +// Close tracer. func (t *Tracing) Close() { if t.closer != nil { err := t.closer.Close() @@ -148,7 +148,7 @@ func LogEventf(r *http.Request, format string, args ...interface{}) { } } -// StartSpan starts a new span from the one in the request context +// StartSpan starts a new span from the one in the request context. func StartSpan(r *http.Request, operationName string, spanKind ext.SpanKindEnum, opts ...opentracing.StartSpanOption) (opentracing.Span, *http.Request, func()) { span, ctx := opentracing.StartSpanFromContext(r.Context(), operationName, opts...) diff --git a/pkg/tracing/zipkin/zipkin.go b/pkg/tracing/zipkin/zipkin.go index 7a6548fb3..8daecd383 100644 --- a/pkg/tracing/zipkin/zipkin.go +++ b/pkg/tracing/zipkin/zipkin.go @@ -30,7 +30,7 @@ func (c *Config) SetDefaults() { c.SampleRate = 1.0 } -// Setup sets up the tracer +// Setup sets up the tracer. func (c *Config) Setup(serviceName string) (opentracing.Tracer, io.Closer, error) { // create our local endpoint endpoint, err := zipkin.NewEndpoint(serviceName, "0.0.0.0:0") diff --git a/pkg/types/http_code_range.go b/pkg/types/http_code_range.go index 95defbf49..4a8f541a5 100644 --- a/pkg/types/http_code_range.go +++ b/pkg/types/http_code_range.go @@ -5,12 +5,12 @@ import ( "strings" ) -// HTTPCodeRanges holds HTTP code ranges +// HTTPCodeRanges holds HTTP code ranges. type HTTPCodeRanges [][2]int // NewHTTPCodeRanges creates HTTPCodeRanges from a given []string. // Break out the http status code ranges into a low int and high int -// for ease of use at runtime +// for ease of use at runtime. func NewHTTPCodeRanges(strBlocks []string) (HTTPCodeRanges, error) { var blocks HTTPCodeRanges for _, block := range strBlocks { @@ -32,8 +32,7 @@ func NewHTTPCodeRanges(strBlocks []string) (HTTPCodeRanges, error) { return blocks, nil } -// 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 { for _, block := range h { if statusCode >= block[0] && statusCode <= block[1] { diff --git a/pkg/types/logs.go b/pkg/types/logs.go index f561effc6..7843079f5 100644 --- a/pkg/types/logs.go +++ b/pkg/types/logs.go @@ -1,11 +1,11 @@ package types const ( - // AccessLogKeep is the keep string value + // AccessLogKeep is the keep string value. AccessLogKeep = "keep" - // AccessLogDrop is the drop string value + // AccessLogDrop is the drop string value. AccessLogDrop = "drop" - // AccessLogRedact is the redact string value + // AccessLogRedact is the redact string value. AccessLogRedact = "redact" ) @@ -48,20 +48,20 @@ func (l *AccessLog) SetDefaults() { l.Fields.SetDefaults() } -// AccessLogFilters holds filters configuration +// AccessLogFilters holds filters configuration. type AccessLogFilters struct { StatusCodes []string `description:"Keep access logs with status codes in the specified range." json:"statusCodes,omitempty" toml:"statusCodes,omitempty" yaml:"statusCodes,omitempty" export:"true"` RetryAttempts bool `description:"Keep access logs when at least one retry happened." json:"retryAttempts,omitempty" toml:"retryAttempts,omitempty" yaml:"retryAttempts,omitempty" export:"true"` MinDuration Duration `description:"Keep access logs when request took longer than the specified duration." json:"minDuration,omitempty" toml:"minDuration,omitempty" yaml:"minDuration,omitempty" export:"true"` } -// FieldHeaders holds configuration for access log headers +// FieldHeaders holds configuration for access log headers. type FieldHeaders struct { DefaultMode string `description:"Default mode for fields: keep | drop | redact" json:"defaultMode,omitempty" toml:"defaultMode,omitempty" yaml:"defaultMode,omitempty" export:"true"` Names map[string]string `description:"Override mode for headers" json:"names,omitempty" toml:"names,omitempty" yaml:"names,omitempty" export:"true"` } -// AccessLogFields holds configuration for access log fields +// AccessLogFields holds configuration for access log fields. type AccessLogFields struct { DefaultMode string `description:"Default mode for fields: keep | drop" json:"defaultMode,omitempty" toml:"defaultMode,omitempty" yaml:"defaultMode,omitempty" export:"true"` Names map[string]string `description:"Override mode for fields" json:"names,omitempty" toml:"names,omitempty" yaml:"names,omitempty" export:"true"` @@ -76,7 +76,7 @@ func (f *AccessLogFields) SetDefaults() { } } -// Keep check if the field need to be kept or dropped +// Keep check if the field need to be kept or dropped. func (f *AccessLogFields) Keep(field string) bool { defaultKeep := true if f != nil { @@ -89,7 +89,7 @@ func (f *AccessLogFields) Keep(field string) bool { return defaultKeep } -// KeepHeader checks if the headers need to be kept, dropped or redacted and returns the status +// KeepHeader checks if the headers need to be kept, dropped or redacted and returns the status. func (f *AccessLogFields) KeepHeader(header string) string { defaultValue := AccessLogKeep if f != nil && f.Headers != nil { diff --git a/pkg/types/route_appender.go b/pkg/types/route_appender.go index 3549bef5e..8a524a814 100644 --- a/pkg/types/route_appender.go +++ b/pkg/types/route_appender.go @@ -4,7 +4,7 @@ import ( "github.com/gorilla/mux" ) -// RouteAppender appends routes on a router (/api, /ping ...) +// RouteAppender appends routes on a router (/api, /ping ...). type RouteAppender interface { Append(systemRouter *mux.Router) } diff --git a/pkg/types/tls.go b/pkg/types/tls.go index 21aa0f6e6..07546b828 100644 --- a/pkg/types/tls.go +++ b/pkg/types/tls.go @@ -12,7 +12,7 @@ import ( ) // ClientTLS holds TLS specific configurations as client -// CA, Cert and Key can be either path or file contents +// CA, Cert and Key can be either path or file contents. type ClientTLS struct { CA string `description:"TLS CA" json:"ca,omitempty" toml:"ca,omitempty" yaml:"ca,omitempty"` CAOptional bool `description:"TLS CA.Optional" json:"caOptional,omitempty" toml:"caOptional,omitempty" yaml:"caOptional,omitempty"` @@ -21,7 +21,7 @@ type ClientTLS struct { InsecureSkipVerify bool `description:"TLS insecure skip verify" json:"insecureSkipVerify,omitempty" toml:"insecureSkipVerify,omitempty" yaml:"insecureSkipVerify,omitempty"` } -// CreateTLSConfig creates a TLS config from ClientTLS structures +// CreateTLSConfig creates a TLS config from ClientTLS structures. func (clientTLS *ClientTLS) CreateTLSConfig(ctx context.Context) (*tls.Config, error) { if clientTLS == nil { log.FromContext(ctx).Warnf("clientTLS is nil") @@ -36,7 +36,7 @@ func (clientTLS *ClientTLS) CreateTLSConfig(ctx context.Context) (*tls.Config, e var err error ca, err = ioutil.ReadFile(clientTLS.CA) if err != nil { - return nil, fmt.Errorf("failed to read CA. %s", err) + return nil, fmt.Errorf("failed to read CA. %w", err) } } else { ca = []byte(clientTLS.CA) @@ -66,7 +66,7 @@ func (clientTLS *ClientTLS) CreateTLSConfig(ctx context.Context) (*tls.Config, e if errKeyIsFile == nil { cert, err = tls.LoadX509KeyPair(clientTLS.Cert, clientTLS.Key) if err != nil { - return nil, fmt.Errorf("failed to load TLS keypair: %v", err) + return nil, fmt.Errorf("failed to load TLS keypair: %w", err) } } else { return nil, fmt.Errorf("TLS cert is a file, but tls key is not") @@ -75,7 +75,7 @@ func (clientTLS *ClientTLS) CreateTLSConfig(ctx context.Context) (*tls.Config, e if errKeyIsFile != nil { cert, err = tls.X509KeyPair([]byte(clientTLS.Cert), []byte(clientTLS.Key)) if err != nil { - return nil, fmt.Errorf("failed to load TLS keypair: %v", err) + return nil, fmt.Errorf("failed to load TLS keypair: %w", err) } } else { return nil, fmt.Errorf("TLS key is a file, but tls cert is not") diff --git a/pkg/udp/proxy.go b/pkg/udp/proxy.go index 520244ee1..740ebc94e 100644 --- a/pkg/udp/proxy.go +++ b/pkg/udp/proxy.go @@ -13,7 +13,7 @@ type Proxy struct { target string } -// NewProxy creates a new Proxy +// NewProxy creates a new Proxy. func NewProxy(address string) (*Proxy, error) { return &Proxy{target: address}, nil } diff --git a/pkg/udp/wrr_load_balancer.go b/pkg/udp/wrr_load_balancer.go index f858c39b8..c5e4ee975 100644 --- a/pkg/udp/wrr_load_balancer.go +++ b/pkg/udp/wrr_load_balancer.go @@ -12,7 +12,7 @@ type server struct { weight int } -// WRRLoadBalancer is a naive RoundRobin load balancer for UDP services +// WRRLoadBalancer is a naive RoundRobin load balancer for UDP services. type WRRLoadBalancer struct { servers []server lock sync.RWMutex @@ -20,14 +20,14 @@ type WRRLoadBalancer struct { index int } -// NewWRRLoadBalancer creates a new WRRLoadBalancer +// NewWRRLoadBalancer creates a new WRRLoadBalancer. func NewWRRLoadBalancer() *WRRLoadBalancer { return &WRRLoadBalancer{ index: -1, } } -// ServeUDP forwards the connection to the right service +// ServeUDP forwards the connection to the right service. func (b *WRRLoadBalancer) ServeUDP(conn *Conn) { if len(b.servers) == 0 { log.WithoutContext().Error("no available server") @@ -42,13 +42,13 @@ func (b *WRRLoadBalancer) ServeUDP(conn *Conn) { next.ServeUDP(conn) } -// AddServer appends a handler to the existing list +// AddServer appends a handler to the existing list. func (b *WRRLoadBalancer) AddServer(serverHandler Handler) { w := 1 b.AddWeightedServer(serverHandler, &w) } -// AddWeightedServer appends a handler to the existing list with a weight +// AddWeightedServer appends a handler to the existing list with a weight. func (b *WRRLoadBalancer) AddWeightedServer(serverHandler Handler, weight *int) { w := 1 if weight != nil { diff --git a/pkg/version/version.go b/pkg/version/version.go index 7b5975bf1..2f02c16d2 100644 --- a/pkg/version/version.go +++ b/pkg/version/version.go @@ -21,7 +21,7 @@ var ( BuildDate = "I don't remember exactly" ) -// Handler expose version routes +// Handler expose version routes. type Handler struct{} var ( @@ -48,7 +48,7 @@ func (v Handler) Append(router *mux.Router) { }) } -// CheckNewVersion checks if a new version is available +// CheckNewVersion checks if a new version is available. func CheckNewVersion() { if Version == "dev" { return