Skip to content

Commit 9cd47dd

Browse files
mmaturtraefiker
authored andcommitted
Small code enhancements
1 parent 015cd7a commit 9cd47dd

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

41 files changed

+187
-85
lines changed

.golangci.toml

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
[linters-settings]
2+
3+
[linters-settings.govet]
4+
check-shadowing = true
5+
6+
[linters-settings.golint]
7+
min-confidence = 0.0
8+
9+
[linters-settings.gocyclo]
10+
min-complexity = 22.0
11+
12+
[linters-settings.maligned]
13+
suggest-new = true
14+
15+
[linters-settings.goconst]
16+
min-len = 2.0
17+
min-occurrences = 2.0
18+
19+
[linters-settings.misspell]
20+
locale = "US"
21+
22+
[linters]
23+
enable-all = true
24+
disable = [
25+
"maligned",
26+
"lll",
27+
"gas",
28+
"dupl",
29+
"prealloc"
30+
]

cluster/datastore.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,7 @@ func (s *datastoreTransaction) Commit(object Object) error {
233233
}
234234
err = s.kv.StoreConfig(s.Datastore.meta)
235235
if err != nil {
236-
return fmt.Errorf("StoreConfig error: %s", err)
236+
return fmt.Errorf("storeConfig error: %s", err)
237237
}
238238

239239
err = s.remoteLock.Unlock()

cmd/context.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import (
77
"syscall"
88
)
99

10-
// ContextWithSignal create a context cancelled when SIGINT or SIGTERM are notified
10+
// ContextWithSignal creates a context canceled when SIGINT or SIGTERM are notified
1111
func ContextWithSignal(ctx context.Context) context.Context {
1212
newCtx, cancel := context.WithCancel(ctx)
1313
signals := make(chan os.Signal)

cmd/traefik/traefik.go

+5-3
Original file line numberDiff line numberDiff line change
@@ -158,7 +158,9 @@ func runCmd(globalConfiguration *configuration.GlobalConfiguration, configFile s
158158

159159
http.DefaultTransport.(*http.Transport).Proxy = http.ProxyFromEnvironment
160160

161-
roundrobin.SetDefaultWeight(0)
161+
if err := roundrobin.SetDefaultWeight(0); err != nil {
162+
log.Error(err)
163+
}
162164

163165
globalConfiguration.SetEffectiveConfiguration(configFile)
164166
globalConfiguration.ValidateConfiguration()
@@ -182,8 +184,8 @@ func runCmd(globalConfiguration *configuration.GlobalConfiguration, configFile s
182184

183185
acmeprovider := globalConfiguration.InitACMEProvider()
184186
if acmeprovider != nil {
185-
err := providerAggregator.AddProvider(acmeprovider)
186-
if err != nil {
187+
188+
if err := providerAggregator.AddProvider(acmeprovider); err != nil {
187189
log.Errorf("Error initializing provider ACME: %v", err)
188190
acmeprovider = nil
189191
}

configuration/router/internal_router.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,9 @@ func (wm *WithMiddleware) AddRoutes(systemRouter *mux.Router) {
7979
wm.router.AddRoutes(realRouter)
8080

8181
if len(wm.routerMiddlewares) > 0 {
82-
realRouter.Walk(wrapRoute(wm.routerMiddlewares))
82+
if err := realRouter.Walk(wrapRoute(wm.routerMiddlewares)); err != nil {
83+
log.Error(err)
84+
}
8385
}
8486
}
8587

configuration/router/internal_router_test.go

+21-5
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"github.com/containous/traefik/acme"
1010
"github.com/containous/traefik/api"
1111
"github.com/containous/traefik/configuration"
12+
"github.com/containous/traefik/log"
1213
"github.com/containous/traefik/ping"
1314
acmeprovider "github.com/containous/traefik/provider/acme"
1415
"github.com/containous/traefik/safe"
@@ -104,20 +105,35 @@ func TestWithMiddleware(t *testing.T) {
104105
router := WithMiddleware{
105106
router: MockInternalRouterFunc(func(systemRouter *mux.Router) {
106107
systemRouter.Handle("/test", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
107-
w.Write([]byte("router"))
108+
109+
if _, err := w.Write([]byte("router")); err != nil {
110+
log.Error(err)
111+
}
108112
}))
109113
}),
110114
routerMiddlewares: []negroni.Handler{
111115
negroni.HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
112-
rw.Write([]byte("before middleware1|"))
116+
if _, err := rw.Write([]byte("before middleware1|")); err != nil {
117+
log.Error(err)
118+
}
119+
113120
next.ServeHTTP(rw, r)
114-
rw.Write([]byte("|after middleware1"))
121+
122+
if _, err := rw.Write([]byte("|after middleware1")); err != nil {
123+
log.Error(err)
124+
}
115125

116126
}),
117127
negroni.HandlerFunc(func(rw http.ResponseWriter, r *http.Request, next http.HandlerFunc) {
118-
rw.Write([]byte("before middleware2|"))
128+
if _, err := rw.Write([]byte("before middleware2|")); err != nil {
129+
log.Error(err)
130+
}
131+
119132
next.ServeHTTP(rw, r)
120-
rw.Write([]byte("|after middleware2"))
133+
134+
if _, err := rw.Write([]byte("|after middleware2")); err != nil {
135+
log.Error(err)
136+
}
121137
}),
122138
},
123139
}

docs/configuration/acme.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -328,7 +328,7 @@ It is not possible to request a double wildcard certificate for a domain (for ex
328328
Due to ACME limitation it is not possible to define wildcards in SANs (alternative domains). Thus, the wildcard domain has to be defined as a main domain.
329329
Most likely the root domain should receive a certificate too, so it needs to be specified as SAN and 2 `DNS-01` challenges are executed.
330330
In this case the generated DNS TXT record for both domains is the same.
331-
Eventhough this behaviour is [DNS RFC](https://community.letsencrypt.org/t/wildcard-issuance-two-txt-records-for-the-same-name/54528/2) compliant, it can lead to problems as all DNS providers keep DNS records cached for a certain time (TTL) and this TTL can be superior to the challenge timeout making the `DNS-01` challenge fail.
331+
Eventhough this behavior is [DNS RFC](https://community.letsencrypt.org/t/wildcard-issuance-two-txt-records-for-the-same-name/54528/2) compliant, it can lead to problems as all DNS providers keep DNS records cached for a certain time (TTL) and this TTL can be superior to the challenge timeout making the `DNS-01` challenge fail.
332332
The Træfik ACME client library [LEGO](https://github.com/xenolf/lego) supports some but not all DNS providers to work around this issue.
333333
The [`provider` table](/configuration/acme/#provider) indicates if they allow generating certificates for a wildcard domain and its root domain.
334334

docs/configuration/backends/ecs.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -126,9 +126,9 @@ Træfik needs the following policy to read ECS information:
126126
}
127127
```
128128

129-
## Labels: overriding default behaviour
129+
## Labels: overriding default behavior
130130

131-
Labels can be used on task containers to override default behaviour:
131+
Labels can be used on task containers to override default behavior:
132132

133133
| Label | Description |
134134
|------------------------------------------------------------|-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|

healthcheck/healthcheck.go

+17-13
Original file line numberDiff line numberDiff line change
@@ -130,30 +130,34 @@ func (hc *HealthCheck) execute(ctx context.Context, backend *BackendConfig) {
130130
func (hc *HealthCheck) checkBackend(backend *BackendConfig) {
131131
enabledURLs := backend.LB.Servers()
132132
var newDisabledURLs []*url.URL
133-
for _, url := range backend.disabledURLs {
133+
for _, disableURL := range backend.disabledURLs {
134134
serverUpMetricValue := float64(0)
135-
if err := checkHealth(url, backend); err == nil {
136-
log.Warnf("Health check up: Returning to server list. Backend: %q URL: %q", backend.name, url.String())
137-
backend.LB.UpsertServer(url, roundrobin.Weight(1))
135+
if err := checkHealth(disableURL, backend); err == nil {
136+
log.Warnf("Health check up: Returning to server list. Backend: %q URL: %q", backend.name, disableURL.String())
137+
if err := backend.LB.UpsertServer(disableURL, roundrobin.Weight(1)); err != nil {
138+
log.Error(err)
139+
}
138140
serverUpMetricValue = 1
139141
} else {
140-
log.Warnf("Health check still failing. Backend: %q URL: %q Reason: %s", backend.name, url.String(), err)
141-
newDisabledURLs = append(newDisabledURLs, url)
142+
log.Warnf("Health check still failing. Backend: %q URL: %q Reason: %s", backend.name, disableURL.String(), err)
143+
newDisabledURLs = append(newDisabledURLs, disableURL)
142144
}
143-
labelValues := []string{"backend", backend.name, "url", url.String()}
145+
labelValues := []string{"backend", backend.name, "url", disableURL.String()}
144146
hc.metrics.BackendServerUpGauge().With(labelValues...).Set(serverUpMetricValue)
145147
}
146148
backend.disabledURLs = newDisabledURLs
147149

148-
for _, url := range enabledURLs {
150+
for _, enableURL := range enabledURLs {
149151
serverUpMetricValue := float64(1)
150-
if err := checkHealth(url, backend); err != nil {
151-
log.Warnf("Health check failed: Remove from server list. Backend: %q URL: %q Reason: %s", backend.name, url.String(), err)
152-
backend.LB.RemoveServer(url)
153-
backend.disabledURLs = append(backend.disabledURLs, url)
152+
if err := checkHealth(enableURL, backend); err != nil {
153+
log.Warnf("Health check failed: Remove from server list. Backend: %q URL: %q Reason: %s", backend.name, enableURL.String(), err)
154+
if err := backend.LB.RemoveServer(enableURL); err != nil {
155+
log.Error(err)
156+
}
157+
backend.disabledURLs = append(backend.disabledURLs, enableURL)
154158
serverUpMetricValue = 0
155159
}
156-
labelValues := []string{"backend", backend.name, "url", url.String()}
160+
labelValues := []string{"backend", backend.name, "url", enableURL.String()}
157161
hc.metrics.BackendServerUpGauge().With(labelValues...).Set(serverUpMetricValue)
158162
}
159163
}

healthcheck/healthcheck_test.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -94,7 +94,7 @@ func TestSetBackendsConfiguration(t *testing.T) {
9494
t.Run(test.desc, func(t *testing.T) {
9595
t.Parallel()
9696

97-
// The context is passed to the health check and canonically cancelled by
97+
// The context is passed to the health check and canonically canceled by
9898
// the test server once all expected requests have been received.
9999
ctx, cancel := context.WithCancel(context.Background())
100100
defer cancel()

hostresolver/hostresolver.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,9 @@ func (hr *Resolver) CNAMEFlatten(host string) (string, string) {
6363
request = resolv.Record
6464
}
6565

66-
hr.cache.Add(host, strings.Join(result, ","), cacheDuration)
66+
if err := hr.cache.Add(host, strings.Join(result, ","), cacheDuration); err != nil {
67+
log.Error(err)
68+
}
6769
}
6870

6971
return result[0], result[len(result)-1]

integration/access_log_test.go

+7-2
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"time"
1313

1414
"github.com/containous/traefik/integration/try"
15+
"github.com/containous/traefik/log"
1516
"github.com/containous/traefik/middlewares/accesslog"
1617
"github.com/go-check/check"
1718
checker "github.com/vdemeester/shakers"
@@ -324,13 +325,17 @@ func digestParts(resp *http.Response) map[string]string {
324325

325326
func getMD5(data string) string {
326327
digest := md5.New()
327-
digest.Write([]byte(data))
328+
if _, err := digest.Write([]byte(data)); err != nil {
329+
log.Error(err)
330+
}
328331
return fmt.Sprintf("%x", digest.Sum(nil))
329332
}
330333

331334
func getCnonce() string {
332335
b := make([]byte, 8)
333-
io.ReadFull(rand.Reader, b)
336+
if _, err := io.ReadFull(rand.Reader, b); err != nil {
337+
log.Error(err)
338+
}
334339
return fmt.Sprintf("%x", b)[:16]
335340
}
336341

integration/consul_catalog_test.go

+4-2
Original file line numberDiff line numberDiff line change
@@ -530,7 +530,8 @@ func (s *ConsulCatalogSuite) TestRetryWithConsulServer(c *check.C) {
530530

531531
// Scale consul to 1
532532
s.composeProject.Scale(c, "consul", 1)
533-
s.waitToElectConsulLeader()
533+
err = s.waitToElectConsulLeader()
534+
c.Assert(err, checker.IsNil)
534535

535536
whoami := s.composeProject.Container(c, "whoami1")
536537
// Register service
@@ -576,7 +577,8 @@ func (s *ConsulCatalogSuite) TestServiceWithMultipleHealthCheck(c *check.C) {
576577

577578
// Scale consul to 1
578579
s.composeProject.Scale(c, "consul", 1)
579-
s.waitToElectConsulLeader()
580+
err = s.waitToElectConsulLeader()
581+
c.Assert(err, checker.IsNil)
580582

581583
whoami := s.composeProject.Container(c, "whoami1")
582584
// Register service

integration/etcd3_test.go

+2-1
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,8 @@ func (s *Etcd3Suite) TestCommandStoreConfig(c *check.C) {
404404
c.Assert(err, checker.IsNil)
405405

406406
// wait for traefik finish without error
407-
cmd.Wait()
407+
err = cmd.Wait()
408+
c.Assert(err, checker.IsNil)
408409

409410
// CHECK
410411
checkmap := map[string]string{

integration/etcd_test.go

+3-2
Original file line numberDiff line numberDiff line change
@@ -411,8 +411,9 @@ func (s *EtcdSuite) TestCommandStoreConfig(c *check.C) {
411411
err := cmd.Start()
412412
c.Assert(err, checker.IsNil)
413413

414-
// wait for Træfik finish without error
415-
cmd.Wait()
414+
// wait for traefik finish without error
415+
err = cmd.Wait()
416+
c.Assert(err, checker.IsNil)
416417

417418
// CHECK
418419
checkmap := map[string]string{

integration/fake_dns_server.go

+3-1
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,9 @@ func (s *handler) ServeDNS(w dns.ResponseWriter, r *dns.Msg) {
9393
auth.Minttl = 1
9494
m.Ns = append(m.Ns, auth)
9595

96-
w.WriteMsg(m)
96+
if err := w.WriteMsg(m); err != nil {
97+
log.Fatalf("Failed to write message %v", err)
98+
}
9799
}
98100

99101
func startFakeDNSServer() *dns.Server {

integration/grpc_test.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313

1414
"github.com/containous/traefik/integration/helloworld"
1515
"github.com/containous/traefik/integration/try"
16+
"github.com/containous/traefik/log"
1617
"github.com/go-check/check"
1718
"google.golang.org/grpc"
1819
"google.golang.org/grpc/credentials"
@@ -47,7 +48,11 @@ func (s *myserver) StreamExample(in *helloworld.StreamExampleRequest, server hel
4748
for i := range data {
4849
data[i] = randCharset[rand.Intn(len(randCharset))]
4950
}
50-
server.Send(&helloworld.StreamExampleReply{Data: string(data)})
51+
52+
if err := server.Send(&helloworld.StreamExampleReply{Data: string(data)}); err != nil {
53+
log.Error(err)
54+
}
55+
5156
<-s.stopStreamExample
5257
return nil
5358
}

integration/https_test.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -708,7 +708,10 @@ func modifyCertificateConfFileContent(c *check.C, certFileName, confFileName, en
708708
defer func() {
709709
f.Close()
710710
}()
711-
f.Truncate(0)
711+
712+
err = f.Truncate(0)
713+
c.Assert(err, checker.IsNil)
714+
712715
// If certificate file is not provided, just truncate the configuration file
713716
if len(certFileName) > 0 {
714717
tlsConf := types.Configuration{

middlewares/accesslog/logger.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,10 @@ const (
2626
DataTableKey key = "LogDataTable"
2727

2828
// CommonFormat is the common logging format (CLF)
29-
CommonFormat = "common"
29+
CommonFormat string = "common"
3030

3131
// JSONFormat is the JSON logging format
32-
JSONFormat = "json"
32+
JSONFormat string = "json"
3333
)
3434

3535
type logHandlerParams struct {

middlewares/accesslog/logger_test.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import (
1515
"time"
1616

1717
"github.com/containous/flaeg/parse"
18+
"github.com/containous/traefik/log"
1819
"github.com/containous/traefik/types"
1920
"github.com/stretchr/testify/assert"
2021
"github.com/stretchr/testify/require"
@@ -626,7 +627,10 @@ func doLogging(t *testing.T, config *types.AccessLog) {
626627
}
627628

628629
func logWriterTestHandlerFunc(rw http.ResponseWriter, r *http.Request) {
629-
rw.Write([]byte(testContent))
630+
if _, err := rw.Write([]byte(testContent)); err != nil {
631+
log.Error(err)
632+
}
633+
630634
rw.WriteHeader(testStatus)
631635

632636
logDataTable := GetLogDataTable(r)

middlewares/auth/forward.go

+4-1
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,10 @@ func Forward(config *types.Forward, w http.ResponseWriter, r *http.Request, next
9090

9191
tracing.LogResponseCode(tracing.GetSpan(r), forwardResponse.StatusCode)
9292
w.WriteHeader(forwardResponse.StatusCode)
93-
w.Write(body)
93+
94+
if _, err = w.Write(body); err != nil {
95+
log.Error(err)
96+
}
9497
return
9598
}
9699

middlewares/cbreaker.go

+5-1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package middlewares
33
import (
44
"net/http"
55

6+
"github.com/containous/traefik/log"
67
"github.com/containous/traefik/middlewares/tracing"
78
"github.com/vulcand/oxy/cbreaker"
89
)
@@ -27,7 +28,10 @@ func NewCircuitBreakerOptions(expression string) cbreaker.CircuitBreakerOption {
2728
tracing.LogEventf(r, "blocked by circuit-breaker (%q)", expression)
2829

2930
w.WriteHeader(http.StatusServiceUnavailable)
30-
w.Write([]byte(http.StatusText(http.StatusServiceUnavailable)))
31+
32+
if _, err := w.Write([]byte(http.StatusText(http.StatusServiceUnavailable))); err != nil {
33+
log.Error(err)
34+
}
3135
}))
3236
}
3337

0 commit comments

Comments
 (0)