From 115ddc6a4a9e3b25e2a5df647730a716a9abe4d1 Mon Sep 17 00:00:00 2001 From: Ludovic Fernandez Date: Tue, 5 Feb 2019 17:10:03 +0100 Subject: [PATCH] refactor: applies linting. --- .golangci.toml | 23 ++++++++++++- cmd/bug/bug.go | 8 ++--- cmd/traefik/traefik.go | 2 +- config/static/entrypoints.go | 4 ++- config/static/static_config.go | 6 ++-- healthcheck/healthcheck.go | 18 +++++------ middlewares/accesslog/logger.go | 2 +- middlewares/auth/forward.go | 32 ++++++++++++------- middlewares/headers/headers_test.go | 2 +- .../passtlsclientcert/pass_tls_client_cert.go | 3 +- middlewares/retry/retry_test.go | 9 ++++-- provider/acme/local_store.go | 4 +-- provider/acme/provider.go | 11 ++++--- provider/base_provider.go | 22 ------------- provider/docker/config.go | 18 ++++------- provider/file/file.go | 7 ++-- provider/rest/rest.go | 16 +++++----- server/server_signals.go | 3 +- server/service/service.go | 25 +++++---------- types/constraints.go | 7 ++-- 20 files changed, 111 insertions(+), 111 deletions(-) diff --git a/.golangci.toml b/.golangci.toml index 990b5fe6c..88a504792 100644 --- a/.golangci.toml +++ b/.golangci.toml @@ -3,6 +3,21 @@ skip-files = [ "^old/.*", + "^acme/.*", + "^cluster/.*", + "^cmd/convert/.*", + "^h2c/.*", + "^integration/.*", + +# "^cmd/traefik/.*", +# "^anonymize/.*", +# "^provider/.*", +# "^tracing/.*", +# "^safe/.*", +# "^h2c/.*", +# "^healthcheck/.*", +# "^middlewares/.*", +# "^server/.*", ] [linters-settings] @@ -21,7 +36,7 @@ [linters-settings.goconst] min-len = 3.0 - min-occurrences = 3.0 + min-occurrences = 4.0 [linters-settings.misspell] locale = "US" @@ -34,12 +49,18 @@ "gas", "dupl", "prealloc", + "gochecknoinits", + "gochecknoglobals", + "unparam", + "scopelint", + "goimports", ] [issues] max-per-linter = 0 max-same = 0 exclude = [ + "field `(foo|fuu)` is unused", "(.+) is deprecated:", "cyclomatic complexity (\\d+) of func `\\(\\*Builder\\)\\.buildConstructor` is high", #alt/server/middleware/middlewares.go "`logger` can be `github.com/containous/traefik/vendor/github.com/stretchr/testify/assert.TestingT`", # alt/middlewares/recovery/recovery.go: diff --git a/cmd/bug/bug.go b/cmd/bug/bug.go index 851f2296c..0fe6ce175 100644 --- a/cmd/bug/bug.go +++ b/cmd/bug/bug.go @@ -155,15 +155,15 @@ func sendReport(body string) { } } -func openBrowser(URL string) error { +func openBrowser(u string) error { var err error switch runtime.GOOS { case "linux": - err = exec.Command("xdg-open", URL).Start() + err = exec.Command("xdg-open", u).Start() case "windows": - err = exec.Command("rundll32", "url.dll,FileProtocolHandler", URL).Start() + err = exec.Command("rundll32", "url.dll,FileProtocolHandler", u).Start() case "darwin": - err = exec.Command("open", URL).Start() + err = exec.Command("open", u).Start() default: err = fmt.Errorf("unsupported platform") } diff --git a/cmd/traefik/traefik.go b/cmd/traefik/traefik.go index 4585ab902..a9187f003 100644 --- a/cmd/traefik/traefik.go +++ b/cmd/traefik/traefik.go @@ -293,7 +293,7 @@ func runCmd(staticConfiguration *static.Configuration, configFile string) error log.WithoutContext().Errorf("Could not enable Watchdog: %v", err) } else if t != 0 { // Send a ping each half time given - t = t / 2 + t /= 2 log.WithoutContext().Infof("Watchdog activated with timer duration %s", t) safe.Go(func() { tick := time.Tick(t) diff --git a/config/static/entrypoints.go b/config/static/entrypoints.go index 190456556..4e9b2c0c2 100644 --- a/config/static/entrypoints.go +++ b/config/static/entrypoints.go @@ -116,7 +116,9 @@ func makeEntryPointTLS(result map[string]string) (*tls.TLS, error) { if configTLS != nil { if len(result["ca"]) > 0 { files := tls.FilesOrContents{} - files.Set(result["ca"]) + if err := files.Set(result["ca"]); err != nil { + return nil, err + } optional := toBool(result, "ca_optional") configTLS.ClientCA = tls.ClientCA{ Files: files, diff --git a/config/static/static_config.go b/config/static/static_config.go index f23431ee0..a7d3a58f4 100644 --- a/config/static/static_config.go +++ b/config/static/static_config.go @@ -334,10 +334,8 @@ func (c *Configuration) ValidateConfiguration() { if c.ACME != nil { if _, ok := c.EntryPoints[c.ACME.EntryPoint]; !ok { log.Fatalf("Unknown entrypoint %q for ACME configuration", c.ACME.EntryPoint) - } else { - if c.EntryPoints[c.ACME.EntryPoint].TLS == nil { - log.Fatalf("Entrypoint %q has no TLS configuration for ACME configuration", c.ACME.EntryPoint) - } + } else if c.EntryPoints[c.ACME.EntryPoint].TLS == nil { + log.Fatalf("Entrypoint %q has no TLS configuration for ACME configuration", c.ACME.EntryPoint) } } } diff --git a/healthcheck/healthcheck.go b/healthcheck/healthcheck.go index a37c4107a..9a0c2886d 100644 --- a/healthcheck/healthcheck.go +++ b/healthcheck/healthcheck.go @@ -132,35 +132,35 @@ func (hc *HealthCheck) checkBackend(backend *BackendConfig) { var newDisabledURLs []*url.URL // FIXME re enable metrics for _, disableURL := range backend.disabledURLs { - //serverUpMetricValue := float64(0) + // FIXME serverUpMetricValue := float64(0) if err := checkHealth(disableURL, backend); err == nil { log.Warnf("Health check up: Returning to server list. Backend: %q URL: %q", backend.name, disableURL.String()) - if err := backend.LB.UpsertServer(disableURL, roundrobin.Weight(1)); err != nil { + if err = backend.LB.UpsertServer(disableURL, roundrobin.Weight(1)); err != nil { log.Error(err) } - //serverUpMetricValue = 1 + // FIXME serverUpMetricValue = 1 } else { log.Warnf("Health check still failing. Backend: %q URL: %q Reason: %s", backend.name, disableURL.String(), err) newDisabledURLs = append(newDisabledURLs, disableURL) } - //labelValues := []string{"backend", backend.name, "url", disableURL.String()} - //hc.metrics.BackendServerUpGauge().With(labelValues...).Set(serverUpMetricValue) + // FIXME labelValues := []string{"backend", backend.name, "url", disableURL.String()} + // FIXME hc.metrics.BackendServerUpGauge().With(labelValues...).Set(serverUpMetricValue) } backend.disabledURLs = newDisabledURLs // FIXME re enable metrics for _, enableURL := range enabledURLs { - //serverUpMetricValue := float64(1) + // FIXME serverUpMetricValue := float64(1) if err := checkHealth(enableURL, backend); err != nil { log.Warnf("Health check failed: Remove from server list. Backend: %q URL: %q Reason: %s", backend.name, enableURL.String(), err) if err := backend.LB.RemoveServer(enableURL); err != nil { log.Error(err) } backend.disabledURLs = append(backend.disabledURLs, enableURL) - //serverUpMetricValue = 0 + // FIXME serverUpMetricValue = 0 } - //labelValues := []string{"backend", backend.name, "url", enableURL.String()} - //hc.metrics.BackendServerUpGauge().With(labelValues...).Set(serverUpMetricValue) + // FIXME labelValues := []string{"backend", backend.name, "url", enableURL.String()} + // FIXME hc.metrics.BackendServerUpGauge().With(labelValues...).Set(serverUpMetricValue) } } diff --git a/middlewares/accesslog/logger.go b/middlewares/accesslog/logger.go index 8da53eaa6..898a3f125 100644 --- a/middlewares/accesslog/logger.go +++ b/middlewares/accesslog/logger.go @@ -272,7 +272,7 @@ func (h *Handler) logTheRoundTrip(logDataTable *LogData, crr *captureRequestRead core[DownstreamContentSize] = crw.Size() if original, ok := core[OriginContentSize]; ok { o64 := original.(int64) - if o64 != crw.Size() && 0 != crw.Size() { + if crw.Size() != o64 && crw.Size() != 0 { core[GzipRatio] = float64(o64) / float64(crw.Size()) } } diff --git a/middlewares/auth/forward.go b/middlewares/auth/forward.go index ad310eea1..b8680ef0e 100644 --- a/middlewares/auth/forward.go +++ b/middlewares/auth/forward.go @@ -167,19 +167,23 @@ func writeHeader(req *http.Request, forwardReq *http.Request, trustForwardHeader forwardReq.Header.Set(forward.XForwardedFor, clientIP) } - if xMethod := req.Header.Get(xForwardedMethod); xMethod != "" && trustForwardHeader { + xMethod := req.Header.Get(xForwardedMethod) + switch { + case xMethod != "" && trustForwardHeader: forwardReq.Header.Set(xForwardedMethod, xMethod) - } else if req.Method != "" { + case req.Method != "": forwardReq.Header.Set(xForwardedMethod, req.Method) - } else { + default: forwardReq.Header.Del(xForwardedMethod) } - if xfp := req.Header.Get(forward.XForwardedProto); xfp != "" && trustForwardHeader { + xfp := req.Header.Get(forward.XForwardedProto) + switch { + case xfp != "" && trustForwardHeader: forwardReq.Header.Set(forward.XForwardedProto, xfp) - } else if req.TLS != nil { + case req.TLS != nil: forwardReq.Header.Set(forward.XForwardedProto, "https") - } else { + default: forwardReq.Header.Set(forward.XForwardedProto, "http") } @@ -187,19 +191,23 @@ func writeHeader(req *http.Request, forwardReq *http.Request, trustForwardHeader forwardReq.Header.Set(forward.XForwardedPort, xfp) } - if xfh := req.Header.Get(forward.XForwardedHost); xfh != "" && trustForwardHeader { + xfh := req.Header.Get(forward.XForwardedHost) + switch { + case xfh != "" && trustForwardHeader: forwardReq.Header.Set(forward.XForwardedHost, xfh) - } else if req.Host != "" { + case req.Host != "": forwardReq.Header.Set(forward.XForwardedHost, req.Host) - } else { + default: forwardReq.Header.Del(forward.XForwardedHost) } - if xfURI := req.Header.Get(xForwardedURI); xfURI != "" && trustForwardHeader { + xfURI := req.Header.Get(xForwardedURI) + switch { + case xfURI != "" && trustForwardHeader: forwardReq.Header.Set(xForwardedURI, xfURI) - } else if req.URL.RequestURI() != "" { + case req.URL.RequestURI() != "": forwardReq.Header.Set(xForwardedURI, req.URL.RequestURI()) - } else { + default: forwardReq.Header.Del(xForwardedURI) } } diff --git a/middlewares/headers/headers_test.go b/middlewares/headers/headers_test.go index 373efafa6..8f23fd094 100644 --- a/middlewares/headers/headers_test.go +++ b/middlewares/headers/headers_test.go @@ -106,7 +106,7 @@ func TestSecureHeader(t *testing.T) { func TestSSLForceHost(t *testing.T) { next := http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { - rw.Write([]byte("OK")) + _, _ = rw.Write([]byte("OK")) }) testCases := []struct { diff --git a/middlewares/passtlsclientcert/pass_tls_client_cert.go b/middlewares/passtlsclientcert/pass_tls_client_cert.go index 926f9ef36..5bdf9bc8c 100644 --- a/middlewares/passtlsclientcert/pass_tls_client_cert.go +++ b/middlewares/passtlsclientcert/pass_tls_client_cert.go @@ -271,7 +271,8 @@ func getSANs(cert *x509.Certificate) []string { return sans } - sans = append(cert.DNSNames, cert.EmailAddresses...) + sans = append(sans, cert.DNSNames...) + sans = append(sans, cert.EmailAddresses...) var ips []string for _, ip := range cert.IPAddresses { diff --git a/middlewares/retry/retry_test.go b/middlewares/retry/retry_test.go index 8c77228f4..8a407c578 100644 --- a/middlewares/retry/retry_test.go +++ b/middlewares/retry/retry_test.go @@ -256,7 +256,7 @@ func TestRetryWebsocket(t *testing.T) { forwarder, err := forward.New() if err != nil { - t.Fatalf("Error creating forwarder: %s", err) + t.Fatalf("Error creating forwarder: %v", err) } backendServer := httptest.NewServer(http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { @@ -274,7 +274,7 @@ func TestRetryWebsocket(t *testing.T) { loadBalancer, err := roundrobin.New(forwarder) if err != nil { - t.Fatalf("Error creating load balancer: %s", err) + t.Fatalf("Error creating load balancer: %v", err) } basePort := 33444 @@ -287,7 +287,10 @@ func TestRetryWebsocket(t *testing.T) { } // add the functioning server to the end of the load balancer list - loadBalancer.UpsertServer(testhelpers.MustParseURL(backendServer.URL)) + err = loadBalancer.UpsertServer(testhelpers.MustParseURL(backendServer.URL)) + if err != nil { + t.Fatalf("Fail to upsert server: %v", err) + } retryListener := &countingRetryListener{} retryH, err := New(context.Background(), loadBalancer, config.Retry{Attempts: test.maxRequestAttempts}, retryListener, "traefikTest") diff --git a/provider/acme/local_store.go b/provider/acme/local_store.go index 03127cb08..94b6cc3e2 100644 --- a/provider/acme/local_store.go +++ b/provider/acme/local_store.go @@ -205,9 +205,7 @@ func (s *LocalStore) RemoveHTTPChallengeToken(token, domain string) error { } if _, ok := s.storedData.HTTPChallenges[token]; ok { - if _, domainOk := s.storedData.HTTPChallenges[token][domain]; domainOk { - delete(s.storedData.HTTPChallenges[token], domain) - } + delete(s.storedData.HTTPChallenges[token], domain) if len(s.storedData.HTTPChallenges[token]) == 0 { delete(s.storedData.HTTPChallenges, token) } diff --git a/provider/acme/provider.go b/provider/acme/provider.go index fe932865f..c2bbed84f 100644 --- a/provider/acme/provider.go +++ b/provider/acme/provider.go @@ -277,7 +277,8 @@ func (p *Provider) getClient() (*lego.Client, error) { return nil, err } - if p.DNSChallenge != nil && len(p.DNSChallenge.Provider) > 0 { + switch { + case p.DNSChallenge != nil && len(p.DNSChallenge.Provider) > 0: logger.Debugf("Using DNS Challenge provider: %s", p.DNSChallenge.Provider) var provider challenge.Provider @@ -310,21 +311,23 @@ func (p *Provider) getClient() (*lego.Client, error) { p.DNSChallenge.preCheckTimeout, p.DNSChallenge.preCheckInterval = challengeProviderTimeout.Timeout() } - } else if p.HTTPChallenge != nil && len(p.HTTPChallenge.EntryPoint) > 0 { + case p.HTTPChallenge != nil && len(p.HTTPChallenge.EntryPoint) > 0: logger.Debug("Using HTTP Challenge provider.") err = client.Challenge.SetHTTP01Provider(&challengeHTTP{Store: p.Store}) if err != nil { return nil, err } - } else if p.TLSChallenge != nil { + + case p.TLSChallenge != nil: logger.Debug("Using TLS Challenge provider.") err = client.Challenge.SetTLSALPN01Provider(&challengeTLSALPN{Store: p.Store}) if err != nil { return nil, err } - } else { + + default: return nil, errors.New("ACME challenge not specified, please select TLS or HTTP or DNS Challenge") } diff --git a/provider/base_provider.go b/provider/base_provider.go index e143a9b52..441b0d6b7 100644 --- a/provider/base_provider.go +++ b/provider/base_provider.go @@ -2,13 +2,11 @@ package provider import ( "bytes" - "io/ioutil" "strings" "text/template" "github.com/BurntSushi/toml" "github.com/Masterminds/sprig" - "github.com/containous/traefik/autogen/gentemplates" "github.com/containous/traefik/config" "github.com/containous/traefik/log" "github.com/containous/traefik/types" @@ -88,26 +86,6 @@ func (p *BaseProvider) DecodeConfiguration(content string) (*config.Configuratio return configuration, nil } -func (p *BaseProvider) getTemplateContent(defaultTemplateFile string) (string, error) { - if len(p.Filename) > 0 { - buf, err := ioutil.ReadFile(p.Filename) - if err != nil { - return "", err - } - return string(buf), nil - } - - if strings.HasSuffix(defaultTemplateFile, ".tmpl") { - buf, err := gentemplates.Asset(defaultTemplateFile) - if err != nil { - return "", err - } - return string(buf), nil - } - - return defaultTemplateFile, nil -} - func split(sep, s string) []string { return strings.Split(s, sep) } diff --git a/provider/docker/config.go b/provider/docker/config.go index 95c12f3c0..65ab3b84f 100644 --- a/provider/docker/config.go +++ b/provider/docker/config.go @@ -139,11 +139,12 @@ func (p *Provider) getIPPort(ctx context.Context, container dockerData, serverPo if p.UseBindPortIP { portBinding, err := p.getPortBinding(container, serverPort) - if err != nil { + switch { + case err != nil: logger.Infof("Unable to find a binding for container %q, falling back on its internal IP/Port.", container.Name) - } else if (portBinding.HostIP == "0.0.0.0") || (len(portBinding.HostIP) == 0) { + case portBinding.HostIP == "0.0.0.0" || len(portBinding.HostIP) == 0: logger.Infof("Cannot determine the IP address (got %q) for %q's binding, falling back on its internal IP/Port.", portBinding.HostIP, container.Name) - } else { + default: ip = portBinding.HostIP port = portBinding.HostPort usedBound = true @@ -166,9 +167,9 @@ func (p Provider) getIPAddress(ctx context.Context, container dockerData) string logger := log.FromContext(ctx) if container.ExtraConf.Docker.Network != "" { - networkSettings := container.NetworkSettings - if networkSettings.Networks != nil { - network := networkSettings.Networks[container.ExtraConf.Docker.Network] + settings := container.NetworkSettings + if settings.Networks != nil { + network := settings.Networks[container.ExtraConf.Docker.Network] if network != nil { return network.Addr } @@ -251,11 +252,6 @@ func getPort(container dockerData, serverPort string) string { return "" } -// Escape beginning slash "/", convert all others to dash "-", and convert underscores "_" to dash "-" -func getSubDomain(name string) string { - return strings.NewReplacer("/", "-", "_", "-").Replace(strings.TrimPrefix(name, "/")) -} - func getServiceName(container dockerData) string { serviceName := container.ServiceName diff --git a/provider/file/file.go b/provider/file/file.go index 522fc801e..a11c66451 100644 --- a/provider/file/file.go +++ b/provider/file/file.go @@ -47,11 +47,12 @@ func (p *Provider) Provide(configurationChan chan<- config.Message, pool *safe.P if p.Watch { var watchItem string - if len(p.Directory) > 0 { + switch { + case len(p.Directory) > 0: watchItem = p.Directory - } else if len(p.Filename) > 0 { + case len(p.Filename) > 0: watchItem = filepath.Dir(p.Filename) - } else { + default: watchItem = filepath.Dir(p.TraefikFile) } diff --git a/provider/rest/rest.go b/provider/rest/rest.go index aa245ac3e..a6076ae7f 100644 --- a/provider/rest/rest.go +++ b/provider/rest/rest.go @@ -45,16 +45,16 @@ func (p *Provider) Append(systemRouter *mux.Router) { configuration := new(config.Configuration) body, _ := ioutil.ReadAll(request.Body) - err := json.Unmarshal(body, configuration) - if err == nil { - p.configurationChan <- config.Message{ProviderName: "rest", Configuration: configuration} - err := templatesRenderer.JSON(response, http.StatusOK, configuration) - if err != nil { - log.WithoutContext().Error(err) - } - } else { + + if err := json.Unmarshal(body, configuration); err != nil { log.WithoutContext().Errorf("Error parsing configuration %+v", err) http.Error(response, fmt.Sprintf("%+v", err), http.StatusBadRequest) + return + } + + p.configurationChan <- config.Message{ProviderName: "rest", Configuration: configuration} + if err := templatesRenderer.JSON(response, http.StatusOK, configuration); err != nil { + log.WithoutContext().Error(err) } }) } diff --git a/server/server_signals.go b/server/server_signals.go index 5badcff24..028ac5493 100644 --- a/server/server_signals.go +++ b/server/server_signals.go @@ -19,8 +19,7 @@ func (s *Server) listenSignals(stop chan bool) { case <-stop: return case sig := <-s.signals: - switch sig { - case syscall.SIGUSR1: + if sig == syscall.SIGUSR1 { log.WithoutContext().Infof("Closing and re-opening log files for rotation: %+v", sig) if s.accessLoggerMiddleware != nil { diff --git a/server/service/service.go b/server/service/service.go index 88055f03b..7ff7320fa 100644 --- a/server/service/service.go +++ b/server/service/service.go @@ -28,17 +28,6 @@ const ( defaultHealthCheckTimeout = 5 * time.Second ) -// See oxy/roundrobin/rr.go -type balancerHandler interface { - Servers() []*url.URL - ServeHTTP(w http.ResponseWriter, req *http.Request) - ServerWeight(u *url.URL) (int, bool) - RemoveServer(u *url.URL) error - UpsertServer(u *url.URL, options ...roundrobin.ServerOption) error - NextServer() (*url.URL, error) - Next() http.Handler -} - // NewManager creates a new Manager func NewManager(configs map[string]*config.Service, defaultRoundTripper http.RoundTripper) *Manager { return &Manager{ @@ -148,11 +137,12 @@ func buildHealthCheckOptions(ctx context.Context, lb healthcheck.BalancerHandler interval := defaultHealthCheckInterval if hc.Interval != "" { intervalOverride, err := time.ParseDuration(hc.Interval) - if err != nil { + switch { + case err != nil: logger.Errorf("Illegal health check interval for '%s': %s", backend, err) - } else if intervalOverride <= 0 { + case intervalOverride <= 0: logger.Errorf("Health check interval smaller than zero for service '%s'", backend) - } else { + default: interval = intervalOverride } } @@ -160,11 +150,12 @@ func buildHealthCheckOptions(ctx context.Context, lb healthcheck.BalancerHandler timeout := defaultHealthCheckTimeout if hc.Timeout != "" { timeoutOverride, err := time.ParseDuration(hc.Timeout) - if err != nil { + switch { + case err != nil: logger.Errorf("Illegal health check timeout for backend '%s': %s", backend, err) - } else if timeoutOverride <= 0 { + case timeoutOverride <= 0: logger.Errorf("Health check timeout smaller than zero for backend '%s', backend", backend) - } else { + default: timeout = timeoutOverride } } diff --git a/types/constraints.go b/types/constraints.go index 9f979b0f9..dc658ce03 100644 --- a/types/constraints.go +++ b/types/constraints.go @@ -23,13 +23,14 @@ func NewConstraint(exp string) (*Constraint, error) { sep := "" constraint := &Constraint{} - if strings.Contains(exp, "==") { + switch { + case strings.Contains(exp, "=="): sep = "==" constraint.MustMatch = true - } else if strings.Contains(exp, "!=") { + case strings.Contains(exp, "!="): sep = "!=" constraint.MustMatch = false - } else { + default: return nil, errors.New("constraint expression missing valid operator: '==' or '!='") }