ソースを参照

golangci-lint 1.49 and related fixes (#1736)

mmetc 2 年 前
コミット
414282a2c9
42 ファイル変更139 行追加157 行削除
  1. 1 1
      .github/workflows/ci_golangci-lint.yml
  2. 33 34
      .golangci.yml
  3. 2 2
      cmd/crowdsec-cli/capi.go
  4. 3 3
      cmd/crowdsec-cli/config.go
  5. 2 2
      cmd/crowdsec-cli/lapi.go
  6. 2 2
      cmd/crowdsec-cli/machines.go
  7. 3 3
      cmd/crowdsec-cli/simulation.go
  8. 7 6
      cmd/crowdsec-cli/support.go
  9. 4 5
      cmd/crowdsec-cli/utils.go
  10. 2 2
      pkg/acquisition/modules/kafka/kafka.go
  11. 2 2
      pkg/acquisition/modules/kinesis/kinesis.go
  12. 2 2
      pkg/apiclient/client.go
  13. 4 5
      pkg/apiclient/decisions_service_test.go
  14. 1 1
      pkg/apiclient/signal.go
  15. 1 2
      pkg/apiserver/apiserver.go
  16. 2 2
      pkg/apiserver/controllers/v1/alerts.go
  17. 2 2
      pkg/apiserver/controllers/v1/decisions.go
  18. 4 3
      pkg/apiserver/middlewares/v1/tls_auth.go
  19. 3 3
      pkg/csconfig/api.go
  20. 1 2
      pkg/csconfig/api_test.go
  21. 1 2
      pkg/csconfig/console.go
  22. 13 14
      pkg/csplugin/broker_test.go
  23. 2 3
      pkg/cstest/hubtest.go
  24. 1 2
      pkg/cstest/hubtest_item.go
  25. 2 2
      pkg/cstest/parser_assert.go
  26. 3 3
      pkg/cstest/scenario_assert.go
  27. 5 6
      pkg/cstest/utils.go
  28. 1 2
      pkg/cwhub/cwhub_test.go
  29. 4 5
      pkg/cwhub/download.go
  30. 1 2
      pkg/cwhub/loader.go
  31. 2 3
      pkg/leakybucket/buckets_test.go
  32. 1 2
      pkg/leakybucket/manager_load.go
  33. 1 2
      pkg/leakybucket/manager_run.go
  34. 4 5
      pkg/metabase/metabase.go
  35. 3 4
      pkg/parser/parsing_test.go
  36. 2 2
      pkg/parser/unix_parser.go
  37. 3 3
      pkg/types/dataset.go
  38. 1 2
      pkg/types/dataset_test.go
  39. 1 2
      pkg/types/utils.go
  40. 2 2
      pkg/yamlpatch/merge_test.go
  41. 2 2
      plugins/notifications/http/main.go
  42. 3 3
      plugins/notifications/splunk/main.go

+ 1 - 1
.github/workflows/ci_golangci-lint.yml

@@ -28,7 +28,7 @@ jobs:
         uses: golangci/golangci-lint-action@v3
         uses: golangci/golangci-lint-action@v3
         with:
         with:
           # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
           # Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
-          version: v1.48
+          version: v1.49
           # Optional: golangci-lint command line arguments.
           # Optional: golangci-lint command line arguments.
           args: --issues-exit-code=1 --timeout 10m
           args: --issues-exit-code=1 --timeout 10m
           # Optional: show only new issues if it's a pull request. The default value is `false`.
           # Optional: show only new issues if it's a pull request. The default value is `false`.

+ 33 - 34
.golangci.yml

@@ -38,21 +38,28 @@ linters:
     #
     #
     # DEPRECATED by golangi-lint
     # DEPRECATED by golangi-lint
     #
     #
+    - deadcode          # The owner seems to have abandoned the linter.  Replaced by unused.
     - exhaustivestruct  # The owner seems to have abandoned the linter. Replaced by exhaustruct.
     - exhaustivestruct  # The owner seems to have abandoned the linter. Replaced by exhaustruct.
     - golint            # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes
     - golint            # Golint differs from gofmt. Gofmt reformats Go source code, whereas golint prints out style mistakes
+    - ifshort           # Checks that your code uses short syntax for if-statements whenever possible
     - interfacer        # Linter that suggests narrower interface types
     - interfacer        # Linter that suggests narrower interface types
     - maligned          # Tool to detect Go structs that would take less memory if their fields were sorted
     - maligned          # Tool to detect Go structs that would take less memory if their fields were sorted
+    - nosnakecase       # nosnakecase is a linter that detects snake case of variable naming and function name.
     - scopelint         # Scopelint checks for unpinned variables in go programs
     - scopelint         # Scopelint checks for unpinned variables in go programs
+    - structcheck       # The owner seems to have abandoned the linter.  Replaced by unused.
+    - varcheck          # The owner seems to have abandoned the linter.  Replaced by unused.
 
 
     #
     #
     # Enabled
     # Enabled
     #
     #
+
     # - asasalint           # check for pass []any as any in variadic func(...any)
     # - 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
     # - asciicheck          # Simple linter to check that your code does not contain non-ASCII identifiers
     # - bidichk             # Checks for dangerous unicode character sequences
     # - bidichk             # Checks for dangerous unicode character sequences
     # - decorder            # check declaration order and count of types, constants, variables and functions
     # - 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
     # - depguard            # Go linter that checks if package imports are in a list of acceptable packages
     # - durationcheck       # check for two durations multiplied together
     # - durationcheck       # check for two durations multiplied together
+    # - errcheck            # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
     # - exportloopref       # checks for pointers to enclosing loop variables
     # - exportloopref       # checks for pointers to enclosing loop variables
     # - funlen              # Tool for detection of long functions
     # - funlen              # Tool for detection of long functions
     # - gochecknoinits      # Checks that no init functions are present in Go code
     # - gochecknoinits      # Checks that no init functions are present in Go code
@@ -60,60 +67,53 @@ linters:
     # - gomoddirectives     # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.
     # - gomoddirectives     # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.
     # - 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.
     # - 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
     # - goprintffuncname    # Checks that printf-like functions are named with `f` at the end
+    # - gosimple            # (megacheck): Linter for Go source code that specializes in simplifying a code
+    # - govet               # (vet, vetshadow): 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
     # - importas            # Enforces consistent import aliases
+    # - ineffassign         # Detects when assignments to existing variables are not used
+    # - interfacebloat      # A linter that checks the number of methods inside an interface.
+    # - logrlint            # Check logr arguments.
     # - makezero            # Finds slice declarations with non-zero initial length
     # - makezero            # Finds slice declarations with non-zero initial length
     # - misspell            # Finds commonly misspelled English words in comments
     # - misspell            # Finds commonly misspelled English words in comments
     # - nolintlint          # Reports ill-formed or insufficient nolint directives
     # - nolintlint          # Reports ill-formed or insufficient nolint directives
     # - predeclared         # find code that shadows one of Go's predeclared identifiers
     # - predeclared         # find code that shadows one of Go's predeclared identifiers
+    # - reassign            # Checks that package variables are not reassigned
     # - rowserrcheck        # checks whether Err of rows is checked successfully
     # - rowserrcheck        # checks whether Err of rows is checked successfully
     # - sqlclosecheck       # Checks that sql.Rows and sql.Stmt are closed.
     # - sqlclosecheck       # Checks that sql.Rows and sql.Stmt are closed.
+    # - staticcheck         # (megacheck): Staticcheck is a go vet on steroids, applying a ton of static analysis checks
     # - tenv                # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
     # - 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
     # - 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
     # - typecheck           # Like the front-end of a Go compiler, parses and type-checks Go code
     # - unconvert           # Remove unnecessary type conversions
     # - unconvert           # Remove unnecessary type conversions
+    # - unused              # (megacheck): Checks Go code for unused constants, variables, functions and types
     # - usestdlibvars       # A linter that detect the possibility to use variables/constants from the Go standard library.
     # - usestdlibvars       # A linter that detect the possibility to use variables/constants from the Go standard library.
-    # - varcheck            # Finds unused global variables and constants
-
-    #
-    # Enabled by default by golangci (but requires fixing current issues, see at the end of this file) There
-    # is some redundancy, but never 1 to 1 (staticcheck seems to find more
-    # cases than ineffassign, deadcore more than unused..).
-    #
-    # - deadcode              # Finds unused code
-    # - errcheck              # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
-    # - gosimple              # (megacheck): Linter for Go source code that specializes in simplifying a code
-    # - govet                 # (vet, vetshadow): Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
-    # - ineffassign           # Detects when assignments to existing variables are not used
-    # - staticcheck           # (megacheck): Staticcheck is a go vet on steroids, applying a ton of static analysis checks
-    # - structcheck           # Finds unused struct fields
-    # - unused                # (megacheck): Checks Go code for unused constants, variables, functions and types
 
 
     #
     #
     # Recommended? (easy)
     # Recommended? (easy)
     #
     #
+
+    - dogsled               # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
     - 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.
     - 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.
     - 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.
     - 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
     - forcetypeassert       # finds forced type assertions
     - forcetypeassert       # finds forced type assertions
     - gci                   # Gci control golang package import order and make it always deterministic.
     - gci                   # Gci control golang package import order and make it always deterministic.
+    - gocritic              # Provides diagnostics that check for bugs, performance and style issues.
+    - godot                 # Check if comments end in a period
     - gofmt                 # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
     - gofmt                 # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
     - goimports             # In addition to fixing imports, goimports also formats your code in the same style as gofmt.
     - goimports             # In addition to fixing imports, goimports also formats your code in the same style as gofmt.
     - gosec                 # (gas): Inspects source code for security problems
     - gosec                 # (gas): Inspects source code for security problems
+    - lll                   # Reports long lines
     - nakedret              # Finds naked returns in functions greater than a specified function length
     - 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.
     - nilerr                # Finds the code that returns nil even if it checks that the error is not nil.
     - nonamedreturns        # Reports all named returns
     - nonamedreturns        # Reports all named returns
     - nosprintfhostport     # Checks for misuse of Sprintf to construct a host with port in a URL.
     - nosprintfhostport     # Checks for misuse of Sprintf to construct a host with port in a URL.
     - promlinter            # Check Prometheus metrics naming via promlint
     - promlinter            # Check Prometheus metrics naming via promlint
     - revive                # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint.
     - revive                # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint.
-    - wastedassign          # wastedassign finds wasted assignment statements.
-    - gocritic              # Provides diagnostics that check for bugs, performance and style issues.
-    - exhaustive            # check exhaustiveness of enum switch statements
     - thelper               # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
     - thelper               # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
-    - dogsled               # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
+    - wastedassign          # wastedassign finds wasted assignment statements.
     - wrapcheck             # Checks that errors returned from external packages are wrapped
     - wrapcheck             # Checks that errors returned from external packages are wrapped
-    - lll                   # Reports long lines
-    - ifshort               # Checks that your code uses short syntax for if-statements whenever possible
-    - godot                 # Check if comments end in a period
 
 
     #
     #
     # Recommended? (requires some work)
     # Recommended? (requires some work)
@@ -122,12 +122,12 @@ linters:
     - bodyclose             # checks whether HTTP response body is closed successfully
     - bodyclose             # checks whether HTTP response body is closed successfully
     - containedctx          # containedctx is a linter that detects struct contained context.Context field
     - containedctx          # containedctx is a linter that detects struct contained context.Context field
     - contextcheck          # check the function whether use a non-inherited context
     - contextcheck          # check the function whether use a non-inherited context
-    - nilnil                # Checks that there is no simultaneous return of `nil` error and an invalid value.
-    - noctx                 # noctx finds sending http request without context.Context
-    - unparam               # Reports unused function parameters
     - errname               # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
     - errname               # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
     - gomnd                 # An analyzer to detect magic numbers.
     - gomnd                 # An analyzer to detect magic numbers.
     - ireturn               # Accept Interfaces, Return Concrete Types
     - ireturn               # Accept Interfaces, Return Concrete Types
+    - nilnil                # Checks that there is no simultaneous return of `nil` error and an invalid value.
+    - noctx                 # noctx finds sending http request without context.Context
+    - unparam               # Reports unused function parameters
 
 
     #
     #
     # Formatting only, useful in IDE but should not be forced on CI?
     # Formatting only, useful in IDE but should not be forced on CI?
@@ -141,29 +141,28 @@ linters:
     #
     #
     # Well intended, but not ready for this
     # Well intended, but not ready for this
     #
     #
-    - paralleltest          # paralleltest detects missing usage of t.Parallel() method in your Go test
     - cyclop                # checks function and package cyclomatic complexity
     - cyclop                # checks function and package cyclomatic complexity
+    - dupl                  # Tool for code clone detection
     - gocognit              # Computes and checks the cognitive complexity of functions
     - gocognit              # Computes and checks the cognitive complexity of functions
-    - maintidx              # maintidx measures the maintainability index of each function.
-    - goerr113              # Golang linter to check the errors handling expressions
-    - nestif                # Reports deeply nested if statements
     - gocyclo               # Computes and checks the cyclomatic complexity of functions
     - 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
-    - dupl                  # Tool for code clone detection
+    - goerr113              # Golang linter to check the errors handling expressions
+    - maintidx              # maintidx measures the maintainability index of each function.
+    - nestif                # Reports deeply nested if statements
+    - paralleltest          # paralleltest detects missing usage of t.Parallel() method in your Go test
     - testpackage           # linter that makes you use a separate _test package
     - testpackage           # linter that makes you use a separate _test package
 
 
     #
     #
     # Too strict / too many false positives (for now?)
     # Too strict / too many false positives (for now?)
     #
     #
     - execinquery           # execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds
     - execinquery           # execinquery is a linter about query string checker in Query function which reads your Go src files and warning it finds
+    - exhaustruct           # Checks if all structure fields are initialized
     - forbidigo             # Forbids identifiers
     - forbidigo             # Forbids identifiers
-    - tagliatelle           # Checks the struct tags.
-    - varnamelen            # checks that the length of a variable's name matches its scope
     - gochecknoglobals      # check that no global variables exist
     - gochecknoglobals      # check that no global variables exist
-    - exhaustruct           # Checks if all structure fields are initialized
     - goconst               # Finds repeated strings that could be replaced by a constant
     - goconst               # Finds repeated strings that could be replaced by a constant
     - stylecheck            # Stylecheck is a replacement for golint
     - stylecheck            # Stylecheck is a replacement for golint
-    - nosnakecase           # nosnakecase is a linter that detects snake case of variable naming and function name.
+    - tagliatelle           # Checks the struct tags.
+    - varnamelen            # checks that the length of a variable's name matches its scope
 
 
     #
     #
     # Under evaluation
     # Under evaluation

+ 2 - 2
cmd/crowdsec-cli/capi.go

@@ -3,8 +3,8 @@ package main
 import (
 import (
 	"context"
 	"context"
 	"fmt"
 	"fmt"
-	"io/ioutil"
 	"net/url"
 	"net/url"
+	"os"
 
 
 	"github.com/crowdsecurity/crowdsec/pkg/apiclient"
 	"github.com/crowdsecurity/crowdsec/pkg/apiclient"
 	"github.com/crowdsecurity/crowdsec/pkg/csconfig"
 	"github.com/crowdsecurity/crowdsec/pkg/csconfig"
@@ -89,7 +89,7 @@ func NewCapiCmd() *cobra.Command {
 				log.Fatalf("unable to marshal api credentials: %s", err)
 				log.Fatalf("unable to marshal api credentials: %s", err)
 			}
 			}
 			if dumpFile != "" {
 			if dumpFile != "" {
-				err = ioutil.WriteFile(dumpFile, apiConfigDump, 0600)
+				err = os.WriteFile(dumpFile, apiConfigDump, 0600)
 				if err != nil {
 				if err != nil {
 					log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
 					log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
 				}
 				}

+ 3 - 3
cmd/crowdsec-cli/config.go

@@ -3,7 +3,7 @@ package main
 import (
 import (
 	"encoding/json"
 	"encoding/json"
 	"fmt"
 	"fmt"
-	"io/ioutil"
+	"io"
 	"os"
 	"os"
 	"path/filepath"
 	"path/filepath"
 
 
@@ -181,7 +181,7 @@ func restoreConfigFromDirectory(dirPath string) error {
 		if err != nil {
 		if err != nil {
 			log.Warningf("failed to open %s : %s", backupOldAPICfg, err)
 			log.Warningf("failed to open %s : %s", backupOldAPICfg, err)
 		} else {
 		} else {
-			byteValue, _ := ioutil.ReadAll(jsonFile)
+			byteValue, _ := io.ReadAll(jsonFile)
 			err = json.Unmarshal(byteValue, &oldAPICfg)
 			err = json.Unmarshal(byteValue, &oldAPICfg)
 			if err != nil {
 			if err != nil {
 				return fmt.Errorf("failed to load json file %s : %s", backupOldAPICfg, err)
 				return fmt.Errorf("failed to load json file %s : %s", backupOldAPICfg, err)
@@ -200,7 +200,7 @@ func restoreConfigFromDirectory(dirPath string) error {
 			if csConfig.API.Server.OnlineClient != nil && csConfig.API.Server.OnlineClient.CredentialsFilePath != "" {
 			if csConfig.API.Server.OnlineClient != nil && csConfig.API.Server.OnlineClient.CredentialsFilePath != "" {
 				apiConfigDumpFile = csConfig.API.Server.OnlineClient.CredentialsFilePath
 				apiConfigDumpFile = csConfig.API.Server.OnlineClient.CredentialsFilePath
 			}
 			}
-			err = ioutil.WriteFile(apiConfigDumpFile, apiConfigDump, 0644)
+			err = os.WriteFile(apiConfigDumpFile, apiConfigDump, 0644)
 			if err != nil {
 			if err != nil {
 				return fmt.Errorf("write api credentials in '%s' failed: %s", apiConfigDumpFile, err)
 				return fmt.Errorf("write api credentials in '%s' failed: %s", apiConfigDumpFile, err)
 			}
 			}

+ 2 - 2
cmd/crowdsec-cli/lapi.go

@@ -3,8 +3,8 @@ package main
 import (
 import (
 	"context"
 	"context"
 	"fmt"
 	"fmt"
-	"io/ioutil"
 	"net/url"
 	"net/url"
+	"os"
 	"strings"
 	"strings"
 
 
 	"github.com/crowdsecurity/crowdsec/pkg/apiclient"
 	"github.com/crowdsecurity/crowdsec/pkg/apiclient"
@@ -103,7 +103,7 @@ Keep in mind the machine needs to be validated by an administrator on LAPI side
 				log.Fatalf("unable to marshal api credentials: %s", err)
 				log.Fatalf("unable to marshal api credentials: %s", err)
 			}
 			}
 			if dumpFile != "" {
 			if dumpFile != "" {
-				err = ioutil.WriteFile(dumpFile, apiConfigDump, 0644)
+				err = os.WriteFile(dumpFile, apiConfigDump, 0644)
 				if err != nil {
 				if err != nil {
 					log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
 					log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
 				}
 				}

+ 2 - 2
cmd/crowdsec-cli/machines.go

@@ -6,8 +6,8 @@ import (
 	"encoding/csv"
 	"encoding/csv"
 	"encoding/json"
 	"encoding/json"
 	"fmt"
 	"fmt"
-	"io/ioutil"
 	"math/big"
 	"math/big"
+	"os"
 	"strings"
 	"strings"
 	"time"
 	"time"
 
 
@@ -294,7 +294,7 @@ cscli machines add MyTestMachine --password MyPassword
 				log.Fatalf("unable to marshal api credentials: %s", err)
 				log.Fatalf("unable to marshal api credentials: %s", err)
 			}
 			}
 			if dumpFile != "" && dumpFile != "-" {
 			if dumpFile != "" && dumpFile != "-" {
-				err = ioutil.WriteFile(dumpFile, apiConfigDump, 0644)
+				err = os.WriteFile(dumpFile, apiConfigDump, 0644)
 				if err != nil {
 				if err != nil {
 					log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
 					log.Fatalf("write api credentials in '%s' failed: %s", dumpFile, err)
 				}
 				}

+ 3 - 3
cmd/crowdsec-cli/simulation.go

@@ -2,7 +2,7 @@ package main
 
 
 import (
 import (
 	"fmt"
 	"fmt"
-	"io/ioutil"
+	"os"
 
 
 	"github.com/crowdsecurity/crowdsec/pkg/cwhub"
 	"github.com/crowdsecurity/crowdsec/pkg/cwhub"
 	log "github.com/sirupsen/logrus"
 	log "github.com/sirupsen/logrus"
@@ -45,7 +45,7 @@ func dumpSimulationFile() error {
 	if err != nil {
 	if err != nil {
 		return fmt.Errorf("unable to marshal simulation configuration: %s", err)
 		return fmt.Errorf("unable to marshal simulation configuration: %s", err)
 	}
 	}
-	err = ioutil.WriteFile(csConfig.ConfigPaths.SimulationFilePath, newConfigSim, 0644)
+	err = os.WriteFile(csConfig.ConfigPaths.SimulationFilePath, newConfigSim, 0644)
 	if err != nil {
 	if err != nil {
 		return fmt.Errorf("write simulation config in '%s' failed: %s", csConfig.ConfigPaths.SimulationFilePath, err)
 		return fmt.Errorf("write simulation config in '%s' failed: %s", csConfig.ConfigPaths.SimulationFilePath, err)
 	}
 	}
@@ -63,7 +63,7 @@ func disableGlobalSimulation() error {
 	if err != nil {
 	if err != nil {
 		return fmt.Errorf("unable to marshal new simulation configuration: %s", err)
 		return fmt.Errorf("unable to marshal new simulation configuration: %s", err)
 	}
 	}
-	err = ioutil.WriteFile(csConfig.ConfigPaths.SimulationFilePath, newConfigSim, 0644)
+	err = os.WriteFile(csConfig.ConfigPaths.SimulationFilePath, newConfigSim, 0644)
 	if err != nil {
 	if err != nil {
 		return fmt.Errorf("unable to write new simulation config in '%s' : %s", csConfig.ConfigPaths.SimulationFilePath, err)
 		return fmt.Errorf("unable to write new simulation config in '%s' : %s", csConfig.ConfigPaths.SimulationFilePath, err)
 	}
 	}

+ 7 - 6
cmd/crowdsec-cli/support.go

@@ -5,9 +5,10 @@ import (
 	"bytes"
 	"bytes"
 	"context"
 	"context"
 	"fmt"
 	"fmt"
-	"io/ioutil"
+	"io"
 	"net/http"
 	"net/http"
 	"net/url"
 	"net/url"
+	"os"
 	"path/filepath"
 	"path/filepath"
 	"regexp"
 	"regexp"
 	"strings"
 	"strings"
@@ -73,7 +74,7 @@ func collectMetrics() ([]byte, []byte, error) {
 
 
 	defer resp.Body.Close()
 	defer resp.Body.Close()
 
 
-	body, err := ioutil.ReadAll(resp.Body)
+	body, err := io.ReadAll(resp.Body)
 	if err != nil {
 	if err != nil {
 		return nil, nil, fmt.Errorf("could not read metrics from prometheus endpoint: %s", err)
 		return nil, nil, fmt.Errorf("could not read metrics from prometheus endpoint: %s", err)
 	}
 	}
@@ -176,7 +177,7 @@ func collectAPIStatus(login string, password string, endpoint string, prefix str
 
 
 func collectCrowdsecConfig() []byte {
 func collectCrowdsecConfig() []byte {
 	log.Info("Collecting crowdsec config")
 	log.Info("Collecting crowdsec config")
-	config, err := ioutil.ReadFile(*csConfig.FilePath)
+	config, err := os.ReadFile(*csConfig.FilePath)
 	if err != nil {
 	if err != nil {
 		return []byte(fmt.Sprintf("could not read config file: %s", err))
 		return []byte(fmt.Sprintf("could not read config file: %s", err))
 	}
 	}
@@ -188,7 +189,7 @@ func collectCrowdsecConfig() []byte {
 
 
 func collectCrowdsecProfile() []byte {
 func collectCrowdsecProfile() []byte {
 	log.Info("Collecting crowdsec profile")
 	log.Info("Collecting crowdsec profile")
-	config, err := ioutil.ReadFile(csConfig.API.Server.ProfilesPath)
+	config, err := os.ReadFile(csConfig.API.Server.ProfilesPath)
 	if err != nil {
 	if err != nil {
 		return []byte(fmt.Sprintf("could not read profile file: %s", err))
 		return []byte(fmt.Sprintf("could not read profile file: %s", err))
 	}
 	}
@@ -200,7 +201,7 @@ func collectAcquisitionConfig() map[string][]byte {
 	ret := make(map[string][]byte)
 	ret := make(map[string][]byte)
 
 
 	for _, filename := range csConfig.Crowdsec.AcquisitionFiles {
 	for _, filename := range csConfig.Crowdsec.AcquisitionFiles {
-		fileContent, err := ioutil.ReadFile(filename)
+		fileContent, err := os.ReadFile(filename)
 		if err != nil {
 		if err != nil {
 			ret[filename] = []byte(fmt.Sprintf("could not read file: %s", err))
 			ret[filename] = []byte(fmt.Sprintf("could not read file: %s", err))
 		} else {
 		} else {
@@ -379,7 +380,7 @@ cscli support dump -f /tmp/crowdsec-support.zip
 			if err != nil {
 			if err != nil {
 				log.Fatalf("could not finalize zip file: %s", err)
 				log.Fatalf("could not finalize zip file: %s", err)
 			}
 			}
-			err = ioutil.WriteFile(outFile, w.Bytes(), 0600)
+			err = os.WriteFile(outFile, w.Bytes(), 0600)
 			if err != nil {
 			if err != nil {
 				log.Fatalf("could not write zip file to %s: %s", outFile, err)
 				log.Fatalf("could not write zip file to %s: %s", outFile, err)
 			}
 			}

+ 4 - 5
cmd/crowdsec-cli/utils.go

@@ -5,7 +5,6 @@ import (
 	"encoding/csv"
 	"encoding/csv"
 	"encoding/json"
 	"encoding/json"
 	"fmt"
 	"fmt"
-	"io/ioutil"
 	"math"
 	"math"
 	"net"
 	"net"
 	"net/http"
 	"net/http"
@@ -593,7 +592,7 @@ func RestoreHub(dirPath string) error {
 		}
 		}
 		/*restore the upstream items*/
 		/*restore the upstream items*/
 		upstreamListFN := fmt.Sprintf("%s/upstream-%s.json", itemDirectory, itype)
 		upstreamListFN := fmt.Sprintf("%s/upstream-%s.json", itemDirectory, itype)
-		file, err := ioutil.ReadFile(upstreamListFN)
+		file, err := os.ReadFile(upstreamListFN)
 		if err != nil {
 		if err != nil {
 			return fmt.Errorf("error while opening %s : %s", upstreamListFN, err)
 			return fmt.Errorf("error while opening %s : %s", upstreamListFN, err)
 		}
 		}
@@ -614,7 +613,7 @@ func RestoreHub(dirPath string) error {
 		}
 		}
 
 
 		/*restore the local and tainted items*/
 		/*restore the local and tainted items*/
-		files, err := ioutil.ReadDir(itemDirectory)
+		files, err := os.ReadDir(itemDirectory)
 		if err != nil {
 		if err != nil {
 			return fmt.Errorf("failed enumerating files of %s : %s", itemDirectory, err)
 			return fmt.Errorf("failed enumerating files of %s : %s", itemDirectory, err)
 		}
 		}
@@ -635,7 +634,7 @@ func RestoreHub(dirPath string) error {
 					return fmt.Errorf("error while creating stage directory %s : %s", stagedir, err)
 					return fmt.Errorf("error while creating stage directory %s : %s", stagedir, err)
 				}
 				}
 				/*find items*/
 				/*find items*/
-				ifiles, err := ioutil.ReadDir(itemDirectory + "/" + stage + "/")
+				ifiles, err := os.ReadDir(itemDirectory + "/" + stage + "/")
 				if err != nil {
 				if err != nil {
 					return fmt.Errorf("failed enumerating files of %s : %s", itemDirectory+"/"+stage, err)
 					return fmt.Errorf("failed enumerating files of %s : %s", itemDirectory+"/"+stage, err)
 				}
 				}
@@ -719,7 +718,7 @@ func BackupHub(dirPath string) error {
 		if err != nil {
 		if err != nil {
 			return fmt.Errorf("failed marshaling upstream parsers : %s", err)
 			return fmt.Errorf("failed marshaling upstream parsers : %s", err)
 		}
 		}
-		err = ioutil.WriteFile(upstreamParsersFname, upstreamParsersContent, 0644)
+		err = os.WriteFile(upstreamParsersFname, upstreamParsersContent, 0644)
 		if err != nil {
 		if err != nil {
 			return fmt.Errorf("unable to write to %s %s : %s", itemType, upstreamParsersFname, err)
 			return fmt.Errorf("unable to write to %s %s : %s", itemType, upstreamParsersFname, err)
 		}
 		}

+ 2 - 2
pkg/acquisition/modules/kafka/kafka.go

@@ -6,7 +6,7 @@ import (
 	"crypto/x509"
 	"crypto/x509"
 	"fmt"
 	"fmt"
 	"io"
 	"io"
-	"io/ioutil"
+	"os"
 	"strconv"
 	"strconv"
 	"time"
 	"time"
 
 
@@ -188,7 +188,7 @@ func (kc *KafkaConfiguration) NewTLSConfig() (*tls.Config, error) {
 	}
 	}
 	tlsConfig.Certificates = []tls.Certificate{cert}
 	tlsConfig.Certificates = []tls.Certificate{cert}
 
 
-	caCert, err := ioutil.ReadFile(kc.TLS.CaCert)
+	caCert, err := os.ReadFile(kc.TLS.CaCert)
 	if err != nil {
 	if err != nil {
 		return &tlsConfig, err
 		return &tlsConfig, err
 	}
 	}

+ 2 - 2
pkg/acquisition/modules/kinesis/kinesis.go

@@ -5,7 +5,7 @@ import (
 	"compress/gzip"
 	"compress/gzip"
 	"encoding/json"
 	"encoding/json"
 	"fmt"
 	"fmt"
-	"io/ioutil"
+	"io"
 	"strings"
 	"strings"
 	"time"
 	"time"
 
 
@@ -171,7 +171,7 @@ func (k *KinesisSource) decodeFromSubscription(record []byte) ([]CloudwatchSubsc
 		k.logger.Error(err)
 		k.logger.Error(err)
 		return nil, err
 		return nil, err
 	}
 	}
-	decompressed, err := ioutil.ReadAll(r)
+	decompressed, err := io.ReadAll(r)
 	if err != nil {
 	if err != nil {
 		k.logger.Error(err)
 		k.logger.Error(err)
 		return nil, err
 		return nil, err

+ 2 - 2
pkg/apiclient/client.go

@@ -6,7 +6,7 @@ import (
 	"crypto/x509"
 	"crypto/x509"
 	"encoding/json"
 	"encoding/json"
 	"fmt"
 	"fmt"
-	"io/ioutil"
+	"io"
 	"net/http"
 	"net/http"
 	"net/url"
 	"net/url"
 
 
@@ -152,7 +152,7 @@ func CheckResponse(r *http.Response) error {
 		return nil
 		return nil
 	}
 	}
 	errorResponse := &ErrorResponse{}
 	errorResponse := &ErrorResponse{}
-	data, err := ioutil.ReadAll(r.Body)
+	data, err := io.ReadAll(r.Body)
 	if err == nil && data != nil {
 	if err == nil && data != nil {
 		err := json.Unmarshal(data, errorResponse)
 		err := json.Unmarshal(data, errorResponse)
 		if err != nil {
 		if err != nil {

+ 4 - 5
pkg/apiclient/decisions_service_test.go

@@ -105,9 +105,8 @@ func TestDecisionsStream(t *testing.T) {
 	mux.HandleFunc("/decisions/stream", func(w http.ResponseWriter, r *http.Request) {
 	mux.HandleFunc("/decisions/stream", func(w http.ResponseWriter, r *http.Request) {
 
 
 		assert.Equal(t, r.Header.Get("X-Api-Key"), "ixu")
 		assert.Equal(t, r.Header.Get("X-Api-Key"), "ixu")
-		testMethod(t, r, "GET")
-		if r.Method == "GET" {
-
+		testMethod(t, r, http.MethodGet)
+		if r.Method == http.MethodGet {
 			if r.URL.RawQuery == "startup=true" {
 			if r.URL.RawQuery == "startup=true" {
 				w.WriteHeader(http.StatusOK)
 				w.WriteHeader(http.StatusOK)
 				w.Write([]byte(`{"deleted":null,"new":[{"duration":"3h59m55.756182786s","id":4,"origin":"cscli","scenario":"manual 'ban' from '82929df7ee394b73b81252fe3b4e50203yaT2u6nXiaN7Ix9'","scope":"Ip","type":"ban","value":"1.2.3.4"}]}`))
 				w.Write([]byte(`{"deleted":null,"new":[{"duration":"3h59m55.756182786s","id":4,"origin":"cscli","scenario":"manual 'ban' from '82929df7ee394b73b81252fe3b4e50203yaT2u6nXiaN7Ix9'","scope":"Ip","type":"ban","value":"1.2.3.4"}]}`))
@@ -119,8 +118,8 @@ func TestDecisionsStream(t *testing.T) {
 	})
 	})
 	mux.HandleFunc("/decisions", func(w http.ResponseWriter, r *http.Request) {
 	mux.HandleFunc("/decisions", func(w http.ResponseWriter, r *http.Request) {
 		assert.Equal(t, r.Header.Get("X-Api-Key"), "ixu")
 		assert.Equal(t, r.Header.Get("X-Api-Key"), "ixu")
-		testMethod(t, r, "DELETE")
-		if r.Method == "DELETE" {
+		testMethod(t, r, http.MethodDelete)
+		if r.Method == http.MethodDelete {
 			w.WriteHeader(http.StatusOK)
 			w.WriteHeader(http.StatusOK)
 		}
 		}
 	})
 	})

+ 1 - 1
pkg/apiclient/signal.go

@@ -26,7 +26,7 @@ func (s *SignalService) Add(ctx context.Context, signals *models.AddSignalsReque
 	if err != nil {
 	if err != nil {
 		return nil, resp, errors.Wrap(err, "while performing request")
 		return nil, resp, errors.Wrap(err, "while performing request")
 	}
 	}
-	if resp.Response.StatusCode != 200 {
+	if resp.Response.StatusCode != http.StatusOK {
 		log.Warnf("Signal push response : http %s", resp.Response.Status)
 		log.Warnf("Signal push response : http %s", resp.Response.Status)
 	} else {
 	} else {
 		log.Debugf("Signal push response : http %s", resp.Response.Status)
 		log.Debugf("Signal push response : http %s", resp.Response.Status)

+ 1 - 2
pkg/apiserver/apiserver.go

@@ -6,7 +6,6 @@ import (
 	"crypto/x509"
 	"crypto/x509"
 	"fmt"
 	"fmt"
 	"io"
 	"io"
-	"io/ioutil"
 	"net"
 	"net"
 	"net/http"
 	"net/http"
 	"os"
 	"os"
@@ -267,7 +266,7 @@ func (s *APIServer) GetTLSConfig() (*tls.Config, error) {
 	if s.TLS.CACertPath != "" {
 	if s.TLS.CACertPath != "" {
 		if clientAuthType > tls.RequestClientCert {
 		if clientAuthType > tls.RequestClientCert {
 			log.Infof("(tls) Client Auth Type set to %s", clientAuthType.String())
 			log.Infof("(tls) Client Auth Type set to %s", clientAuthType.String())
-			caCert, err = ioutil.ReadFile(s.TLS.CACertPath)
+			caCert, err = os.ReadFile(s.TLS.CACertPath)
 			if err != nil {
 			if err != nil {
 				return nil, errors.Wrap(err, "Error opening cert file")
 				return nil, errors.Wrap(err, "Error opening cert file")
 			}
 			}

+ 2 - 2
pkg/apiserver/controllers/v1/alerts.go

@@ -210,7 +210,7 @@ func (c *Controller) FindAlerts(gctx *gin.Context) {
 
 
 	data := FormatAlerts(result)
 	data := FormatAlerts(result)
 
 
-	if gctx.Request.Method == "HEAD" {
+	if gctx.Request.Method == http.MethodHead {
 		gctx.String(http.StatusOK, "")
 		gctx.String(http.StatusOK, "")
 		return
 		return
 	}
 	}
@@ -232,7 +232,7 @@ func (c *Controller) FindAlertByID(gctx *gin.Context) {
 	}
 	}
 	data := FormatOneAlert(result)
 	data := FormatOneAlert(result)
 
 
-	if gctx.Request.Method == "HEAD" {
+	if gctx.Request.Method == http.MethodHead {
 		gctx.String(http.StatusOK, "")
 		gctx.String(http.StatusOK, "")
 		return
 		return
 	}
 	}

+ 2 - 2
pkg/apiserver/controllers/v1/decisions.go

@@ -70,7 +70,7 @@ func (c *Controller) GetDecision(gctx *gin.Context) {
 		PrometheusBouncersHasEmptyDecision(gctx)
 		PrometheusBouncersHasEmptyDecision(gctx)
 	}
 	}
 
 
-	if gctx.Request.Method == "HEAD" {
+	if gctx.Request.Method == http.MethodHead {
 		gctx.String(http.StatusOK, "")
 		gctx.String(http.StatusOK, "")
 		return
 		return
 	}
 	}
@@ -181,7 +181,7 @@ func (c *Controller) StreamDecision(gctx *gin.Context) {
 				gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
 				gctx.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
 				return
 				return
 			}
 			}
-			if gctx.Request.Method == "HEAD" {
+			if gctx.Request.Method == http.MethodHead {
 				gctx.String(http.StatusOK, "")
 				gctx.String(http.StatusOK, "")
 				return
 				return
 			}
 			}

+ 4 - 3
pkg/apiserver/middlewares/v1/tls_auth.go

@@ -5,9 +5,10 @@ import (
 	"crypto"
 	"crypto"
 	"crypto/x509"
 	"crypto/x509"
 	"fmt"
 	"fmt"
-	"io/ioutil"
+	"io"
 	"net/http"
 	"net/http"
 	"net/url"
 	"net/url"
+	"os"
 	"time"
 	"time"
 
 
 	"github.com/gin-gonic/gin"
 	"github.com/gin-gonic/gin"
@@ -56,7 +57,7 @@ func (ta *TLSAuth) ocspQuery(server string, cert *x509.Certificate, issuer *x509
 		return nil, err
 		return nil, err
 	}
 	}
 	defer httpResponse.Body.Close()
 	defer httpResponse.Body.Close()
-	output, err := ioutil.ReadAll(httpResponse.Body)
+	output, err := io.ReadAll(httpResponse.Body)
 	if err != nil {
 	if err != nil {
 		ta.logger.Error("TLSAuth: cannot read HTTP response from OCSP")
 		ta.logger.Error("TLSAuth: cannot read HTTP response from OCSP")
 		return nil, err
 		return nil, err
@@ -109,7 +110,7 @@ func (ta *TLSAuth) isCRLRevoked(cert *x509.Certificate) (bool, error) {
 		ta.logger.Warn("no crl_path, skipping CRL check")
 		ta.logger.Warn("no crl_path, skipping CRL check")
 		return false, nil
 		return false, nil
 	}
 	}
-	crlContent, err := ioutil.ReadFile(ta.CrlPath)
+	crlContent, err := os.ReadFile(ta.CrlPath)
 	if err != nil {
 	if err != nil {
 		ta.logger.Warnf("could not read CRL file, skipping check: %s", err)
 		ta.logger.Warnf("could not read CRL file, skipping check: %s", err)
 		return false, nil
 		return false, nil

+ 3 - 3
pkg/csconfig/api.go

@@ -4,8 +4,8 @@ import (
 	"crypto/tls"
 	"crypto/tls"
 	"crypto/x509"
 	"crypto/x509"
 	"fmt"
 	"fmt"
-	"io/ioutil"
 	"net"
 	"net"
+	"os"
 	"strings"
 	"strings"
 	"time"
 	"time"
 
 
@@ -45,7 +45,7 @@ type LocalApiClientCfg struct {
 
 
 func (o *OnlineApiClientCfg) Load() error {
 func (o *OnlineApiClientCfg) Load() error {
 	o.Credentials = new(ApiCredentialsCfg)
 	o.Credentials = new(ApiCredentialsCfg)
-	fcontent, err := ioutil.ReadFile(o.CredentialsFilePath)
+	fcontent, err := os.ReadFile(o.CredentialsFilePath)
 	if err != nil {
 	if err != nil {
 		return errors.Wrapf(err, "failed to read api server credentials configuration file '%s'", o.CredentialsFilePath)
 		return errors.Wrapf(err, "failed to read api server credentials configuration file '%s'", o.CredentialsFilePath)
 	}
 	}
@@ -96,7 +96,7 @@ func (l *LocalApiClientCfg) Load() error {
 			return errors.Wrapf(err, "failed to load api client certificate")
 			return errors.Wrapf(err, "failed to load api client certificate")
 		}
 		}
 
 
-		caCert, err := ioutil.ReadFile(l.Credentials.CACertPath)
+		caCert, err := os.ReadFile(l.Credentials.CACertPath)
 		if err != nil {
 		if err != nil {
 			return errors.Wrapf(err, "failed to load cacert")
 			return errors.Wrapf(err, "failed to load cacert")
 		}
 		}

+ 1 - 2
pkg/csconfig/api_test.go

@@ -2,7 +2,6 @@ package csconfig
 
 
 import (
 import (
 	"fmt"
 	"fmt"
-	"io/ioutil"
 	"os"
 	"os"
 	"path/filepath"
 	"path/filepath"
 	"strings"
 	"strings"
@@ -162,7 +161,7 @@ func TestLoadAPIServer(t *testing.T) {
 	}
 	}
 
 
 	config := &Config{}
 	config := &Config{}
-	fcontent, err := ioutil.ReadFile("./tests/config.yaml")
+	fcontent, err := os.ReadFile("./tests/config.yaml")
 	if err != nil {
 	if err != nil {
 		t.Fatalf(err.Error())
 		t.Fatalf(err.Error())
 	}
 	}

+ 1 - 2
pkg/csconfig/console.go

@@ -2,7 +2,6 @@ package csconfig
 
 
 import (
 import (
 	"fmt"
 	"fmt"
-	"io/ioutil"
 	"os"
 	"os"
 
 
 	"github.com/crowdsecurity/crowdsec/pkg/types"
 	"github.com/crowdsecurity/crowdsec/pkg/types"
@@ -37,7 +36,7 @@ func (c *LocalApiServerCfg) LoadConsoleConfig() error {
 		return nil
 		return nil
 	}
 	}
 
 
-	yamlFile, err := ioutil.ReadFile(c.ConsoleConfigPath)
+	yamlFile, err := os.ReadFile(c.ConsoleConfigPath)
 	if err != nil {
 	if err != nil {
 		return fmt.Errorf("reading console config file '%s': %s", c.ConsoleConfigPath, err)
 		return fmt.Errorf("reading console config file '%s': %s", c.ConsoleConfigPath, err)
 	}
 	}

+ 13 - 14
pkg/csplugin/broker_test.go

@@ -4,7 +4,6 @@ package csplugin
 
 
 import (
 import (
 	"encoding/json"
 	"encoding/json"
-	"io/ioutil"
 	"os"
 	"os"
 	"os/exec"
 	"os/exec"
 	"path"
 	"path"
@@ -264,7 +263,7 @@ func TestBrokerInit(t *testing.T) {
 
 
 func readconfig(t *testing.T, path string) ([]byte, PluginConfig) {
 func readconfig(t *testing.T, path string) ([]byte, PluginConfig) {
 	var config PluginConfig
 	var config PluginConfig
-	orig, err := ioutil.ReadFile("tests/notifications/dummy.yaml")
+	orig, err := os.ReadFile("tests/notifications/dummy.yaml")
 	if err != nil {
 	if err != nil {
 		t.Fatalf("unable to read config file %s : %s", path, err)
 		t.Fatalf("unable to read config file %s : %s", path, err)
 	}
 	}
@@ -279,7 +278,7 @@ func writeconfig(t *testing.T, config PluginConfig, path string) {
 	if err != nil {
 	if err != nil {
 		t.Fatalf("unable to marshal config file : %s", err)
 		t.Fatalf("unable to marshal config file : %s", err)
 	}
 	}
-	if err := ioutil.WriteFile(path, data, 0644); err != nil {
+	if err := os.WriteFile(path, data, 0644); err != nil {
 		t.Fatalf("unable to write config file %s : %s", path, err)
 		t.Fatalf("unable to write config file %s : %s", path, err)
 	}
 	}
 }
 }
@@ -311,7 +310,7 @@ func TestBrokerNoThreshold(t *testing.T) {
 	pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}}
 	pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}}
 	time.Sleep(200 * time.Millisecond)
 	time.Sleep(200 * time.Millisecond)
 	//we expect one now
 	//we expect one now
-	content, err := ioutil.ReadFile("./out")
+	content, err := os.ReadFile("./out")
 	if err != nil {
 	if err != nil {
 		log.Errorf("Error reading file: %s", err)
 		log.Errorf("Error reading file: %s", err)
 	}
 	}
@@ -325,7 +324,7 @@ func TestBrokerNoThreshold(t *testing.T) {
 	pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}}
 	pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}}
 	time.Sleep(200 * time.Millisecond)
 	time.Sleep(200 * time.Millisecond)
 	//we expect one again, as we cleaned the file
 	//we expect one again, as we cleaned the file
-	content, err = ioutil.ReadFile("./out")
+	content, err = os.ReadFile("./out")
 	if err != nil {
 	if err != nil {
 		log.Errorf("Error reading file: %s", err)
 		log.Errorf("Error reading file: %s", err)
 	}
 	}
@@ -371,14 +370,14 @@ func TestBrokerRunGroupAndTimeThreshold_TimeFirst(t *testing.T) {
 	assert.NoFileExists(t, "./out")
 	assert.NoFileExists(t, "./out")
 	time.Sleep(1 * time.Second)
 	time.Sleep(1 * time.Second)
 	//after 1 seconds, we should have data
 	//after 1 seconds, we should have data
-	content, err := ioutil.ReadFile("./out")
+	content, err := os.ReadFile("./out")
 	assert.NoError(t, err)
 	assert.NoError(t, err)
 	var alerts []models.Alert
 	var alerts []models.Alert
 	err = json.Unmarshal(content, &alerts)
 	err = json.Unmarshal(content, &alerts)
 	assert.NoError(t, err)
 	assert.NoError(t, err)
 	assert.Equal(t, 3, len(alerts))
 	assert.Equal(t, 3, len(alerts))
 	//restore config
 	//restore config
-	if err := ioutil.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil {
+	if err := os.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil {
 		t.Fatalf("unable to write config file %s", err)
 		t.Fatalf("unable to write config file %s", err)
 	}
 	}
 }
 }
@@ -418,7 +417,7 @@ func TestBrokerRunGroupAndTimeThreshold_CountFirst(t *testing.T) {
 	pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}}
 	pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}}
 	time.Sleep(100 * time.Millisecond)
 	time.Sleep(100 * time.Millisecond)
 	//and now we should
 	//and now we should
-	content, err := ioutil.ReadFile("./out")
+	content, err := os.ReadFile("./out")
 	if err != nil {
 	if err != nil {
 		log.Errorf("Error reading file: %s", err)
 		log.Errorf("Error reading file: %s", err)
 	}
 	}
@@ -427,7 +426,7 @@ func TestBrokerRunGroupAndTimeThreshold_CountFirst(t *testing.T) {
 	assert.NoError(t, err)
 	assert.NoError(t, err)
 	assert.Equal(t, 4, len(alerts))
 	assert.Equal(t, 4, len(alerts))
 	//restore config
 	//restore config
-	if err := ioutil.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil {
+	if err := os.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil {
 		t.Fatalf("unable to write config file %s", err)
 		t.Fatalf("unable to write config file %s", err)
 	}
 	}
 }
 }
@@ -467,7 +466,7 @@ func TestBrokerRunGroupThreshold(t *testing.T) {
 	pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}}
 	pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}}
 	time.Sleep(100 * time.Millisecond)
 	time.Sleep(100 * time.Millisecond)
 	//and now we should
 	//and now we should
-	content, err := ioutil.ReadFile("./out")
+	content, err := os.ReadFile("./out")
 	if err != nil {
 	if err != nil {
 		log.Errorf("Error reading file: %s", err)
 		log.Errorf("Error reading file: %s", err)
 	}
 	}
@@ -476,7 +475,7 @@ func TestBrokerRunGroupThreshold(t *testing.T) {
 	assert.NoError(t, err)
 	assert.NoError(t, err)
 	assert.Equal(t, 4, len(alerts))
 	assert.Equal(t, 4, len(alerts))
 	//restore config
 	//restore config
-	if err := ioutil.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil {
+	if err := os.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil {
 		t.Fatalf("unable to write config file %s", err)
 		t.Fatalf("unable to write config file %s", err)
 	}
 	}
 }
 }
@@ -512,7 +511,7 @@ func TestBrokerRunTimeThreshold(t *testing.T) {
 	assert.NoFileExists(t, "./out")
 	assert.NoFileExists(t, "./out")
 	time.Sleep(1 * time.Second)
 	time.Sleep(1 * time.Second)
 	//and now we should
 	//and now we should
-	content, err := ioutil.ReadFile("./out")
+	content, err := os.ReadFile("./out")
 	if err != nil {
 	if err != nil {
 		log.Errorf("Error reading file: %s", err)
 		log.Errorf("Error reading file: %s", err)
 	}
 	}
@@ -521,7 +520,7 @@ func TestBrokerRunTimeThreshold(t *testing.T) {
 	assert.NoError(t, err)
 	assert.NoError(t, err)
 	assert.Equal(t, 1, len(alerts))
 	assert.Equal(t, 1, len(alerts))
 	//restore config
 	//restore config
-	if err := ioutil.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil {
+	if err := os.WriteFile("tests/notifications/dummy.yaml", raw, 0644); err != nil {
 		t.Fatalf("unable to write config file %s", err)
 		t.Fatalf("unable to write config file %s", err)
 	}
 	}
 }
 }
@@ -553,7 +552,7 @@ func TestBrokerRunSimple(t *testing.T) {
 	pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}}
 	pb.PluginChannel <- ProfileAlert{ProfileID: uint(0), Alert: &models.Alert{}}
 	time.Sleep(time.Millisecond * 200)
 	time.Sleep(time.Millisecond * 200)
 
 
-	content, err := ioutil.ReadFile("./out")
+	content, err := os.ReadFile("./out")
 	if err != nil {
 	if err != nil {
 		log.Errorf("Error reading file: %s", err)
 		log.Errorf("Error reading file: %s", err)
 	}
 	}

+ 2 - 3
pkg/cstest/hubtest.go

@@ -2,7 +2,6 @@ package cstest
 
 
 import (
 import (
 	"fmt"
 	"fmt"
-	"io/ioutil"
 	"os"
 	"os"
 	"os/exec"
 	"os/exec"
 	"path/filepath"
 	"path/filepath"
@@ -58,7 +57,7 @@ func NewHubTest(hubPath string, crowdsecPath string, cscliPath string) (HubTest,
 	}
 	}
 
 
 	hubIndexFile := filepath.Join(hubPath, ".index.json")
 	hubIndexFile := filepath.Join(hubPath, ".index.json")
-	bidx, err := ioutil.ReadFile(hubIndexFile)
+	bidx, err := os.ReadFile(hubIndexFile)
 	if err != nil {
 	if err != nil {
 		return HubTest{}, fmt.Errorf("unable to read index file: %s", err)
 		return HubTest{}, fmt.Errorf("unable to read index file: %s", err)
 	}
 	}
@@ -98,7 +97,7 @@ func (h *HubTest) LoadTestItem(name string) (*HubTestItem, error) {
 }
 }
 
 
 func (h *HubTest) LoadAllTests() error {
 func (h *HubTest) LoadAllTests() error {
-	testsFolder, err := ioutil.ReadDir(h.HubTestPath)
+	testsFolder, err := os.ReadDir(h.HubTestPath)
 	if err != nil {
 	if err != nil {
 		return err
 		return err
 	}
 	}

+ 1 - 2
pkg/cstest/hubtest_item.go

@@ -2,7 +2,6 @@ package cstest
 
 
 import (
 import (
 	"fmt"
 	"fmt"
-	"io/ioutil"
 	"os"
 	"os"
 	"os/exec"
 	"os/exec"
 	"path/filepath"
 	"path/filepath"
@@ -93,7 +92,7 @@ func NewTest(name string, hubTest *HubTest) (*HubTestItem, error) {
 
 
 	// read test configuration file
 	// read test configuration file
 	configFileData := &HubTestItemConfig{}
 	configFileData := &HubTestItemConfig{}
-	yamlFile, err := ioutil.ReadFile(configFilePath)
+	yamlFile, err := os.ReadFile(configFilePath)
 	if err != nil {
 	if err != nil {
 		log.Printf("no config file found in '%s': %v", testPath, err)
 		log.Printf("no config file found in '%s': %v", testPath, err)
 	}
 	}

+ 2 - 2
pkg/cstest/parser_assert.go

@@ -3,7 +3,7 @@ package cstest
 import (
 import (
 	"bufio"
 	"bufio"
 	"fmt"
 	"fmt"
-	"io/ioutil"
+	"io"
 	"os"
 	"os"
 	"regexp"
 	"regexp"
 	"sort"
 	"sort"
@@ -260,7 +260,7 @@ func LoadParserDump(filepath string) (*ParserResults, error) {
 	}
 	}
 	defer dumpData.Close()
 	defer dumpData.Close()
 
 
-	results, err := ioutil.ReadAll(dumpData)
+	results, err := io.ReadAll(dumpData)
 	if err != nil {
 	if err != nil {
 		return nil, err
 		return nil, err
 	}
 	}

+ 3 - 3
pkg/cstest/scenario_assert.go

@@ -3,7 +3,7 @@ package cstest
 import (
 import (
 	"bufio"
 	"bufio"
 	"fmt"
 	"fmt"
-	"io/ioutil"
+	"io"
 	"os"
 	"os"
 	"regexp"
 	"regexp"
 	"sort"
 	"sort"
@@ -237,7 +237,7 @@ func LoadBucketPourDump(filepath string) (*BucketPourInfo, error) {
 	}
 	}
 	defer dumpData.Close()
 	defer dumpData.Close()
 
 
-	results, err := ioutil.ReadAll(dumpData)
+	results, err := io.ReadAll(dumpData)
 	if err != nil {
 	if err != nil {
 		return nil, err
 		return nil, err
 	}
 	}
@@ -258,7 +258,7 @@ func LoadScenarioDump(filepath string) (*BucketResults, error) {
 	}
 	}
 	defer dumpData.Close()
 	defer dumpData.Close()
 
 
-	results, err := ioutil.ReadAll(dumpData)
+	results, err := io.ReadAll(dumpData)
 	if err != nil {
 	if err != nil {
 		return nil, err
 		return nil, err
 	}
 	}

+ 5 - 6
pkg/cstest/utils.go

@@ -2,7 +2,6 @@ package cstest
 
 
 import (
 import (
 	"fmt"
 	"fmt"
-	"io/ioutil"
 	"os"
 	"os"
 	"path/filepath"
 	"path/filepath"
 	"testing"
 	"testing"
@@ -11,12 +10,12 @@ import (
 )
 )
 
 
 func Copy(sourceFile string, destinationFile string) error {
 func Copy(sourceFile string, destinationFile string) error {
-	input, err := ioutil.ReadFile(sourceFile)
+	input, err := os.ReadFile(sourceFile)
 	if err != nil {
 	if err != nil {
 		return err
 		return err
 	}
 	}
 
 
-	err = ioutil.WriteFile(destinationFile, input, 0644)
+	err = os.WriteFile(destinationFile, input, 0644)
 	if err != nil {
 	if err != nil {
 		return err
 		return err
 	}
 	}
@@ -73,7 +72,7 @@ func CopyDir(src string, dest string) error {
 		return err
 		return err
 	}
 	}
 
 
-	files, err := ioutil.ReadDir(src)
+	files, err := os.ReadDir(src)
 	if err != nil {
 	if err != nil {
 		return err
 		return err
 	}
 	}
@@ -91,13 +90,13 @@ func CopyDir(src string, dest string) error {
 
 
 		if !f.IsDir() {
 		if !f.IsDir() {
 
 
-			content, err := ioutil.ReadFile(src + "/" + f.Name())
+			content, err := os.ReadFile(src + "/" + f.Name())
 			if err != nil {
 			if err != nil {
 				return err
 				return err
 
 
 			}
 			}
 
 
-			err = ioutil.WriteFile(dest+"/"+f.Name(), content, 0755)
+			err = os.WriteFile(dest+"/"+f.Name(), content, 0755)
 			if err != nil {
 			if err != nil {
 				return err
 				return err
 
 

+ 1 - 2
pkg/cwhub/cwhub_test.go

@@ -3,7 +3,6 @@ package cwhub
 import (
 import (
 	"fmt"
 	"fmt"
 	"io"
 	"io"
-	"io/ioutil"
 	"net/http"
 	"net/http"
 	"os"
 	"os"
 	"path/filepath"
 	"path/filepath"
@@ -391,7 +390,7 @@ func (t *mockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
 		log.Fatalf("unexpected url :/ %s", req.URL.Path)
 		log.Fatalf("unexpected url :/ %s", req.URL.Path)
 	}
 	}
 
 
-	response.Body = ioutil.NopCloser(strings.NewReader(responseBody))
+	response.Body = io.NopCloser(strings.NewReader(responseBody))
 	return response, nil
 	return response, nil
 }
 }
 
 

+ 4 - 5
pkg/cwhub/download.go

@@ -5,7 +5,6 @@ import (
 	"crypto/sha256"
 	"crypto/sha256"
 	"fmt"
 	"fmt"
 	"io"
 	"io"
-	"io/ioutil"
 	"net/http"
 	"net/http"
 	"os"
 	"os"
 	"path"
 	"path"
@@ -48,11 +47,11 @@ func DownloadHubIdx(hub *csconfig.Hub) ([]byte, error) {
 	if err != nil {
 	if err != nil {
 		return nil, errors.Wrap(err, "failed http request for hub index")
 		return nil, errors.Wrap(err, "failed http request for hub index")
 	}
 	}
-	if resp.StatusCode != 200 {
+	if resp.StatusCode != http.StatusOK {
 		return nil, fmt.Errorf("bad http code %d while requesting %s", resp.StatusCode, req.URL.String())
 		return nil, fmt.Errorf("bad http code %d while requesting %s", resp.StatusCode, req.URL.String())
 	}
 	}
 	defer resp.Body.Close()
 	defer resp.Body.Close()
-	body, err := ioutil.ReadAll(resp.Body)
+	body, err := io.ReadAll(resp.Body)
 	if err != nil {
 	if err != nil {
 		return nil, errors.Wrap(err, "failed to read request answer for hub index")
 		return nil, errors.Wrap(err, "failed to read request answer for hub index")
 	}
 	}
@@ -152,11 +151,11 @@ func DownloadItem(hub *csconfig.Hub, target Item, overwrite bool) (Item, error)
 	if err != nil {
 	if err != nil {
 		return target, errors.Wrap(err, fmt.Sprintf("while downloading %s", req.URL.String()))
 		return target, errors.Wrap(err, fmt.Sprintf("while downloading %s", req.URL.String()))
 	}
 	}
-	if resp.StatusCode != 200 {
+	if resp.StatusCode != http.StatusOK {
 		return target, fmt.Errorf("bad http code %d for %s", resp.StatusCode, req.URL.String())
 		return target, fmt.Errorf("bad http code %d for %s", resp.StatusCode, req.URL.String())
 	}
 	}
 	defer resp.Body.Close()
 	defer resp.Body.Close()
-	body, err := ioutil.ReadAll(resp.Body)
+	body, err := io.ReadAll(resp.Body)
 	if err != nil {
 	if err != nil {
 		return target, errors.Wrap(err, fmt.Sprintf("while reading %s", req.URL.String()))
 		return target, errors.Wrap(err, fmt.Sprintf("while reading %s", req.URL.String()))
 	}
 	}

+ 1 - 2
pkg/cwhub/loader.go

@@ -3,7 +3,6 @@ package cwhub
 import (
 import (
 	"encoding/json"
 	"encoding/json"
 	"fmt"
 	"fmt"
-	"io/ioutil"
 	"os"
 	"os"
 	"path/filepath"
 	"path/filepath"
 	"sort"
 	"sort"
@@ -357,7 +356,7 @@ func GetHubIdx(hub *csconfig.Hub) error {
 		return fmt.Errorf("no configuration found for hub")
 		return fmt.Errorf("no configuration found for hub")
 	}
 	}
 	log.Debugf("loading hub idx %s", hub.HubIndexFile)
 	log.Debugf("loading hub idx %s", hub.HubIndexFile)
-	bidx, err := ioutil.ReadFile(hub.HubIndexFile)
+	bidx, err := os.ReadFile(hub.HubIndexFile)
 	if err != nil {
 	if err != nil {
 		return errors.Wrap(err, "unable to read index file")
 		return errors.Wrap(err, "unable to read index file")
 	}
 	}

+ 2 - 3
pkg/leakybucket/buckets_test.go

@@ -6,7 +6,6 @@ import (
 	"fmt"
 	"fmt"
 	"html/template"
 	"html/template"
 	"io"
 	"io"
-	"io/ioutil"
 	"os"
 	"os"
 	"reflect"
 	"reflect"
 	"sync"
 	"sync"
@@ -44,7 +43,7 @@ func TestBucket(t *testing.T) {
 		}
 		}
 	} else {
 	} else {
 		wg := new(sync.WaitGroup)
 		wg := new(sync.WaitGroup)
-		fds, err := ioutil.ReadDir("./tests/")
+		fds, err := os.ReadDir("./tests/")
 		if err != nil {
 		if err != nil {
 			t.Fatalf("Unable to read test directory : %s", err)
 			t.Fatalf("Unable to read test directory : %s", err)
 		}
 		}
@@ -91,7 +90,7 @@ func testOneBucket(t *testing.T, dir string, tomb *tomb.Tomb) error {
 
 
 	/*load the scenarios*/
 	/*load the scenarios*/
 	stagecfg = dir + "/scenarios.yaml"
 	stagecfg = dir + "/scenarios.yaml"
-	if stagefiles, err = ioutil.ReadFile(stagecfg); err != nil {
+	if stagefiles, err = os.ReadFile(stagecfg); err != nil {
 		t.Fatalf("Failed to load stage file %s : %s", stagecfg, err)
 		t.Fatalf("Failed to load stage file %s : %s", stagecfg, err)
 	}
 	}
 
 

+ 1 - 2
pkg/leakybucket/manager_load.go

@@ -4,7 +4,6 @@ import (
 	"encoding/json"
 	"encoding/json"
 	"fmt"
 	"fmt"
 	"io"
 	"io"
-	"io/ioutil"
 	"os"
 	"os"
 	"path/filepath"
 	"path/filepath"
 	"strings"
 	"strings"
@@ -355,7 +354,7 @@ func LoadBucket(bucketFactory *BucketFactory, tomb *tomb.Tomb) error {
 
 
 func LoadBucketsState(file string, buckets *Buckets, bucketFactories []BucketFactory) error {
 func LoadBucketsState(file string, buckets *Buckets, bucketFactories []BucketFactory) error {
 	var state map[string]Leaky
 	var state map[string]Leaky
-	body, err := ioutil.ReadFile(file)
+	body, err := os.ReadFile(file)
 	if err != nil {
 	if err != nil {
 		return fmt.Errorf("can't state file %s : %s", file, err)
 		return fmt.Errorf("can't state file %s : %s", file, err)
 	}
 	}

+ 1 - 2
pkg/leakybucket/manager_run.go

@@ -3,7 +3,6 @@ package leakybucket
 import (
 import (
 	"encoding/json"
 	"encoding/json"
 	"fmt"
 	"fmt"
-	"io/ioutil"
 	"math"
 	"math"
 	"os"
 	"os"
 	"time"
 	"time"
@@ -87,7 +86,7 @@ func DumpBucketsStateAt(deadline time.Time, outputdir string, buckets *Buckets)
 	if outputdir == "" {
 	if outputdir == "" {
 		return "", fmt.Errorf("empty output dir for dump bucket state")
 		return "", fmt.Errorf("empty output dir for dump bucket state")
 	}
 	}
-	tmpFd, err := ioutil.TempFile(os.TempDir(), "crowdsec-buckets-dump-")
+	tmpFd, err := os.CreateTemp(os.TempDir(), "crowdsec-buckets-dump-")
 	if err != nil {
 	if err != nil {
 		return "", fmt.Errorf("failed to create temp file : %s", err)
 		return "", fmt.Errorf("failed to create temp file : %s", err)
 	}
 	}

+ 4 - 5
pkg/metabase/metabase.go

@@ -6,7 +6,6 @@ import (
 	"context"
 	"context"
 	"fmt"
 	"fmt"
 	"io"
 	"io"
-	"io/ioutil"
 	"net/http"
 	"net/http"
 	"os"
 	"os"
 	"path"
 	"path"
@@ -109,7 +108,7 @@ func NewMetabase(configPath string, containerName string) (*Metabase, error) {
 }
 }
 
 
 func (m *Metabase) LoadConfig(configPath string) error {
 func (m *Metabase) LoadConfig(configPath string) error {
-	yamlFile, err := ioutil.ReadFile(configPath)
+	yamlFile, err := os.ReadFile(configPath)
 	if err != nil {
 	if err != nil {
 		return err
 		return err
 	}
 	}
@@ -303,7 +302,7 @@ func (m *Metabase) DumpConfig(path string) error {
 	if err != nil {
 	if err != nil {
 		return err
 		return err
 	}
 	}
-	return ioutil.WriteFile(path, data, 0600)
+	return os.WriteFile(path, data, 0600)
 }
 }
 
 
 func (m *Metabase) DownloadDatabase(force bool) error {
 func (m *Metabase) DownloadDatabase(force bool) error {
@@ -329,11 +328,11 @@ func (m *Metabase) DownloadDatabase(force bool) error {
 	if err != nil {
 	if err != nil {
 		return fmt.Errorf("failed request to fetch metabase db : %s", err)
 		return fmt.Errorf("failed request to fetch metabase db : %s", err)
 	}
 	}
-	if resp.StatusCode != 200 {
+	if resp.StatusCode != http.StatusOK {
 		return fmt.Errorf("got http %d while requesting metabase db %s, stop", resp.StatusCode, m.InternalDBURL)
 		return fmt.Errorf("got http %d while requesting metabase db %s, stop", resp.StatusCode, m.InternalDBURL)
 	}
 	}
 	defer resp.Body.Close()
 	defer resp.Body.Close()
-	body, err := ioutil.ReadAll(resp.Body)
+	body, err := io.ReadAll(resp.Body)
 	if err != nil {
 	if err != nil {
 		return fmt.Errorf("failed request read while fetching metabase db : %s", err)
 		return fmt.Errorf("failed request read while fetching metabase db : %s", err)
 	}
 	}

+ 3 - 4
pkg/parser/parsing_test.go

@@ -5,7 +5,6 @@ import (
 	"fmt"
 	"fmt"
 	"html/template"
 	"html/template"
 	"io"
 	"io"
-	"io/ioutil"
 	"os"
 	"os"
 	"sort"
 	"sort"
 	"strings"
 	"strings"
@@ -39,7 +38,7 @@ func TestParser(t *testing.T) {
 			t.Fatalf("Test '%s' failed : %s", envSetting, err)
 			t.Fatalf("Test '%s' failed : %s", envSetting, err)
 		}
 		}
 	} else {
 	} else {
-		fds, err := ioutil.ReadDir("./tests/")
+		fds, err := os.ReadDir("./tests/")
 		if err != nil {
 		if err != nil {
 			t.Fatalf("Unable to read test directory : %s", err)
 			t.Fatalf("Unable to read test directory : %s", err)
 		}
 		}
@@ -72,7 +71,7 @@ func BenchmarkParser(t *testing.B) {
 			t.Fatalf("Test '%s' failed : %s", envSetting, err)
 			t.Fatalf("Test '%s' failed : %s", envSetting, err)
 		}
 		}
 	} else {
 	} else {
-		fds, err := ioutil.ReadDir("./tests/")
+		fds, err := os.ReadDir("./tests/")
 		if err != nil {
 		if err != nil {
 			t.Fatalf("Unable to read test directory : %s", err)
 			t.Fatalf("Unable to read test directory : %s", err)
 		}
 		}
@@ -99,7 +98,7 @@ func testOneParser(pctx *UnixParserCtx, ectx EnricherCtx, dir string, b *testing
 	)
 	)
 	log.Warningf("testing %s", dir)
 	log.Warningf("testing %s", dir)
 	parser_cfg_file := fmt.Sprintf("%s/parsers.yaml", dir)
 	parser_cfg_file := fmt.Sprintf("%s/parsers.yaml", dir)
-	cfg, err := ioutil.ReadFile(parser_cfg_file)
+	cfg, err := os.ReadFile(parser_cfg_file)
 	if err != nil {
 	if err != nil {
 		return fmt.Errorf("failed opening %s : %s", parser_cfg_file, err)
 		return fmt.Errorf("failed opening %s : %s", parser_cfg_file, err)
 	}
 	}

+ 2 - 2
pkg/parser/unix_parser.go

@@ -2,7 +2,7 @@ package parser
 
 
 import (
 import (
 	"fmt"
 	"fmt"
-	"io/ioutil"
+	"os"
 	"path"
 	"path"
 
 
 	"github.com/crowdsecurity/crowdsec/pkg/csconfig"
 	"github.com/crowdsecurity/crowdsec/pkg/csconfig"
@@ -31,7 +31,7 @@ type Parsers struct {
 func Init(c map[string]interface{}) (*UnixParserCtx, error) {
 func Init(c map[string]interface{}) (*UnixParserCtx, error) {
 	r := UnixParserCtx{}
 	r := UnixParserCtx{}
 	r.Grok = grokky.NewBase()
 	r.Grok = grokky.NewBase()
-	files, err := ioutil.ReadDir(c["patterns"].(string))
+	files, err := os.ReadDir(c["patterns"].(string))
 	if err != nil {
 	if err != nil {
 		return nil, err
 		return nil, err
 	}
 	}

+ 3 - 3
pkg/types/dataset.go

@@ -2,7 +2,7 @@ package types
 
 
 import (
 import (
 	"fmt"
 	"fmt"
-	"io/ioutil"
+	"io"
 	"net/http"
 	"net/http"
 	"os"
 	"os"
 	"path"
 	"path"
@@ -33,12 +33,12 @@ func downloadFile(url string, destPath string) error {
 	}
 	}
 	defer resp.Body.Close()
 	defer resp.Body.Close()
 
 
-	body, err := ioutil.ReadAll(resp.Body)
+	body, err := io.ReadAll(resp.Body)
 	if err != nil {
 	if err != nil {
 		return err
 		return err
 	}
 	}
 
 
-	if resp.StatusCode != 200 {
+	if resp.StatusCode != http.StatusOK {
 		return fmt.Errorf("download response 'HTTP %d' : %s", resp.StatusCode, string(body))
 		return fmt.Errorf("download response 'HTTP %d' : %s", resp.StatusCode, string(body))
 	}
 	}
 
 

+ 1 - 2
pkg/types/dataset_test.go

@@ -1,7 +1,6 @@
 package types
 package types
 
 
 import (
 import (
-	"io/ioutil"
 	"os"
 	"os"
 	"testing"
 	"testing"
 
 
@@ -29,7 +28,7 @@ func TestDownladFile(t *testing.T) {
 	)
 	)
 	err := downloadFile("https://example.com/xx", examplePath)
 	err := downloadFile("https://example.com/xx", examplePath)
 	assert.NoError(t, err)
 	assert.NoError(t, err)
-	content, err := ioutil.ReadFile(examplePath)
+	content, err := os.ReadFile(examplePath)
 	assert.Equal(t, "example content oneoneone", string(content))
 	assert.Equal(t, "example content oneoneone", string(content))
 	assert.NoError(t, err)
 	assert.NoError(t, err)
 	//bad uri
 	//bad uri

+ 1 - 2
pkg/types/utils.go

@@ -6,7 +6,6 @@ import (
 	"encoding/gob"
 	"encoding/gob"
 	"fmt"
 	"fmt"
 	"io"
 	"io"
-	"io/ioutil"
 	"os"
 	"os"
 	"path/filepath"
 	"path/filepath"
 	"runtime/debug"
 	"runtime/debug"
@@ -100,7 +99,7 @@ func Clone(a, b interface{}) error {
 }
 }
 
 
 func WriteStackTrace(iErr interface{}) string {
 func WriteStackTrace(iErr interface{}) string {
-	tmpfile, err := ioutil.TempFile("", "crowdsec-crash.*.txt")
+	tmpfile, err := os.CreateTemp("", "crowdsec-crash.*.txt")
 	if err != nil {
 	if err != nil {
 		log.Fatal(err)
 		log.Fatal(err)
 	}
 	}

+ 2 - 2
pkg/yamlpatch/merge_test.go

@@ -22,7 +22,7 @@ package yamlpatch
 
 
 import (
 import (
 	"bytes"
 	"bytes"
-	"io/ioutil"
+	"os"
 	"strings"
 	"strings"
 	"testing"
 	"testing"
 
 
@@ -36,7 +36,7 @@ func trimcr(s string) string {
 }
 }
 
 
 func mustRead(t testing.TB, fname string) []byte {
 func mustRead(t testing.TB, fname string) []byte {
-	contents, err := ioutil.ReadFile(fname)
+	contents, err := os.ReadFile(fname)
 	require.NoError(t, err, "failed to read file: %s", fname)
 	require.NoError(t, err, "failed to read file: %s", fname)
 	return contents
 	return contents
 }
 }

+ 2 - 2
plugins/notifications/http/main.go

@@ -5,7 +5,7 @@ import (
 	"context"
 	"context"
 	"crypto/tls"
 	"crypto/tls"
 	"fmt"
 	"fmt"
-	"io/ioutil"
+	"io"
 	"net/http"
 	"net/http"
 	"os"
 	"os"
 
 
@@ -71,7 +71,7 @@ func (s *HTTPPlugin) Notify(ctx context.Context, notification *protobufs.Notific
 	}
 	}
 	defer resp.Body.Close()
 	defer resp.Body.Close()
 
 
-	respData, err := ioutil.ReadAll(resp.Body)
+	respData, err := io.ReadAll(resp.Body)
 	if err != nil {
 	if err != nil {
 		return nil, fmt.Errorf("failed to read response body got error %s", err)
 		return nil, fmt.Errorf("failed to read response body got error %s", err)
 	}
 	}

+ 3 - 3
plugins/notifications/splunk/main.go

@@ -5,7 +5,7 @@ import (
 	"crypto/tls"
 	"crypto/tls"
 	"encoding/json"
 	"encoding/json"
 	"fmt"
 	"fmt"
-	"io/ioutil"
+	"io"
 	"net/http"
 	"net/http"
 	"os"
 	"os"
 	"strings"
 	"strings"
@@ -71,13 +71,13 @@ func (s *Splunk) Notify(ctx context.Context, notification *protobufs.Notificatio
 	}
 	}
 
 
 	if resp.StatusCode != 200 {
 	if resp.StatusCode != 200 {
-		content, err := ioutil.ReadAll(resp.Body)
+		content, err := io.ReadAll(resp.Body)
 		if err != nil {
 		if err != nil {
 			return &protobufs.Empty{}, fmt.Errorf("got non 200 response and failed to read error %s", err)
 			return &protobufs.Empty{}, fmt.Errorf("got non 200 response and failed to read error %s", err)
 		}
 		}
 		return &protobufs.Empty{}, fmt.Errorf("got non 200 response %s", string(content))
 		return &protobufs.Empty{}, fmt.Errorf("got non 200 response %s", string(content))
 	}
 	}
-	respData, err := ioutil.ReadAll(resp.Body)
+	respData, err := io.ReadAll(resp.Body)
 	if err != nil {
 	if err != nil {
 		return &protobufs.Empty{}, fmt.Errorf("failed to read response body got error %s", err)
 		return &protobufs.Empty{}, fmt.Errorf("failed to read response body got error %s", err)
 	}
 	}