From 157148dd257d7ed2f049000cd5e0b40475206f89 Mon Sep 17 00:00:00 2001 From: Daniel Adam Date: Tue, 2 Apr 2024 11:41:27 +0200 Subject: [PATCH 1/2] Upgrade dependencies Direct: github.com/pion/dtls/v2 v2.2.8-0.20240327211025-8244c4570c01 github.com/pion/transport/v3 v3.0.2 golang.org/x/exp v0.0.0-20240325151524-a685a6edb6d8 golang.org/x/net v0.22.0 Indirect: golang.org/x/crypto v0.21.0 golang.org/x/sys v0.18.0 --- go.mod | 14 +++++++------- go.sum | 35 ++++++++++++++++------------------- mux/router.go | 2 +- mux/router_test.go | 2 +- pkg/sync/map.go | 2 +- 5 files changed, 26 insertions(+), 29 deletions(-) diff --git a/go.mod b/go.mod index 4b358328..b62a51f1 100644 --- a/go.mod +++ b/go.mod @@ -5,12 +5,12 @@ go 1.20 require ( github.com/dsnet/golib/memfile v1.0.0 github.com/hashicorp/go-multierror v1.1.1 - github.com/pion/dtls/v2 v2.2.8-0.20240201071732-2597464081c8 - github.com/pion/transport/v3 v3.0.1 + github.com/pion/dtls/v2 v2.2.8-0.20240327211025-8244c4570c01 + github.com/pion/transport/v3 v3.0.2 github.com/stretchr/testify v1.9.0 go.uber.org/atomic v1.11.0 - golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 - golang.org/x/net v0.21.0 + golang.org/x/exp v0.0.0-20240325151524-a685a6edb6d8 + golang.org/x/net v0.22.0 golang.org/x/sync v0.6.0 ) @@ -19,11 +19,11 @@ require ( github.com/hashicorp/errwrap v1.1.0 // indirect github.com/pion/logging v0.2.2 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect - golang.org/x/crypto v0.20.0 // indirect - golang.org/x/sys v0.17.0 // indirect + golang.org/x/crypto v0.21.0 // indirect + golang.org/x/sys v0.18.0 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect ) // note: github.com/pion/dtls/v2/pkg/net package is not yet available in release branches, // so we force to the use of the pinned master branch -replace github.com/pion/dtls/v2 => github.com/pion/dtls/v2 v2.2.8-0.20240201071732-2597464081c8 +replace github.com/pion/dtls/v2 => github.com/pion/dtls/v2 v2.2.8-0.20240327211025-8244c4570c01 diff --git a/go.sum b/go.sum index 473de4f6..8f2f329c 100644 --- a/go.sum +++ b/go.sum @@ -8,17 +8,18 @@ github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= -github.com/pion/dtls/v2 v2.2.8-0.20240201071732-2597464081c8 h1:r7K+oQUYubeA0am08kTAvd2wT2D8PZggs/CpMGp0nkM= -github.com/pion/dtls/v2 v2.2.8-0.20240201071732-2597464081c8/go.mod h1:/gft3czh67pwl4nM1BBUvF7eTy72uGkObJXOYfxRDbA= +github.com/pion/dtls/v2 v2.2.8-0.20240327211025-8244c4570c01 h1:Yiqcf3WfIu66j820RdYDjnnTsrDwMKYsuqFvzDJn4uk= +github.com/pion/dtls/v2 v2.2.8-0.20240327211025-8244c4570c01/go.mod h1:eLnUKAwQ5J17w2P583p4UXWBlOK5OkkLY7sXZANcwj0= github.com/pion/logging v0.2.2 h1:M9+AIj/+pxNsDfAT64+MAVgJO0rsyLnoJKCqf//DoeY= github.com/pion/logging v0.2.2/go.mod h1:k0/tDVsRCX2Mb2ZEmTqNa7CWsQPc+YYCB7Q+5pahoms= -github.com/pion/transport/v3 v3.0.1 h1:gDTlPJwROfSfz6QfSi0ZmeCSkFcnWWiiR9ES0ouANiM= -github.com/pion/transport/v3 v3.0.1/go.mod h1:UY7kiITrlMv7/IKgd5eTUcaahZx5oUN3l9SzK5f5xE0= +github.com/pion/transport/v3 v3.0.2 h1:r+40RJR25S9w3jbA6/5uEPTzcdn7ncyU44RWCbHkLg4= +github.com/pion/transport/v3 v3.0.2/go.mod h1:nIToODoOlb5If2jF9y2Igfx3PFYWfuXi37m0IlWa/D0= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= @@ -29,12 +30,11 @@ go.uber.org/atomic v1.11.0 h1:ZvwS0R+56ePWxUNi+Atn9dWONBPp/AUETXlHW0DxSjE= go.uber.org/atomic v1.11.0/go.mod h1:LUxbIzbOniOlMKjJjyPfpl4v+PKK2cNJn91OQbhoJI0= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.12.0/go.mod h1:NF0Gs7EO5K4qLn+Ylc+fih8BSTeIjAP05siRnAh98yw= -golang.org/x/crypto v0.18.0/go.mod h1:R0j02AL6hcrfOiy9T4ZYp/rcWeMxM3L6QYxlOuEG1mg= -golang.org/x/crypto v0.20.0 h1:jmAMJJZXr5KiCw05dfYK9QnqaqKLYXijU23lsEdcQqg= -golang.org/x/crypto v0.20.0/go.mod h1:Xwo95rrVNIoSMx9wa1JroENMToLWn3RNVrTBpLHgZPQ= -golang.org/x/exp v0.0.0-20240222234643-814bf88cf225 h1:LfspQV/FYTatPTr/3HzIcmiUFH7PGP+OQ6mgDYo3yuQ= -golang.org/x/exp v0.0.0-20240222234643-814bf88cf225/go.mod h1:CxmFvTBINI24O/j8iY7H1xHzx2i4OsyguNBmN/uPtqc= +golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU= +golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA= +golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs= +golang.org/x/exp v0.0.0-20240325151524-a685a6edb6d8 h1:aAcj0Da7eBAtrTp03QXWvm88pSyOt+UgdZw2BFZ+lEw= +golang.org/x/exp v0.0.0-20240325151524-a685a6edb6d8/go.mod h1:CQ1k9gNrJ50XIzaKCRR2hssIjF07kZFEiieALBM/ARQ= golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= @@ -42,10 +42,9 @@ golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= -golang.org/x/net v0.14.0/go.mod h1:PpSgVXXLK0OxS0F31C1/tv6XNguvCrnXIDrFMspZIUI= -golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= -golang.org/x/net v0.21.0 h1:AQyQV4dYCvJ7vGmJyKki9+PBdyvhkSd8EIx/qb0AYv4= golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44= +golang.org/x/net v0.22.0 h1:9sGLhx7iRIHEiX0oAJ3MRZMUCElJgy7Br1nO+AMN3Tc= +golang.org/x/net v0.22.0/go.mod h1:JKghWKKOSdJwpW2GEx0Ja7fmaKnMsbu+MWVZTokSYmg= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -58,22 +57,20 @@ golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.11.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= -golang.org/x/sys v0.17.0 h1:25cE3gD+tdBA7lp7QfhuV+rJiE9YXTcS3VG1SqssI/Y= golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/sys v0.18.0 h1:DBdB3niSjOA/O0blCZBqDefyWNYveAYMNF1Wum0DYQ4= +golang.org/x/sys v0.18.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= -golang.org/x/term v0.11.0/go.mod h1:zC9APTIj3jG3FdV/Ons+XE1riIZXG4aZ4GTHiPZJPIU= -golang.org/x/term v0.16.0/go.mod h1:yn7UURbUtPyrVJPGPq404EukNFxcm/foM+bV/bfcDsY= +golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk= +golang.org/x/term v0.18.0/go.mod h1:ILwASektA3OnRv7amZ1xhE/KTR+u50pbXfZ03+6Nx58= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= -golang.org/x/text v0.12.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= diff --git a/mux/router.go b/mux/router.go index 6e3933ef..5a597ce8 100644 --- a/mux/router.go +++ b/mux/router.go @@ -9,7 +9,7 @@ import ( "github.com/plgd-dev/go-coap/v3/message" "github.com/plgd-dev/go-coap/v3/message/codes" "github.com/plgd-dev/go-coap/v3/message/pool" - "golang.org/x/exp/maps" // TODO: switch to non-exp maps package when dependency hits 1.20 + "golang.org/x/exp/maps" // TODO: replace with standard maps package as soon as Go dependency hits 1.21 ) type ResponseWriter = interface { diff --git a/mux/router_test.go b/mux/router_test.go index 6ecec353..b2966143 100644 --- a/mux/router_test.go +++ b/mux/router_test.go @@ -5,7 +5,7 @@ import ( "github.com/plgd-dev/go-coap/v3/mux" "github.com/stretchr/testify/require" - "golang.org/x/exp/maps" // TODO: replace with standard maps package as soon as Go dependency hits 1.20 + "golang.org/x/exp/maps" // TODO: replace with standard maps package as soon as Go dependency hits 1.21 ) type routeTest struct { diff --git a/pkg/sync/map.go b/pkg/sync/map.go index 321aefb3..113e8753 100644 --- a/pkg/sync/map.go +++ b/pkg/sync/map.go @@ -3,7 +3,7 @@ package sync import ( "sync" - "golang.org/x/exp/maps" + "golang.org/x/exp/maps" // TODO: replace with standard maps package as soon as Go dependency hits 1.21 ) // Map is like a Go map[interface{}]interface{} but is safe for concurrent use by multiple goroutines. From 5f647977f48d9daafbd59c722c52f7a8fd101477 Mon Sep 17 00:00:00 2001 From: Daniel Adam Date: Tue, 2 Apr 2024 11:41:47 +0200 Subject: [PATCH 2/2] Update golangci-lint configuration and fix issues --- .golangci.yml | 69 ++++++++++++++----- dtls/client_test.go | 2 +- dtls/server/server.go | 4 +- dtls/server/session.go | 4 +- message/codes/code_string.go | 4 +- message/codes/codes.go | 3 +- message/codes/codes_test.go | 2 +- message/option.go | 5 +- message/options_test.go | 4 +- message/pool/message_test.go | 4 +- message/status/status_test.go | 5 +- net/blockwise/blockwise.go | 18 +++-- net/blockwise/blockwise_test.go | 17 +++-- .../limitParallelRequests_test.go | 6 +- net/connUDP.go | 13 ++-- net/connUDP_internal_test.go | 10 +-- net/conn_test.go | 16 ++--- net/dtlslistener.go | 2 +- net/observation/handler.go | 7 +- net/tlslistener_test.go | 28 ++++---- pkg/cache/cache_test.go | 4 +- server.go | 3 +- tcp/client/conn.go | 2 +- tcp/client/session.go | 4 +- tcp/client_test.go | 2 +- tcp/coder/bench_test.go | 3 +- tcp/coder/coder_test.go | 2 +- tcp/server/server.go | 4 +- udp/client/conn.go | 4 +- udp/client/conn_test.go | 5 +- udp/client_test.go | 27 ++++---- udp/coder/bench_test.go | 2 +- udp/coder/coder_test.go | 2 +- udp/server/discover.go | 9 +-- udp/server/server.go | 7 +- udp/server/session.go | 4 +- udp/server_test.go | 2 +- 37 files changed, 170 insertions(+), 139 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 48c1b51f..aaf335db 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -2,19 +2,24 @@ linters-settings: gocyclo: min-complexity: 15 govet: - check-shadowing: true + enable: + - nilness + - shadow gomoddirectives: replace-allow-list: - github.com/pion/dtls/v2 + testifylint: + disable: + - go-require linters: enable: + - asasalint # Check for pass []any as any in variadic func(...any) - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers - bidichk # Checks for dangerous unicode character sequences - # - bodyclose # checks whether HTTP response body is closed successfully - # - contextcheck # check the function whether use a non-inherited context + - bodyclose # Checks whether HTTP response body is closed successfully + # - copyloopvar # Detects places where loop variables are copied - decorder # check declaration order and count of types, constants, variables and functions - # - depguard # Go linter that checks if package imports are in a list of acceptable packages - dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) - dupl # Tool for code clone detection - durationcheck # check for two durations multiplied together @@ -22,18 +27,16 @@ linters: - 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. - errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. - # - exhaustive # check exhaustiveness of enum switch statements + - execinquery # Execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds. - exportloopref # checks for pointers to enclosing loop variables - # - forbidigo # Forbids identifiers - forcetypeassert # finds forced type assertions - gci # Gci control golang package import order and make it always deterministic. - # - gochecknoglobals # Checks that no globals are present in Go code - # - gochecknoinits # Checks that no init functions are present in Go code + - gocheckcompilerdirectives # Checks that go compiler directive comments (//go:) are valid. - gocognit # Computes and checks the cognitive complexity of functions - goconst # Finds repeated strings that could be replaced by a constant - gocritic # The most opinionated Go source code linter - gocyclo # Computes and checks the cyclomatic complexity of functions - # - godox # Tool for detection of FIXME, TODO and other comment keywords + - godox # Tool for detection of FIXME, TODO and other comment keywords # - goerr113 # Golang linter to check the errors handling expressions - gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification - gofumpt # Gofumpt checks whether code was gofumpt-ed. @@ -43,50 +46,73 @@ linters: - 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. - goprintffuncname # Checks that printf-like functions are named with `f` at the end - gosec # Inspects source code for security problems + - gosmopolitan # Report certain i18n/l10n anti-patterns in your Go codebase - gosimple # Linter for Go source code that specializes in simplifying a code - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - grouper # An analyzer to analyze expression groups. + - grouper # An analyzer to analyze expression groups - importas # Enforces consistent import aliases - ineffassign # Detects when assignments to existing variables are not used + # - intrange # Intrange is a linter to find places where for loops could make use of an integer range + - loggercheck # Checks key value pairs for common logger libraries (kitlog,klog,logr,zap). + - mirror # Reports wrong mirror patterns of bytes/strings usage - misspell # Finds commonly misspelled English words in comments - # - nakedret # Finds naked returns in functions greater than a specified function length - nilerr # Finds the code that returns nil even if it checks that the error is not nil. - nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value. - # - noctx # noctx finds sending http request without context.Context + - noctx # noctx finds sending http request without context.Context - nolintlint # Reports ill-formed or insufficient nolint directives - # - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test + - nosprintfhostport # Checks for misuse of Sprintf to construct a host with port in a URL + - perfsprint # Checks that fmt.Sprintf can be replaced with a faster alternative. - predeclared # find code that shadows one of Go's predeclared identifiers + - protogetter # Reports direct reads from proto message fields when getters should be used. - revive # golint replacement, finds style mistakes + - reassign # Checks that package variables are not reassigned + - sloglint # Ensure consistent code style when using log/slog + - spancheck # Checks for mistakes with OpenTelemetry/Census spans - staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks - stylecheck # Stylecheck is a replacement for golint - # - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 - # - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes + - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 + - testifylint # Checks usage of github.com/stretchr/testify. + - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - unconvert # Remove unnecessary type conversions - unparam # Reports unused function parameters - unused # Checks Go code for unused constants, variables, functions and types - # - wastedassign # wastedassign finds wasted assignment statements + - usestdlibvars # A linter that detect the possibility to use variables/constants from the Go standard library. + - wastedassign # wastedassign finds wasted assignment statements - whitespace # Tool for detection of leading and trailing whitespace disable: - containedctx # containedctx is a linter that detects struct contained context.Context field + - contextcheck # check the function whether use a non-inherited context - cyclop # checks function and package cyclomatic complexity + - depguard # Go linter that checks if package imports are in a list of acceptable packages + - exhaustive # Check exhaustiveness of enum switch statements - exhaustivestruct # Checks if all struct's fields are initialized + - exhaustruct # Checks if all structure fields are initialized. + - forbidigo # Forbids identifiers - funlen # Tool for detection of long functions + - gochecknoglobals # Checks that no globals are present in Go code + - gochecknoinits # Checks that no init functions are present in Go code - godot # Check if comments end in a period - gomnd # An analyzer to detect magic numbers. - ifshort # Checks that your code uses short syntax for if-statements whenever possible + - inamedparam # Reports interfaces with unnamed method parameters. + - interfacebloat # A linter that checks the number of methods inside an interface - ireturn # Accept Interfaces, Return Concrete Types - lll # Reports long lines - maintidx # maintidx measures the maintainability index of each function. - makezero # Finds slice declarations with non-zero initial length - maligned # Tool to detect Go structs that would take less memory if their fields were sorted + - nakedret # Finds naked returns in functions greater than a specified function length - nestif # Reports deeply nested if statements - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity + - nonamedreturns # Reports all named returns + - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test - prealloc # Finds slice declarations that could potentially be preallocated - promlinter # Check Prometheus metrics naming via promlint - rowserrcheck # checks whether Err of rows is checked successfully - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. - structcheck # Finds unused struct fields + - tagalign # Check that struct tags are well aligned. - tagliatelle # Checks the struct tags. - testpackage # linter that makes you use a separate _test package - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers @@ -105,6 +131,7 @@ issues: - gosec - gocyclo - gocognit + - perfsprint - path: ^test/.*\.go linters: @@ -113,6 +140,7 @@ issues: - gosec - gocyclo - gocognit + - perfsprint - path: example_test\.go text: "exitAfterDefer" @@ -124,5 +152,14 @@ issues: linters: - gosec + - path: .*/client/conn.go + linters: + - godox + + - path: .*.go + text: "replace with standard maps package" + linters: + - godox + # # Fix found issues (if it's supported by the linter). # fix: true diff --git a/dtls/client_test.go b/dtls/client_test.go index ceabee0a..968c2bb5 100644 --- a/dtls/client_test.go +++ b/dtls/client_test.go @@ -208,7 +208,7 @@ func TestConnGetSeparateMessage(t *testing.T) { }() cc, err := dtls.Dial(l.Addr().String(), dtlsCfg, options.WithHandlerFunc(func(_ *responsewriter.ResponseWriter[*client.Conn], r *pool.Message) { - assert.NoError(t, fmt.Errorf("none msg expected comes: %+v", r)) + require.Failf(t, "Unexpected msg", "Received unexpected message: %+v", r) })) require.NoError(t, err) defer func() { diff --git a/dtls/server/server.go b/dtls/server/server.go index c1cb9969..1f879a67 100644 --- a/dtls/server/server.go +++ b/dtls/server/server.go @@ -89,7 +89,7 @@ func (s *Server) checkAndSetListener(l Listener) error { s.listenMutex.Lock() defer s.listenMutex.Unlock() if s.listen != nil { - return fmt.Errorf("server already serve listener") + return errors.New("server already serve listener") } s.listen = l return nil @@ -127,7 +127,7 @@ func (s *Server) serveConnection(connections *connections.Connections, cc *udpCl func (s *Server) Serve(l Listener) error { if s.cfg.BlockwiseSZX > blockwise.SZX1024 { - return fmt.Errorf("invalid blockwiseSZX") + return errors.New("invalid blockwiseSZX") } err := s.checkAndSetListener(l) if err != nil { diff --git a/dtls/server/session.go b/dtls/server/session.go index 5f0d9154..f1584aa0 100644 --- a/dtls/server/session.go +++ b/dtls/server/session.go @@ -19,7 +19,7 @@ type EventFunc = func() type Session struct { onClose []EventFunc - ctx atomic.Value // TODO: change to atomic.Pointer[context.Context] for go1.19 + ctx atomic.Pointer[context.Context] cancel context.CancelFunc connection *coapNet.Conn @@ -90,7 +90,7 @@ func (s *Session) Close() error { } func (s *Session) Context() context.Context { - return *s.ctx.Load().(*context.Context) //nolint:forcetypeassert + return *s.ctx.Load() } // SetContextValue stores the value associated with key to context of connection. diff --git a/message/codes/code_string.go b/message/codes/code_string.go index 79f248a7..10f8dbc8 100644 --- a/message/codes/code_string.go +++ b/message/codes/code_string.go @@ -1,7 +1,7 @@ package codes import ( - "fmt" + "errors" "strconv" ) @@ -54,5 +54,5 @@ func ToCode(v string) (Code, error) { return key, nil } } - return 0, fmt.Errorf("not found") + return 0, errors.New("not found") } diff --git a/message/codes/codes.go b/message/codes/codes.go index 5cda66de..fd3568bc 100644 --- a/message/codes/codes.go +++ b/message/codes/codes.go @@ -1,6 +1,7 @@ package codes import ( + "errors" "fmt" "strconv" ) @@ -116,7 +117,7 @@ func (c *Code) UnmarshalJSON(b []byte) error { return nil } if c == nil { - return fmt.Errorf("nil receiver passed to UnmarshalJSON") + return errors.New("nil receiver passed to UnmarshalJSON") } if len(b) > _maxCodeLen { diff --git a/message/codes/codes_test.go b/message/codes/codes_test.go index 3d0b3f5a..5a9c9142 100644 --- a/message/codes/codes_test.go +++ b/message/codes/codes_test.go @@ -52,7 +52,7 @@ func TestUnmarshalJSONUnknownInput(t *testing.T) { var got Code longStr := "This is a very long string that is longer than the max code length" - require.True(t, len(longStr) > getMaxCodeLen()) + require.Greater(t, len(longStr), getMaxCodeLen()) err := got.UnmarshalJSON([]byte(longStr)) require.Error(t, err) } diff --git a/message/option.go b/message/option.go index 5d4713be..d8b8dba8 100644 --- a/message/option.go +++ b/message/option.go @@ -3,7 +3,6 @@ package message import ( "encoding/binary" "errors" - "fmt" "strconv" ) @@ -113,7 +112,7 @@ func ToOptionID(v string) (OptionID, error) { return key, nil } } - return 0, fmt.Errorf("not found") + return 0, errors.New("not found") } // Option value format (RFC7252 section 3.2) @@ -234,7 +233,7 @@ func ToMediaType(v string) (MediaType, error) { return key, nil } } - return 0, fmt.Errorf("not found") + return 0, errors.New("not found") } func extendOpt(opt int) (int, int) { diff --git a/message/options_test.go b/message/options_test.go index 98545024..21e1eb29 100644 --- a/message/options_test.go +++ b/message/options_test.go @@ -264,7 +264,7 @@ func TestSetBytesOption(t *testing.T) { v := make([]string, 2) n, err := options.GetStrings(1, v) - require.Equal(t, nil, err) + require.NoError(t, err) require.Equal(t, 1, n) require.Equal(t, []string{"11"}, v[:n]) @@ -288,7 +288,7 @@ func TestAddBytesOption(t *testing.T) { options = testAddBytesOption(t, options, Option{ID: 1, Value: []byte("4")}, 2) v := make([][]byte, 2) n, err := options.GetBytess(0, v) - require.Equal(t, nil, err) + require.NoError(t, err) require.Equal(t, 2, n) require.Equal(t, [][]byte{{0x30}, {0x31}}, v) } diff --git a/message/pool/message_test.go b/message/pool/message_test.go index 3f07aeed..dd5cf6d0 100644 --- a/message/pool/message_test.go +++ b/message/pool/message_test.go @@ -355,7 +355,7 @@ func TestMessageClone(t *testing.T) { original.SetBody(malFuncSeeker{}) err = original.Clone(cloned) require.Error(t, err) - require.Equal(t, err.Error(), "seek error") + require.Equal(t, "seek error", err.Error()) original.SetBody(malFuncReader{}) err = original.Clone(cloned) @@ -386,7 +386,7 @@ func TestUnmarshalMessageWithMultipleOptions(t *testing.T) { msg := pool.NewMessage(context.Background()) n, err := msg.UnmarshalWithDecoder(coder.DefaultCoder, data) require.NoError(t, err) - require.Equal(t, n, len(data)) + require.Len(t, data, n) require.Equal(t, req.Options(), msg.Options()) }) } diff --git a/message/status/status_test.go b/message/status/status_test.go index d2cf02f7..6a744830 100644 --- a/message/status/status_test.go +++ b/message/status/status_test.go @@ -2,7 +2,6 @@ package status import ( "context" - "errors" "fmt" "testing" @@ -25,7 +24,7 @@ func TestStatus(t *testing.T) { s, ok = FromError(err) require.True(t, ok) require.Equal(t, codes.NotFound, s.Code()) - require.True(t, errors.Is(err, context.Canceled)) + require.ErrorIs(t, err, context.Canceled) s = Convert(err) require.Equal(t, codes.NotFound, s.Code()) @@ -34,7 +33,7 @@ func TestStatus(t *testing.T) { require.Equal(t, OK, Code(nil)) err = FromContextError(context.Canceled) - require.True(t, errors.Is(err, context.Canceled)) + require.ErrorIs(t, err, context.Canceled) require.Equal(t, Canceled, Code(err)) err = FromContextError(nil) diff --git a/net/blockwise/blockwise.go b/net/blockwise/blockwise.go index 980aa83e..0157d692 100644 --- a/net/blockwise/blockwise.go +++ b/net/blockwise/blockwise.go @@ -204,10 +204,10 @@ func payloadSizeError(err error) error { // Do sends an coap message and returns an coap response via blockwise transfer. func (b *BlockWise[C]) Do(r *pool.Message, maxSzx SZX, maxMessageSize uint32, do func(req *pool.Message) (*pool.Message, error)) (*pool.Message, error) { if maxSzx > SZXBERT { - return nil, fmt.Errorf("invalid szx") + return nil, errors.New("invalid szx") } if len(r.Token()) == 0 { - return nil, fmt.Errorf("invalid token") + return nil, errors.New("invalid token") } expire, ok := r.Context().Deadline() @@ -216,7 +216,7 @@ func (b *BlockWise[C]) Do(r *pool.Message, maxSzx SZX, maxMessageSize uint32, do } _, loaded := b.sendingMessagesCache.LoadOrStore(r.Token().Hash(), cache.NewElement(r, expire, nil)) if loaded { - return nil, fmt.Errorf("invalid token") + return nil, errors.New("invalid token") } defer b.sendingMessagesCache.Delete(r.Token().Hash()) if r.Body() == nil { @@ -583,7 +583,7 @@ func (b *BlockWise[C]) getSentRequest(token message.Token) *pool.Message { func (b *BlockWise[C]) handleObserveResponse(sentRequest *pool.Message) (message.Token, time.Time, error) { // https://tools.ietf.org/html/rfc7959#section-2.6 - performs GET with new token. if sentRequest == nil { - return nil, time.Time{}, fmt.Errorf("observation is not registered") + return nil, time.Time{}, errors.New("observation is not registered") } token, err := message.GetToken() if err != nil { @@ -594,7 +594,7 @@ func (b *BlockWise[C]) handleObserveResponse(sentRequest *pool.Message) (message bwSentRequest.SetToken(token) _, loaded := b.sendingMessagesCache.LoadOrStore(token.Hash(), cache.NewElement(bwSentRequest, validUntil, nil)) if loaded { - return nil, time.Time{}, fmt.Errorf("cannot process message: message with token already exist") + return nil, time.Time{}, errors.New("cannot process message: message with token already exist") } return token, validUntil, nil } @@ -648,7 +648,6 @@ func (b *BlockWise[C]) getPayloadFromCachedReceivedMessage(r, cachedReceivedMess } func copyToPayloadFromOffset(r *pool.Message, payloadFile *memfile.File, offset int64) (int64, error) { - payloadSize := int64(0) copyn, err := payloadFile.Seek(offset, io.SeekStart) if err != nil { return 0, fmt.Errorf("cannot seek to off(%v) of cached request: %w", offset, err) @@ -664,7 +663,7 @@ func copyToPayloadFromOffset(r *pool.Message, payloadFile *memfile.File, offset return 0, fmt.Errorf("cannot copy to cached request: %w", err) } } - payloadSize = copyn + written + payloadSize := copyn + written err = payloadFile.Truncate(payloadSize) if err != nil { return 0, fmt.Errorf("cannot truncate cached request: %w", err) @@ -717,7 +716,7 @@ func (b *BlockWise[C]) getCachedReceivedMessage(mg *messageGuard, r *pool.Messag mg = element.Data() if mg == nil { closeFn() - return nil, nil, fmt.Errorf("request was already stored in cache") + return nil, nil, errors.New("request was already stored in cache") } errA := mg.Acquire(mg.Context(), 1) if errA != nil { @@ -732,7 +731,6 @@ func (b *BlockWise[C]) getCachedReceivedMessage(mg *messageGuard, r *pool.Messag //nolint:gocyclo,gocognit func (b *BlockWise[C]) processReceivedMessage(w *responsewriter.ResponseWriter[C], r *pool.Message, maxSzx SZX, next func(w *responsewriter.ResponseWriter[C], r *pool.Message), blockType message.OptionID, sizeType message.OptionID) error { - // TODO: lower cyclomatic complexity token := r.Token() if len(token) == 0 { next(w, r) @@ -760,7 +758,7 @@ func (b *BlockWise[C]) processReceivedMessage(w *responsewriter.ResponseWriter[C } validUntil := b.getValidUntil(sentRequest) if blockType == message.Block2 && sentRequest == nil { - return fmt.Errorf("cannot request body without paired request") + return errors.New("cannot request body without paired request") } if isObserveResponse(r) { token, validUntil, err = b.handleObserveResponse(sentRequest) diff --git a/net/blockwise/blockwise_test.go b/net/blockwise/blockwise_test.go index 4b0eacbb..70d173ff 100644 --- a/net/blockwise/blockwise_test.go +++ b/net/blockwise/blockwise_test.go @@ -3,7 +3,6 @@ package blockwise import ( "bytes" "context" - "fmt" "io" "testing" "time" @@ -302,13 +301,13 @@ func TestBlockWiseDo(t *testing.T) { t.Run(tt.name, func(t *testing.T) { got, err := sender.Do(toPoolMessage(tt.args.r), tt.args.szx, uint32(tt.args.maxMessageSize), tt.args.do) if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) return } receivingMessagesCache := sender.receivingMessagesCache.LoadAndDeleteAll() - require.Len(t, receivingMessagesCache, 0) + require.Empty(t, receivingMessagesCache) sendingMessagesCache := sender.sendingMessagesCache.LoadAndDeleteAll() - require.Len(t, sendingMessagesCache, 0) + require.Empty(t, sendingMessagesCache) require.NoError(t, err) assert.Equal(t, tt.want, fromPoolMessage(got)) }) @@ -390,7 +389,7 @@ func TestBlockWiseParallel(t *testing.T) { } got, err := sender.Do(toPoolMessage(req), tt.args.szx, uint32(tt.args.maxMessageSize), tt.args.do) if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) return } require.NoError(t, err) @@ -435,7 +434,7 @@ func TestEncodeBlockOption(t *testing.T) { t.Run(tt.name, func(t *testing.T) { got, err := EncodeBlockOption(tt.args.szx, tt.args.blockNumber, tt.args.moreBlocksFollowing) if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) return } require.NoError(t, err) @@ -478,7 +477,7 @@ func TestDecodeBlockOption(t *testing.T) { t.Run(tt.name, func(t *testing.T) { gotSzx, gotBlockNumber, gotMoreBlocksFollowing, err := DecodeBlockOption(tt.args.blockVal) if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) return } require.NoError(t, err) @@ -553,7 +552,7 @@ func TestBlockWiseWriteTestMessage(t *testing.T) { szx: SZX16, maxMessageSize: SZX16.Size(), writetestmessage: makeWriteReq(sender, receiver, SZX16, uint32(SZX16.Size()), SZX16, uint32(SZX16.Size()), func(_ *responsewriter.ResponseWriter[*testClient], r *pool.Message) { - require.NoError(t, fmt.Errorf("not expected received message: %+v", r)) + require.Failf(t, "Unexpected msg", "Received unexpected message: %+v", r) }), }, }, @@ -609,7 +608,7 @@ func TestBlockWiseWriteTestMessage(t *testing.T) { t.Run(tt.name, func(t *testing.T) { err := sender.WriteMessage(toPoolMessage(tt.args.r), tt.args.szx, uint32(tt.args.maxMessageSize), tt.args.writetestmessage) if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) return } require.NoError(t, err) diff --git a/net/client/limitParallelRequests/limitParallelRequests_test.go b/net/client/limitParallelRequests/limitParallelRequests_test.go index 83a8400c..a33e2c21 100644 --- a/net/client/limitParallelRequests/limitParallelRequests_test.go +++ b/net/client/limitParallelRequests/limitParallelRequests_test.go @@ -2,7 +2,7 @@ package limitparallelrequests import ( "context" - "fmt" + "errors" "sync" "testing" "time" @@ -27,12 +27,12 @@ type mockClient struct { func (c *mockClient) do(*pool.Message) (*pool.Message, error) { c.num.Inc() - return nil, fmt.Errorf("not implemented") + return nil, errors.New("not implemented") } func (c *mockClient) doObserve(*pool.Message, func(req *pool.Message)) (Observation, error) { c.num.Inc() - return nil, fmt.Errorf("not implemented") + return nil, errors.New("not implemented") } func TestLimitParallelRequestsDo(t *testing.T) { diff --git a/net/connUDP.go b/net/connUDP.go index 0552aa91..9bda1ea8 100644 --- a/net/connUDP.go +++ b/net/connUDP.go @@ -2,6 +2,7 @@ package net import ( "context" + "errors" "fmt" "net" "strings" @@ -244,7 +245,7 @@ func NewListenUDP(network, addr string, opts ...UDPOption) (*UDPConn, error) { func newPacketConn(c *net.UDPConn) (packetConn, error) { laddr := c.LocalAddr() if laddr == nil { - return nil, fmt.Errorf("invalid UDP connection") + return nil, errors.New("invalid UDP connection") } addr, ok := laddr.(*net.UDPAddr) if !ok { @@ -255,14 +256,10 @@ func newPacketConn(c *net.UDPConn) (packetConn, error) { func newPacketConnWithAddr(addr *net.UDPAddr, c *net.UDPConn) (packetConn, error) { var pc packetConn - var err error if IsIPv6(addr.IP) { pc = newPacketConnIPv6(ipv6.NewPacketConn(c)) } else { pc = newPacketConnIPv4(ipv4.NewPacketConn(c)) - if err != nil { - return nil, fmt.Errorf("invalid UDPv4 connection: %w", err) - } } return pc, nil } @@ -398,7 +395,7 @@ func (c *UDPConn) WriteMulticast(ctx context.Context, raddr *net.UDPAddr, buffer func (c *UDPConn) writeMulticastWithInterface(raddr *net.UDPAddr, buffer []byte, opt MulticastOptions) error { if opt.Iface == nil && opt.IFaceMode == MulticastSpecificInterface { - return fmt.Errorf("invalid interface") + return errors.New("invalid interface") } if opt.Source != nil { return c.writeToAddr(opt.Iface, opt.Source, opt.HopLimit, raddr, buffer) @@ -472,7 +469,7 @@ func (c *UDPConn) validateMulticast(ctx context.Context, raddr *net.UDPAddr, opt default: } if raddr == nil { - return fmt.Errorf("cannot write multicast with context: invalid raddr") + return errors.New("cannot write multicast with context: invalid raddr") } if _, ok := c.packetConn.(*packetConnIPv4); ok && IsIPv6(raddr.IP) { return fmt.Errorf("cannot write multicast with context: invalid destination address(%v)", raddr.IP) @@ -611,7 +608,7 @@ func WithControlMessage(cm *ControlMessage) UDPWriteOption { // WriteWithContext writes data with context. func (c *UDPConn) writeWithCfg(buffer []byte, cfg UDPWriteCfg) error { if cfg.RemoteAddr == nil { - return fmt.Errorf("cannot write with context: invalid raddr") + return errors.New("cannot write with context: invalid raddr") } select { case <-cfg.Ctx.Done(): diff --git a/net/connUDP_internal_test.go b/net/connUDP_internal_test.go index 70fe61b9..0f122edd 100644 --- a/net/connUDP_internal_test.go +++ b/net/connUDP_internal_test.go @@ -90,9 +90,9 @@ func TestUDPConnWriteWithContext(t *testing.T) { c1.RemoteAddr() if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) } else { - assert.NoError(t, err) + require.NoError(t, err) } }) } @@ -208,7 +208,7 @@ func TestUDPConnwriteMulticastWithContext(t *testing.T) { go func() { b := make([]byte, 1024) n, _, errR := c2.ReadWithContext(ctx, b) - assert.NoError(t, errR) + require.NoError(t, errR) if n > 0 { b = b[:n] assert.Equal(t, payload, b) @@ -224,10 +224,10 @@ func TestUDPConnwriteMulticastWithContext(t *testing.T) { c1.RemoteAddr() if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) }) } } diff --git a/net/conn_test.go b/net/conn_test.go index 52e19516..16c16756 100644 --- a/net/conn_test.go +++ b/net/conn_test.go @@ -5,7 +5,7 @@ import ( "net" "testing" - "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestConnWriteWithContext(t *testing.T) { @@ -40,10 +40,10 @@ func TestConnWriteWithContext(t *testing.T) { } listener, err := NewTCPListener("tcp", "127.0.0.1:") - assert.NoError(t, err) + require.NoError(t, err) defer func() { err := listener.Close() - assert.NoError(t, err) + require.NoError(t, err) }() ctx, cancel := context.WithCancel(context.Background()) defer cancel() @@ -58,18 +58,18 @@ func TestConnWriteWithContext(t *testing.T) { b := make([]byte, len(helloWorld)) _ = c.ReadFullWithContext(ctx, b) err = c.Close() - assert.NoError(t, err) + require.NoError(t, err) } }() for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { tcpConn, err := net.Dial("tcp", listener.Addr().String()) - assert.NoError(t, err) + require.NoError(t, err) c := NewConn(tcpConn) defer func() { errC := c.Close() - assert.NoError(t, errC) + require.NoError(t, errC) }() c.LocalAddr() @@ -77,10 +77,10 @@ func TestConnWriteWithContext(t *testing.T) { err = c.WriteWithContext(tt.args.ctx, tt.args.data) if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) return } - assert.NoError(t, err) + require.NoError(t, err) }) } } diff --git a/net/dtlslistener.go b/net/dtlslistener.go index b797507f..4a7379b6 100644 --- a/net/dtlslistener.go +++ b/net/dtlslistener.go @@ -70,7 +70,7 @@ func NewDTLSListener(network string, addr string, dtlsCfg *dtls.Config, opts ... } if cfg.GoPool == nil { - return nil, fmt.Errorf("empty go pool") + return nil, errors.New("empty go pool") } l := DTLSListener{ diff --git a/net/observation/handler.go b/net/observation/handler.go index f170269f..0b539e90 100644 --- a/net/observation/handler.go +++ b/net/observation/handler.go @@ -2,6 +2,7 @@ package observation import ( "context" + "errors" "fmt" "sync" "time" @@ -10,7 +11,7 @@ import ( "github.com/plgd-dev/go-coap/v3/message/codes" "github.com/plgd-dev/go-coap/v3/message/pool" "github.com/plgd-dev/go-coap/v3/net/responsewriter" - "github.com/plgd-dev/go-coap/v3/pkg/errors" + pkgErrors "github.com/plgd-dev/go-coap/v3/pkg/errors" coapSync "github.com/plgd-dev/go-coap/v3/pkg/sync" "go.uber.org/atomic" ) @@ -57,7 +58,7 @@ func (h *Handler[C]) NewObservation(req *pool.Message, observeFunc func(req *poo } token := req.Token() if len(token) == 0 { - return nil, fmt.Errorf("empty token") + return nil, errors.New("empty token") } options, err := req.Options().Clone() if err != nil { @@ -75,7 +76,7 @@ func (h *Handler[C]) NewObservation(req *pool.Message, observeFunc func(req *poo } }(&err) if _, loaded := h.observations.LoadOrStore(token.Hash(), o); loaded { - err = errors.ErrKeyAlreadyExists + err = pkgErrors.ErrKeyAlreadyExists return nil, err } diff --git a/net/tlslistener_test.go b/net/tlslistener_test.go index cc05228c..56e356eb 100644 --- a/net/tlslistener_test.go +++ b/net/tlslistener_test.go @@ -75,10 +75,10 @@ func TestTLSListenerAcceptWithContext(t *testing.T) { } dir, err := os.MkdirTemp("", "gotesttmp") - assert.NoError(t, err) + require.NoError(t, err) defer func() { errR := os.RemoveAll(dir) - assert.NoError(t, errR) + require.NoError(t, errR) }() config := SetTLSConfig(t) @@ -86,7 +86,7 @@ func TestTLSListenerAcceptWithContext(t *testing.T) { require.NoError(t, err) defer func() { err := listener.Close() - assert.NoError(t, err) + require.NoError(t, err) }() var wg sync.WaitGroup @@ -109,10 +109,10 @@ func TestTLSListenerAcceptWithContext(t *testing.T) { continue } _, err = c.Write([]byte("hello")) - assert.NoError(t, err) + require.NoError(t, err) time.Sleep(time.Millisecond * 200) err = c.Close() - assert.NoError(t, err) + require.NoError(t, err) } }() @@ -120,14 +120,14 @@ func TestTLSListenerAcceptWithContext(t *testing.T) { t.Run(tt.name, func(t *testing.T) { con, err := listener.AcceptWithContext(tt.args.ctx) if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) } else { require.NoError(t, err) b := make([]byte, 1024) _, err = con.Read(b) - assert.NoError(t, err) + require.NoError(t, err) err = con.Close() - assert.NoError(t, err) + require.NoError(t, err) } }) } @@ -161,10 +161,10 @@ func TestTLSListenerCheckForInfinitLoop(t *testing.T) { } dir, err := os.MkdirTemp("", "gotesttmp") - assert.NoError(t, err) + require.NoError(t, err) defer func() { errR := os.RemoveAll(dir) - assert.NoError(t, errR) + require.NoError(t, errR) }() config := SetTLSConfig(t) @@ -172,7 +172,7 @@ func TestTLSListenerCheckForInfinitLoop(t *testing.T) { require.NoError(t, err) defer func() { err := listener.Close() - assert.NoError(t, err) + require.NoError(t, err) }() var wg sync.WaitGroup @@ -210,17 +210,17 @@ func TestTLSListenerCheckForInfinitLoop(t *testing.T) { t.Run(tt.name, func(t *testing.T) { con, err := listener.AcceptWithContext(tt.args.ctx) if tt.wantErr { - assert.Error(t, err) + require.Error(t, err) return } require.NoError(t, err) b := make([]byte, 1024) c := NewConn(con) _, err = c.ReadWithContext(context.Background(), b) - assert.Error(t, err) + require.Error(t, err) assert.Contains(t, err.Error(), "EOF") err = con.Close() - assert.Error(t, err) + require.Error(t, err) }) } } diff --git a/pkg/cache/cache_test.go b/pkg/cache/cache_test.go index 76f7f46e..48921a53 100644 --- a/pkg/cache/cache_test.go +++ b/pkg/cache/cache_test.go @@ -118,7 +118,7 @@ func TestRangeFunction(t *testing.T) { return true }) - require.Equal(t, foundElements, 2) + require.Equal(t, 2, foundElements) for k := range actualMap { _, contains := actualMap[k] @@ -145,5 +145,5 @@ func TestPullOutAllFunction(t *testing.T) { foundElements++ return true }) - require.Equal(t, foundElements, 0) + require.Equal(t, 0, foundElements) } diff --git a/server.go b/server.go index 859a6292..bec94646 100644 --- a/server.go +++ b/server.go @@ -3,6 +3,7 @@ package coap import ( "crypto/tls" + "errors" "fmt" piondtls "github.com/pion/dtls/v2" @@ -99,7 +100,7 @@ func ListenAndServeWithOptions(network, addr string, opts ...any) (err error) { case udpServer.Option: udpOptions = append(udpOptions, o) default: - return fmt.Errorf("only support tcpServer.Option and udpServer.Option") + return errors.New("only support tcpServer.Option and udpServer.Option") } } diff --git a/tcp/client/conn.go b/tcp/client/conn.go index 13fc7f56..018ead4d 100644 --- a/tcp/client/conn.go +++ b/tcp/client/conn.go @@ -166,7 +166,7 @@ func (cc *Conn) Close() error { func (cc *Conn) doInternal(req *pool.Message) (*pool.Message, error) { token := req.Token() if token == nil { - return nil, fmt.Errorf("invalid token") + return nil, errors.New("invalid token") } respChan := make(chan *pool.Message, 1) if _, loaded := cc.tokenHandlerContainer.LoadOrStore(token.Hash(), func(_ *responsewriter.ResponseWriter[*Conn], r *pool.Message) { diff --git a/tcp/client/session.go b/tcp/client/session.go index ecf58415..66c3d2c9 100644 --- a/tcp/client/session.go +++ b/tcp/client/session.go @@ -30,7 +30,7 @@ type Session struct { errors ErrorFunc connection *coapNet.Conn messagePool *pool.Pool - ctx atomic.Value // TODO: change to atomic.Pointer[context.Context] for go1.19 + ctx atomic.Pointer[context.Context] maxMessageSize uint32 private struct { mutex sync.Mutex @@ -138,7 +138,7 @@ func (s *Session) Sequence() uint64 { } func (s *Session) Context() context.Context { - return *s.ctx.Load().(*context.Context) //nolint:forcetypeassert + return *s.ctx.Load() } func seekBufferToNextMessage(buffer *bytes.Buffer, msgSize int) *bytes.Buffer { diff --git a/tcp/client_test.go b/tcp/client_test.go index 752362be..5a02cea7 100644 --- a/tcp/client_test.go +++ b/tcp/client_test.go @@ -837,5 +837,5 @@ func TestConnRequestMonitorDropRequest(t *testing.T) { deleteReq.SetMessageID(2) _, err = cc.Do(deleteReq) require.Error(t, err) - require.True(t, errors.Is(err, context.DeadlineExceeded)) + require.ErrorIs(t, err, context.DeadlineExceeded) } diff --git a/tcp/coder/bench_test.go b/tcp/coder/bench_test.go index 0d2fd54f..d5d3d615 100644 --- a/tcp/coder/bench_test.go +++ b/tcp/coder/bench_test.go @@ -12,8 +12,7 @@ func BenchmarkMarshalMessage(b *testing.B) { bufOptions := make([]byte, 1024) bufOptionsUsed := bufOptions - enc := 0 - + var enc int options, enc, _ = options.SetPath(bufOptionsUsed, "/a/b/c/d/e") bufOptionsUsed = bufOptionsUsed[enc:] diff --git a/tcp/coder/coder_test.go b/tcp/coder/coder_test.go index b3c86ff1..b7d54d97 100644 --- a/tcp/coder/coder_test.go +++ b/tcp/coder/coder_test.go @@ -30,7 +30,7 @@ func TestMarshalMessage(t *testing.T) { bufOptions := make([]byte, 1024) bufOptionsUsed := bufOptions options := make(message.Options, 0, 32) - enc := 0 + options, enc, err := options.SetPath(bufOptionsUsed, "/a/b/c/d/e") if err != nil { t.Fatalf("Cannot set uri") diff --git a/tcp/server/server.go b/tcp/server/server.go index b4b95063..08f6e079 100644 --- a/tcp/server/server.go +++ b/tcp/server/server.go @@ -82,7 +82,7 @@ func (s *Server) checkAndSetListener(l Listener) error { s.listenMutex.Lock() defer s.listenMutex.Unlock() if s.listen != nil { - return fmt.Errorf("server already serves listener") + return errors.New("server already serves listener") } s.listen = l return nil @@ -135,7 +135,7 @@ func (s *Server) serveConnection(connections *connections.Connections, rw net.Co func (s *Server) Serve(l Listener) error { if s.cfg.BlockwiseSZX > blockwise.SZXBERT { - return fmt.Errorf("invalid blockwiseSZX") + return errors.New("invalid blockwiseSZX") } err := s.checkAndSetListener(l) diff --git a/udp/client/conn.go b/udp/client/conn.go index 3ec4ce6e..5fc0699f 100644 --- a/udp/client/conn.go +++ b/udp/client/conn.go @@ -323,7 +323,7 @@ func (cc *Conn) Close() error { func (cc *Conn) doInternal(req *pool.Message) (*pool.Message, error) { token := req.Token() if token == nil { - return nil, fmt.Errorf("invalid token") + return nil, errors.New("invalid token") } respChan := make(chan *pool.Message, 1) @@ -942,7 +942,7 @@ func (cc *Conn) ReleaseMessage(m *pool.Message) { // Via opts you can specify the network interface, source IP address, and hop limit. func (cc *Conn) WriteMulticastMessage(req *pool.Message, address *net.UDPAddr, options ...coapNet.MulticastOption) error { if req.Type() == message.Confirmable { - return fmt.Errorf("multicast messages cannot be confirmable") + return errors.New("multicast messages cannot be confirmable") } req.UpsertMessageID(cc.GetMessageID()) diff --git a/udp/client/conn_test.go b/udp/client/conn_test.go index cddec86e..49a4153e 100644 --- a/udp/client/conn_test.go +++ b/udp/client/conn_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "errors" - "fmt" "io" "log" "sync" @@ -374,7 +373,7 @@ func TestConnGetSeparateMessage(t *testing.T) { }() cc, err := udp.Dial(l.LocalAddr().String(), options.WithHandlerFunc(func(_ *responsewriter.ResponseWriter[*client.Conn], r *pool.Message) { - assert.NoError(t, fmt.Errorf("none msg expected comes: %+v", r)) + require.Failf(t, "Unexpected msg", "Received unexpected message: %+v", r) })) require.NoError(t, err) defer func() { @@ -1003,5 +1002,5 @@ func TestConnRequestMonitorDropRequest(t *testing.T) { deleteReq.SetMessageID(2) _, err = cc.Do(deleteReq) require.Error(t, err) - require.True(t, errors.Is(err, context.DeadlineExceeded)) + require.ErrorIs(t, err, context.DeadlineExceeded) } diff --git a/udp/client_test.go b/udp/client_test.go index 35f73acf..f577bbb7 100644 --- a/udp/client_test.go +++ b/udp/client_test.go @@ -4,7 +4,6 @@ import ( "bytes" "context" "errors" - "fmt" "io" "log" "net" @@ -105,7 +104,7 @@ func TestConnGet(t *testing.T) { errS := w.SetResponse(codes.BadRequest, message.TextPlain, bytes.NewReader(make([]byte, 5330))) require.NoError(t, errS) require.NotEmpty(t, w.Conn()) - require.True(t, r.Type() == message.Confirmable) + require.Equal(t, message.Confirmable, r.Type()) })) require.NoError(t, err) err = m.Handle("/b", mux.HandlerFunc(func(w mux.ResponseWriter, r *mux.Message) { @@ -113,7 +112,7 @@ func TestConnGet(t *testing.T) { errS := w.SetResponse(codes.Content, message.TextPlain, bytes.NewReader([]byte("b"))) require.NoError(t, errS) require.NotEmpty(t, w.Conn()) - assert.True(t, r.Type() == message.Confirmable) + assert.Equal(t, message.Confirmable, r.Type()) })) require.NoError(t, err) err = m.Handle("/b-non", mux.HandlerFunc(func(w mux.ResponseWriter, r *mux.Message) { @@ -121,7 +120,7 @@ func TestConnGet(t *testing.T) { errS := w.SetResponse(codes.Content, message.TextPlain, bytes.NewReader([]byte("b"))) require.NoError(t, errS) require.NotEmpty(t, w.Conn()) - assert.False(t, r.Type() == message.Confirmable) + assert.NotEqual(t, message.Confirmable, r.Type()) })) require.NoError(t, err) err = m.Handle("/empty", mux.HandlerFunc(func(w mux.ResponseWriter, r *mux.Message) { @@ -131,7 +130,7 @@ func TestConnGet(t *testing.T) { errS := w.SetResponse(codes.Content, message.TextPlain, bytes.NewReader([]byte{})) require.NoError(t, errS) require.NotEmpty(t, w.Conn()) - assert.True(t, r.Type() == message.Confirmable) + require.Equal(t, message.Confirmable, r.Type()) })) require.NoError(t, err) @@ -173,7 +172,7 @@ func TestConnGet(t *testing.T) { assert.Greater(t, got.Sequence(), uint64(0)) if tt.wantContentFormat != nil { ct, errC := got.ContentFormat() - assert.NoError(t, errC) + require.NoError(t, errC) assert.Equal(t, *tt.wantContentFormat, ct) } if tt.wantPayload != nil { @@ -207,7 +206,7 @@ func TestConnGetSeparateMessage(t *testing.T) { go func() { time.Sleep(time.Second * 1) assert.Equal(t, codes.GET, r.Code()) - assert.True(t, r.Type() == message.Confirmable) + assert.Equal(t, message.Confirmable, r.Type()) customResp := message.Message{ Code: codes.Content, Token: r.Token(), @@ -246,7 +245,7 @@ func TestConnGetSeparateMessage(t *testing.T) { }() cc, err := Dial(l.LocalAddr().String(), options.WithHandlerFunc(func(_ *responsewriter.ResponseWriter[*client.Conn], r *pool.Message) { - assert.NoError(t, fmt.Errorf("none msg expected comes: %+v", r)) + require.Failf(t, "Unexpected msg", "Received unexpected message: %+v", r) })) require.NoError(t, err) defer func() { @@ -339,7 +338,7 @@ func TestConnPost(t *testing.T) { errH = w.SetResponse(codes.BadRequest, message.TextPlain, bytes.NewReader(make([]byte, 5330))) require.NoError(t, errH) require.NotEmpty(t, w.Conn()) - assert.True(t, r.Type() == message.Confirmable) + assert.Equal(t, message.Confirmable, r.Type()) })) require.NoError(t, err) err = m.Handle("/b", mux.HandlerFunc(func(w mux.ResponseWriter, r *mux.Message) { @@ -353,7 +352,7 @@ func TestConnPost(t *testing.T) { errH = w.SetResponse(codes.Content, message.TextPlain, bytes.NewReader([]byte("b"))) require.NoError(t, errH) require.NotEmpty(t, w.Conn()) - assert.True(t, r.Type() == message.Confirmable) + assert.Equal(t, message.Confirmable, r.Type()) })) require.NoError(t, err) @@ -469,7 +468,7 @@ func TestConnPut(t *testing.T) { errH = w.SetResponse(codes.BadRequest, message.TextPlain, bytes.NewReader(make([]byte, 5330))) require.NoError(t, errH) require.NotEmpty(t, w.Conn()) - assert.True(t, r.Type() == message.Confirmable) + assert.Equal(t, message.Confirmable, r.Type()) })) require.NoError(t, err) err = m.Handle("/b", mux.HandlerFunc(func(w mux.ResponseWriter, r *mux.Message) { @@ -483,7 +482,7 @@ func TestConnPut(t *testing.T) { errH = w.SetResponse(codes.Content, message.TextPlain, bytes.NewReader([]byte("b"))) require.NoError(t, errH) require.NotEmpty(t, w.Conn()) - assert.True(t, r.Type() == message.Confirmable) + assert.Equal(t, message.Confirmable, r.Type()) })) require.NoError(t, err) @@ -582,7 +581,7 @@ func TestConnDelete(t *testing.T) { errH := w.SetResponse(codes.BadRequest, message.TextPlain, bytes.NewReader(make([]byte, 5330))) require.NoError(t, errH) require.NotEmpty(t, w.Conn()) - assert.True(t, r.Type() == message.Confirmable) + assert.Equal(t, message.Confirmable, r.Type()) })) require.NoError(t, err) err = m.Handle("/b", mux.HandlerFunc(func(w mux.ResponseWriter, r *mux.Message) { @@ -590,7 +589,7 @@ func TestConnDelete(t *testing.T) { errH := w.SetResponse(codes.Deleted, message.TextPlain, bytes.NewReader([]byte("b"))) require.NoError(t, errH) require.NotEmpty(t, w.Conn()) - assert.True(t, r.Type() == message.Confirmable) + assert.Equal(t, message.Confirmable, r.Type()) })) require.NoError(t, err) diff --git a/udp/coder/bench_test.go b/udp/coder/bench_test.go index 7974f9d5..3ca7cb42 100644 --- a/udp/coder/bench_test.go +++ b/udp/coder/bench_test.go @@ -12,7 +12,7 @@ func BenchmarkMarshalMessage(b *testing.B) { bufOptions := make([]byte, 1024) bufOptionsUsed := bufOptions - enc := 0 + var enc int options, enc, _ = options.SetPath(bufOptionsUsed, "/a/b/c/d/e") bufOptionsUsed = bufOptionsUsed[enc:] diff --git a/udp/coder/coder_test.go b/udp/coder/coder_test.go index a6b11a83..b4e4e61f 100644 --- a/udp/coder/coder_test.go +++ b/udp/coder/coder_test.go @@ -78,7 +78,7 @@ func TestMarshalMessage(t *testing.T) { bufOptions := make([]byte, 1024) bufOptionsUsed := bufOptions options := make(message.Options, 0, 32) - enc := 0 + var enc int options, enc, err = options.SetPath(bufOptionsUsed, "/a/b/c/d/e") if err != nil { t.Fatalf("Cannot set uri") diff --git a/udp/server/discover.go b/udp/server/discover.go index aa41af4c..ee771bab 100644 --- a/udp/server/discover.go +++ b/udp/server/discover.go @@ -2,6 +2,7 @@ package server import ( "context" + "errors" "fmt" "net" @@ -9,7 +10,7 @@ import ( "github.com/plgd-dev/go-coap/v3/message/pool" coapNet "github.com/plgd-dev/go-coap/v3/net" "github.com/plgd-dev/go-coap/v3/net/responsewriter" - "github.com/plgd-dev/go-coap/v3/pkg/errors" + pkgErrors "github.com/plgd-dev/go-coap/v3/pkg/errors" "github.com/plgd-dev/go-coap/v3/udp/client" "github.com/plgd-dev/go-coap/v3/udp/coder" ) @@ -43,11 +44,11 @@ func (s *Server) Discover(ctx context.Context, address, path string, receiverFun func (s *Server) DiscoveryRequest(req *pool.Message, address string, receiverFunc func(cc *client.Conn, resp *pool.Message), opts ...coapNet.MulticastOption) error { token := req.Token() if len(token) == 0 { - return fmt.Errorf("invalid token") + return errors.New("invalid token") } c := s.conn() if c == nil { - return fmt.Errorf("server doesn't serve connection") + return errors.New("server doesn't serve connection") } addr, err := net.ResolveUDPAddr(c.Network(), address) if err != nil { @@ -63,7 +64,7 @@ func (s *Server) DiscoveryRequest(req *pool.Message, address string, receiverFun if _, loaded := s.multicastHandler.LoadOrStore(token.Hash(), func(w *responsewriter.ResponseWriter[*client.Conn], r *pool.Message) { receiverFunc(w.Conn(), r) }); loaded { - return errors.ErrKeyAlreadyExists + return pkgErrors.ErrKeyAlreadyExists } defer func() { _, _ = s.multicastHandler.LoadAndDelete(token.Hash()) diff --git a/udp/server/server.go b/udp/server/server.go index b1361696..beffe0ea 100644 --- a/udp/server/server.go +++ b/udp/server/server.go @@ -2,6 +2,7 @@ package server import ( "context" + "errors" "fmt" "net" "sync" @@ -117,7 +118,7 @@ func (s *Server) closeConnection(cc *client.Conn) { func (s *Server) Serve(l *coapNet.UDPConn) error { if s.cfg.BlockwiseSZX > blockwise.SZX1024 { - return fmt.Errorf("invalid blockwiseSZX") + return errors.New("invalid blockwiseSZX") } err := s.checkAndSetListener(l) @@ -372,7 +373,7 @@ func (s *Server) getConn(l *coapNet.UDPConn, raddr *net.UDPAddr, firstTime bool) if firstTime { return s.getConn(l, raddr, false) } - return nil, fmt.Errorf("connection is closed") + return nil, errors.New("connection is closed") } return cc, nil } @@ -381,7 +382,7 @@ func (s *Server) NewConn(addr *net.UDPAddr) (*client.Conn, error) { l := s.getListener() if l == nil { // server is not started/stopped - return nil, fmt.Errorf("server is not running") + return nil, errors.New("server is not running") } return s.getConn(l, addr, true) } diff --git a/udp/server/session.go b/udp/server/session.go index 55394142..99d3bf95 100644 --- a/udp/server/session.go +++ b/udp/server/session.go @@ -18,7 +18,7 @@ type EventFunc = func() type Session struct { onClose []EventFunc - ctx atomic.Value // TODO: change to atomic.Pointer[context.Context] for go1.19 + ctx atomic.Pointer[context.Context] doneCtx context.Context connection *coapNet.UDPConn @@ -101,7 +101,7 @@ func (s *Session) Close() error { } func (s *Session) Context() context.Context { - return *s.ctx.Load().(*context.Context) //nolint:forcetypeassert + return *s.ctx.Load() } func (s *Session) WriteMessage(req *pool.Message) error { diff --git a/udp/server_test.go b/udp/server_test.go index 7af22d33..5c2f3814 100644 --- a/udp/server_test.go +++ b/udp/server_test.go @@ -197,7 +197,7 @@ func TestServerDiscover(t *testing.T) { err = sd.Discover(ctx, multicastAddr, path, recv.process, tt.args.opts...) require.NoError(t, err) got := recv.pop() - require.Greater(t, len(got), 0) + require.NotEmpty(t, got) require.Equal(t, codes.BadRequest, got[0].Code()) }) }