Skip to content

Commit 54b9d20

Browse files
authored
Upgrade golangci-lint, more linters (#432)
1 parent 7a3d4d2 commit 54b9d20

Some content is hidden

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

81 files changed

+1173
-774
lines changed

.golangci.yml

+31-18
Original file line numberDiff line numberDiff line change
@@ -25,17 +25,32 @@ linters-settings:
2525
- ^os.Exit$
2626
- ^panic$
2727
- ^print(ln)?$
28+
varnamelen:
29+
max-distance: 12
30+
min-name-length: 2
31+
ignore-type-assert-ok: true
32+
ignore-map-index-ok: true
33+
ignore-chan-recv-ok: true
34+
ignore-decls:
35+
- i int
36+
- n int
37+
- w io.Writer
38+
- r io.Reader
39+
- b []byte
2840

2941
linters:
3042
enable:
3143
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
3244
- bidichk # Checks for dangerous unicode character sequences
3345
- bodyclose # checks whether HTTP response body is closed successfully
46+
- containedctx # containedctx is a linter that detects struct contained context.Context field
3447
- contextcheck # check the function whether use a non-inherited context
48+
- cyclop # checks function and package cyclomatic complexity
3549
- decorder # check declaration order and count of types, constants, variables and functions
3650
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
3751
- dupl # Tool for code clone detection
3852
- durationcheck # check for two durations multiplied together
53+
- err113 # Golang linter to check the errors handling expressions
3954
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
4055
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted.
4156
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
@@ -44,68 +59,66 @@ linters:
4459
- exportloopref # checks for pointers to enclosing loop variables
4560
- forbidigo # Forbids identifiers
4661
- forcetypeassert # finds forced type assertions
62+
- funlen # Tool for detection of long functions
4763
- gci # Gci control golang package import order and make it always deterministic.
4864
- gochecknoglobals # Checks that no globals are present in Go code
49-
- gochecknoinits # Checks that no init functions are present in Go code
5065
- gocognit # Computes and checks the cognitive complexity of functions
5166
- goconst # Finds repeated strings that could be replaced by a constant
5267
- gocritic # The most opinionated Go source code linter
68+
- gocyclo # Computes and checks the cyclomatic complexity of functions
69+
- godot # Check if comments end in a period
5370
- godox # Tool for detection of FIXME, TODO and other comment keywords
54-
- err113 # Golang linter to check the errors handling expressions
5571
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
5672
- gofumpt # Gofumpt checks whether code was gofumpt-ed.
5773
- goheader # Checks is file header matches to pattern
5874
- goimports # Goimports does everything that gofmt does. Additionally it checks unused imports
5975
- gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.
60-
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
6176
- goprintffuncname # Checks that printf-like functions are named with `f` at the end
6277
- gosec # Inspects source code for security problems
6378
- gosimple # Linter for Go source code that specializes in simplifying a code
6479
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
6580
- grouper # An analyzer to analyze expression groups.
6681
- importas # Enforces consistent import aliases
6782
- ineffassign # Detects when assignments to existing variables are not used
83+
- lll # Reports long lines
84+
- maintidx # maintidx measures the maintainability index of each function.
85+
- makezero # Finds slice declarations with non-zero initial length
6886
- misspell # Finds commonly misspelled English words in comments
87+
- nakedret # Finds naked returns in functions greater than a specified function length
88+
- nestif # Reports deeply nested if statements
6989
- nilerr # Finds the code that returns nil even if it checks that the error is not nil.
7090
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value.
91+
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
7192
- noctx # noctx finds sending http request without context.Context
7293
- predeclared # find code that shadows one of Go's predeclared identifiers
7394
- revive # golint replacement, finds style mistakes
7495
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
7596
- stylecheck # Stylecheck is a replacement for golint
7697
- tagliatelle # Checks the struct tags.
7798
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
78-
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
99+
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
79100
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
80101
- unconvert # Remove unnecessary type conversions
81102
- unparam # Reports unused function parameters
82103
- unused # Checks Go code for unused constants, variables, functions and types
104+
- varnamelen # checks that the length of a variable's name matches its scope
83105
- wastedassign # wastedassign finds wasted assignment statements
84106
- whitespace # Tool for detection of leading and trailing whitespace
85107
disable:
86108
- depguard # Go linter that checks if package imports are in a list of acceptable packages
87-
- containedctx # containedctx is a linter that detects struct contained context.Context field
88-
- cyclop # checks function and package cyclomatic complexity
89-
- funlen # Tool for detection of long functions
90-
- gocyclo # Computes and checks the cyclomatic complexity of functions
91-
- godot # Check if comments end in a period
92-
- gomnd # An analyzer to detect magic numbers.
109+
- gochecknoinits # Checks that no init functions are present in Go code
110+
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations.
111+
- interfacebloat # A linter that checks length of interface.
93112
- ireturn # Accept Interfaces, Return Concrete Types
94-
- lll # Reports long lines
95-
- maintidx # maintidx measures the maintainability index of each function.
96-
- makezero # Finds slice declarations with non-zero initial length
97-
- nakedret # Finds naked returns in functions greater than a specified function length
98-
- nestif # Reports deeply nested if statements
99-
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
113+
- mnd # An analyzer to detect magic numbers
100114
- nolintlint # Reports ill-formed or insufficient nolint directives
101115
- paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test
102116
- prealloc # Finds slice declarations that could potentially be preallocated
103117
- promlinter # Check Prometheus metrics naming via promlint
104118
- rowserrcheck # checks whether Err of rows is checked successfully
105119
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
106120
- testpackage # linter that makes you use a separate _test package
107-
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
108-
- varnamelen # checks that the length of a variable's name matches its scope
121+
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
109122
- wrapcheck # Checks that errors returned from external packages are wrapped
110123
- wsl # Whitespace Linter - Forces you to use empty lines!
111124

client.go

+38-17
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ type ClientConfig struct {
4949
LoggerFactory logging.LoggerFactory
5050
}
5151

52-
// Client is a STUN server client
52+
// Client is a STUN server client.
5353
type Client struct {
5454
conn net.PacketConn // Read-only
5555
net transport.Net // Read-only
@@ -72,7 +72,8 @@ type Client struct {
7272
log logging.LeveledLogger // Read-only
7373
}
7474

75-
// NewClient returns a new Client instance. listeningAddress is the address and port to listen on, default "0.0.0.0:0"
75+
// NewClient returns a new Client instance. listeningAddress is the address and port to listen on,
76+
// default "0.0.0.0:0".
7677
func NewClient(config *ClientConfig) (*Client, error) {
7778
loggerFactory := config.LoggerFactory
7879
if loggerFactory == nil {
@@ -119,7 +120,7 @@ func NewClient(config *ClientConfig) (*Client, error) {
119120
log.Debugf("Resolved TURN server %s to %s", config.TURNServerAddr, turnServ)
120121
}
121122

122-
c := &Client{
123+
client := &Client{
123124
conn: config.Conn,
124125
stunServerAddr: stunServ,
125126
turnServerAddr: turnServ,
@@ -133,25 +134,25 @@ func NewClient(config *ClientConfig) (*Client, error) {
133134
log: log,
134135
}
135136

136-
return c, nil
137+
return client, nil
137138
}
138139

139-
// TURNServerAddr return the TURN server address
140+
// TURNServerAddr return the TURN server address.
140141
func (c *Client) TURNServerAddr() net.Addr {
141142
return c.turnServerAddr
142143
}
143144

144-
// STUNServerAddr return the STUN server address
145+
// STUNServerAddr return the STUN server address.
145146
func (c *Client) STUNServerAddr() net.Addr {
146147
return c.stunServerAddr
147148
}
148149

149-
// Username returns username
150+
// Username returns username.
150151
func (c *Client) Username() stun.Username {
151152
return c.username
152153
}
153154

154-
// Realm return realm
155+
// Realm return realm.
155156
func (c *Client) Realm() stun.Realm {
156157
return c.realm
157158
}
@@ -175,12 +176,14 @@ func (c *Client) Listen() error {
175176
n, from, err := c.conn.ReadFrom(buf)
176177
if err != nil {
177178
c.log.Debugf("Failed to read: %s. Exiting loop", err)
179+
178180
break
179181
}
180182

181183
_, err = c.HandleInbound(buf[:n], from)
182184
if err != nil {
183185
c.log.Debugf("Failed to handle inbound message: %s. Exiting loop", err)
186+
184187
break
185188
}
186189
}
@@ -191,7 +194,7 @@ func (c *Client) Listen() error {
191194
return nil
192195
}
193196

194-
// Close closes this client
197+
// Close closes this client.
195198
func (c *Client) Close() {
196199
c.mutexTrMap.Lock()
197200
defer c.mutexTrMap.Unlock()
@@ -201,7 +204,7 @@ func (c *Client) Close() {
201204

202205
// TransactionID & Base64: https://play.golang.org/p/EEgmJDI971P
203206

204-
// SendBindingRequestTo sends a new STUN request to the given transport address
207+
// SendBindingRequestTo sends a new STUN request to the given transport address.
205208
func (c *Client) SendBindingRequestTo(to net.Addr) (net.Addr, error) {
206209
attrs := []stun.Setter{stun.TransactionID, stun.BindingRequest}
207210
if len(c.software) > 0 {
@@ -228,15 +231,21 @@ func (c *Client) SendBindingRequestTo(to net.Addr) (net.Addr, error) {
228231
}, nil
229232
}
230233

231-
// SendBindingRequest sends a new STUN request to the STUN server
234+
// SendBindingRequest sends a new STUN request to the STUN server.
232235
func (c *Client) SendBindingRequest() (net.Addr, error) {
233236
if c.stunServerAddr == nil {
234237
return nil, errSTUNServerAddressNotSet
235238
}
239+
236240
return c.SendBindingRequestTo(c.stunServerAddr)
237241
}
238242

239-
func (c *Client) sendAllocateRequest(protocol proto.Protocol) (proto.RelayedAddress, proto.Lifetime, stun.Nonce, error) {
243+
func (c *Client) sendAllocateRequest(protocol proto.Protocol) ( // nolint:cyclop,funlen
244+
proto.RelayedAddress,
245+
proto.Lifetime,
246+
stun.Nonce,
247+
error,
248+
) {
240249
var relayed proto.RelayedAddress
241250
var lifetime proto.Lifetime
242251
var nonce stun.Nonce
@@ -295,6 +304,7 @@ func (c *Client) sendAllocateRequest(protocol proto.Protocol) (proto.RelayedAddr
295304
if err = code.GetFrom(res); err == nil {
296305
return relayed, lifetime, nonce, fmt.Errorf("%s (error %s)", res.Type, code) //nolint:goerr113
297306
}
307+
298308
return relayed, lifetime, nonce, fmt.Errorf("%s", res.Type) //nolint:goerr113
299309
}
300310

@@ -307,10 +317,11 @@ func (c *Client) sendAllocateRequest(protocol proto.Protocol) (proto.RelayedAddr
307317
if err := lifetime.GetFrom(res); err != nil {
308318
return relayed, lifetime, nonce, err
309319
}
320+
310321
return relayed, lifetime, nonce, nil
311322
}
312323

313-
// Allocate sends a TURN allocation request to the given transport address
324+
// Allocate sends a TURN allocation request to the given transport address.
314325
func (c *Client) Allocate() (net.PacketConn, error) {
315326
if err := c.allocTryLock.Lock(); err != nil {
316327
return nil, fmt.Errorf("%w: %s", errOneAllocateOnly, err.Error())
@@ -403,10 +414,11 @@ func (c *Client) CreatePermission(addrs ...net.Addr) error {
403414
return err
404415
}
405416
}
417+
406418
return nil
407419
}
408420

409-
// PerformTransaction performs STUN transaction
421+
// PerformTransaction performs STUN transaction.
410422
func (c *Client) PerformTransaction(msg *stun.Message, to net.Addr, ignoreResult bool) (client.TransactionResult,
411423
error,
412424
) {
@@ -442,11 +454,12 @@ func (c *Client) PerformTransaction(msg *stun.Message, to net.Addr, ignoreResult
442454
if res.Err != nil {
443455
return res, res.Err
444456
}
457+
445458
return res, nil
446459
}
447460

448461
// OnDeallocated is called when de-allocation of relay address has been complete.
449-
// (Called by UDPConn)
462+
// (Called by UDPConn).
450463
func (c *Client) OnDeallocated(net.Addr) {
451464
c.setRelayedUDPConn(nil)
452465
c.setTCPAllocation(nil)
@@ -494,7 +507,7 @@ func (c *Client) HandleInbound(data []byte, from net.Addr) (bool, error) {
494507
return false, nil
495508
}
496509

497-
func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error {
510+
func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error { // nolint:cyclop,funlen
498511
raw := make([]byte, len(data))
499512
copy(raw, data)
500513

@@ -507,7 +520,7 @@ func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error {
507520
return fmt.Errorf("%w : %s", errUnexpectedSTUNRequestMessage, msg.String())
508521
}
509522

510-
if msg.Type.Class == stun.ClassIndication {
523+
if msg.Type.Class == stun.ClassIndication { // nolint:nestif
511524
switch msg.Type.Method {
512525
case stun.MethodData:
513526
var peerAddr proto.PeerAddress
@@ -529,6 +542,7 @@ func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error {
529542
relayedConn := c.relayedUDPConn()
530543
if relayedConn == nil {
531544
c.log.Debug("No relayed conn allocated")
545+
532546
return nil // Silently discard
533547
}
534548
relayedConn.HandleInbound(data, from)
@@ -553,13 +567,15 @@ func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error {
553567
allocation := c.getTCPAllocation()
554568
if allocation == nil {
555569
c.log.Debug("No TCP allocation exists")
570+
556571
return nil // Silently discard
557572
}
558573

559574
allocation.HandleConnectionAttempt(addr, cid)
560575
default:
561576
c.log.Debug("Received unsupported STUN method")
562577
}
578+
563579
return nil
564580
}
565581

@@ -576,6 +592,7 @@ func (c *Client) handleSTUNMessage(data []byte, from net.Addr) error {
576592
c.mutexTrMap.Unlock()
577593
// Silently discard
578594
c.log.Debugf("No transaction for %s", msg)
595+
579596
return nil
580597
}
581598

@@ -607,6 +624,7 @@ func (c *Client) handleChannelData(data []byte) error {
607624
relayedConn := c.relayedUDPConn()
608625
if relayedConn == nil {
609626
c.log.Debug("No relayed conn allocated")
627+
610628
return nil // Silently discard
611629
}
612630

@@ -618,6 +636,7 @@ func (c *Client) handleChannelData(data []byte) error {
618636
c.log.Tracef("Channel data received from %s (ch=%d)", addr.String(), int(chData.Number))
619637

620638
relayedConn.HandleInbound(chData.Data, addr)
639+
621640
return nil
622641
}
623642

@@ -638,6 +657,7 @@ func (c *Client) onRtxTimeout(trKey string, nRtx int) {
638657
}) {
639658
c.log.Debug("No listener for transaction")
640659
}
660+
641661
return
642662
}
643663

@@ -651,6 +671,7 @@ func (c *Client) onRtxTimeout(trKey string, nRtx int) {
651671
}) {
652672
c.log.Debug("No listener for transaction")
653673
}
674+
654675
return
655676
}
656677
tr.StartRtxTimer(c.onRtxTimeout)

0 commit comments

Comments
 (0)