Skip to content

Commit

Permalink
refactor: applies linting.
Browse files Browse the repository at this point in the history
  • Loading branch information
ldez authored and traefiker committed Feb 5, 2019
1 parent 54ca0ce commit 115ddc6
Show file tree
Hide file tree
Showing 20 changed files with 111 additions and 111 deletions.
23 changes: 22 additions & 1 deletion .golangci.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -21,7 +36,7 @@

[linters-settings.goconst]
min-len = 3.0
min-occurrences = 3.0
min-occurrences = 4.0

[linters-settings.misspell]
locale = "US"
Expand All @@ -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:
Expand Down
8 changes: 4 additions & 4 deletions cmd/bug/bug.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/traefik/traefik.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 3 additions & 1 deletion config/static/entrypoints.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
6 changes: 2 additions & 4 deletions config/static/static_config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}
}
Expand Down
18 changes: 9 additions & 9 deletions healthcheck/healthcheck.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

Expand Down
2 changes: 1 addition & 1 deletion middlewares/accesslog/logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}
Expand Down
32 changes: 20 additions & 12 deletions middlewares/auth/forward.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,39 +167,47 @@ 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")
}

if xfp := req.Header.Get(forward.XForwardedPort); xfp != "" && 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)
}
}
2 changes: 1 addition & 1 deletion middlewares/headers/headers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
3 changes: 2 additions & 1 deletion middlewares/passtlsclientcert/pass_tls_client_cert.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
9 changes: 6 additions & 3 deletions middlewares/retry/retry_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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
Expand All @@ -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")
Expand Down
4 changes: 1 addition & 3 deletions provider/acme/local_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
Expand Down
11 changes: 7 additions & 4 deletions provider/acme/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
}

Expand Down
22 changes: 0 additions & 22 deletions provider/base_provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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)
}
18 changes: 7 additions & 11 deletions provider/docker/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
}
Expand Down Expand Up @@ -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

Expand Down
Loading

0 comments on commit 115ddc6

Please sign in to comment.