diff --git a/.golangci.yaml b/.golangci.yaml index 9df0a1811..68872971a 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -9,6 +9,9 @@ linters: - gosimple - govet - errorlint + - copyloopvar + - intrange + - perfsprint linters-settings: depguard: diff --git a/api/archive/targz.go b/api/archive/targz.go index 01eb17b40..187cfbf5d 100644 --- a/api/archive/targz.go +++ b/api/archive/targz.go @@ -15,7 +15,7 @@ import ( // abosolutePath should be an absolute path to a directory. // Archive name will be .tar.gz and will be placed next to the directory. func TarGzDir(absolutePath string) (string, error) { - targzPath := filepath.Join(absolutePath, fmt.Sprintf("%s.tar.gz", filepath.Base(absolutePath))) + targzPath := filepath.Join(absolutePath, filepath.Base(absolutePath)+".tar.gz") outFile, err := os.Create(targzPath) if err != nil { return "", err diff --git a/api/archive/targz_test.go b/api/archive/targz_test.go index f3694f16f..70e1e2fc4 100644 --- a/api/archive/targz_test.go +++ b/api/archive/targz_test.go @@ -1,7 +1,6 @@ package archive import ( - "fmt" "os" "os/exec" "path" @@ -24,7 +23,7 @@ func listFiles(dir string) []string { return items } -func Test_shouldCreateArhive(t *testing.T) { +func Test_shouldCreateArchive(t *testing.T) { tmpdir := t.TempDir() content := []byte("content") os.WriteFile(path.Join(tmpdir, "outer"), content, 0600) @@ -34,12 +33,11 @@ func Test_shouldCreateArhive(t *testing.T) { gzPath, err := TarGzDir(tmpdir) assert.Nil(t, err) - assert.Equal(t, filepath.Join(tmpdir, fmt.Sprintf("%s.tar.gz", filepath.Base(tmpdir))), gzPath) + assert.Equal(t, filepath.Join(tmpdir, filepath.Base(tmpdir)+".tar.gz"), gzPath) extractionDir := t.TempDir() cmd := exec.Command("tar", "-xzf", gzPath, "-C", extractionDir) - err = cmd.Run() - if err != nil { + if err := cmd.Run(); err != nil { t.Fatal("Failed to extract archive: ", err) } extractedFiles := listFiles(extractionDir) @@ -56,7 +54,7 @@ func Test_shouldCreateArhive(t *testing.T) { wasExtracted("dir/.dotfile") } -func Test_shouldCreateArhiveXXXXX(t *testing.T) { +func Test_shouldCreateArchive2(t *testing.T) { tmpdir := t.TempDir() content := []byte("content") os.WriteFile(path.Join(tmpdir, "outer"), content, 0600) @@ -66,12 +64,11 @@ func Test_shouldCreateArhiveXXXXX(t *testing.T) { gzPath, err := TarGzDir(tmpdir) assert.Nil(t, err) - assert.Equal(t, filepath.Join(tmpdir, fmt.Sprintf("%s.tar.gz", filepath.Base(tmpdir))), gzPath) + assert.Equal(t, filepath.Join(tmpdir, filepath.Base(tmpdir)+".tar.gz"), gzPath) extractionDir := t.TempDir() r, _ := os.Open(gzPath) - ExtractTarGz(r, extractionDir) - if err != nil { + if err := ExtractTarGz(r, extractionDir); err != nil { t.Fatal("Failed to extract archive: ", err) } extractedFiles := listFiles(extractionDir) diff --git a/api/aws/ecr/authorization_token.go b/api/aws/ecr/authorization_token.go index 3e5968a99..234cf4e99 100644 --- a/api/aws/ecr/authorization_token.go +++ b/api/aws/ecr/authorization_token.go @@ -3,7 +3,7 @@ package ecr import ( "context" "encoding/base64" - "fmt" + "errors" "strings" "time" ) @@ -15,7 +15,7 @@ func (s *Service) GetEncodedAuthorizationToken() (token *string, expiry *time.Ti } if len(getAuthorizationTokenOutput.AuthorizationData) == 0 { - err = fmt.Errorf("AuthorizationData is empty") + err = errors.New("AuthorizationData is empty") return } @@ -50,7 +50,7 @@ func (s *Service) ParseAuthorizationToken(token string) (username string, passwo splitToken := strings.Split(token, ":") if len(splitToken) < 2 { - err = fmt.Errorf("invalid ECR authorization token") + err = errors.New("invalid ECR authorization token") return } diff --git a/api/backup/backup.go b/api/backup/backup.go index 823f69bbe..b00577470 100644 --- a/api/backup/backup.go +++ b/api/backup/backup.go @@ -94,7 +94,7 @@ func encrypt(path string, passphrase string) (string, error) { } defer in.Close() - outFileName := fmt.Sprintf("%s.encrypted", path) + outFileName := path + ".encrypted" out, err := os.Create(outFileName) if err != nil { return "", err diff --git a/api/crypto/aes.go b/api/crypto/aes.go index 02046b362..922cdfd75 100644 --- a/api/crypto/aes.go +++ b/api/crypto/aes.go @@ -31,8 +31,7 @@ const ( // AesEncrypt reads from input, encrypts with AES-256 and writes to output. passphrase is used to generate an encryption key func AesEncrypt(input io.Reader, output io.Writer, passphrase []byte) error { - err := aesEncryptGCM(input, output, passphrase) - if err != nil { + if err := aesEncryptGCM(input, output, passphrase); err != nil { return fmt.Errorf("error encrypting file: %w", err) } @@ -142,7 +141,7 @@ func aesDecryptGCM(input io.Reader, passphrase []byte) (io.Reader, error) { } if string(header) != aesGcmHeader { - return nil, fmt.Errorf("invalid header") + return nil, errors.New("invalid header") } // Read salt @@ -194,8 +193,7 @@ func aesDecryptGCM(input io.Reader, passphrase []byte) (io.Reader, error) { return nil, err } - _, err = buf.Write(plaintext) - if err != nil { + if _, err := buf.Write(plaintext); err != nil { return nil, err } diff --git a/api/dataservices/apikeyrepository/apikeyrepository.go b/api/dataservices/apikeyrepository/apikeyrepository.go index 92a4828f3..34547ee50 100644 --- a/api/dataservices/apikeyrepository/apikeyrepository.go +++ b/api/dataservices/apikeyrepository/apikeyrepository.go @@ -21,8 +21,7 @@ type Service struct { // NewService creates a new instance of a service. func NewService(connection portainer.Connection) (*Service, error) { - err := connection.SetServiceName(BucketName) - if err != nil { + if err := connection.SetServiceName(BucketName); err != nil { return nil, err } @@ -62,7 +61,7 @@ func (service *Service) GetAPIKeysByUserID(userID portainer.UserID) ([]portainer // Note: there is a 1-to-1 mapping of api-key and digest func (service *Service) GetAPIKeyByDigest(digest string) (*portainer.APIKey, error) { var k *portainer.APIKey - stop := fmt.Errorf("ok") + stop := errors.New("ok") err := service.Connection.GetAll( BucketName, &portainer.APIKey{}, diff --git a/api/dataservices/resourcecontrol/resourcecontrol.go b/api/dataservices/resourcecontrol/resourcecontrol.go index 7f943022b..482170090 100644 --- a/api/dataservices/resourcecontrol/resourcecontrol.go +++ b/api/dataservices/resourcecontrol/resourcecontrol.go @@ -48,7 +48,7 @@ func (service *Service) Tx(tx portainer.Transaction) ServiceTx { // if no ResourceControl was found. func (service *Service) ResourceControlByResourceIDAndType(resourceID string, resourceType portainer.ResourceControlType) (*portainer.ResourceControl, error) { var resourceControl *portainer.ResourceControl - stop := fmt.Errorf("ok") + stop := errors.New("ok") err := service.Connection.GetAll( BucketName, &portainer.ResourceControl{}, diff --git a/api/dataservices/resourcecontrol/tx.go b/api/dataservices/resourcecontrol/tx.go index 0bb16f261..ea42f3f4b 100644 --- a/api/dataservices/resourcecontrol/tx.go +++ b/api/dataservices/resourcecontrol/tx.go @@ -19,7 +19,7 @@ type ServiceTx struct { // if no ResourceControl was found. func (service ServiceTx) ResourceControlByResourceIDAndType(resourceID string, resourceType portainer.ResourceControlType) (*portainer.ResourceControl, error) { var resourceControl *portainer.ResourceControl - stop := fmt.Errorf("ok") + stop := errors.New("ok") err := service.Tx.GetAll( BucketName, &portainer.ResourceControl{}, diff --git a/api/datastore/backup_test.go b/api/datastore/backup_test.go index 98c8e5829..6b7d35bb9 100644 --- a/api/datastore/backup_test.go +++ b/api/datastore/backup_test.go @@ -1,7 +1,6 @@ package datastore import ( - "fmt" "testing" portainer "github.com/portainer/portainer/api" @@ -33,7 +32,7 @@ func TestStoreCreation(t *testing.T) { func TestBackup(t *testing.T) { _, store := MustNewTestStore(t, true, true) backupFileName := store.backupFilename() - t.Run(fmt.Sprintf("Backup should create %s", backupFileName), func(t *testing.T) { + t.Run("Backup should create "+backupFileName, func(t *testing.T) { v := models.Version{ Edition: int(portainer.PortainerCE), SchemaVersion: portainer.APIVersion, diff --git a/api/docker/images/image.go b/api/docker/images/image.go index 8fbd910c3..55e72aff0 100644 --- a/api/docker/images/image.go +++ b/api/docker/images/image.go @@ -142,23 +142,23 @@ func (i *Image) hubLink() (string, error) { prefix = "_" path = strings.Replace(i.Path, "library/", "", 1) } - return fmt.Sprintf("https://hub.docker.com/%s/%s", prefix, path), nil + return "https://hub.docker.com/" + prefix + "/" + path, nil case "docker.bintray.io", "jfrog-docker-reg2.bintray.io": - return fmt.Sprintf("https://bintray.com/jfrog/reg2/%s", strings.ReplaceAll(i.Path, "/", "%3A")), nil + return "https://bintray.com/jfrog/reg2/" + strings.ReplaceAll(i.Path, "/", "%3A"), nil case "docker.pkg.github.com": - return fmt.Sprintf("https://github.com/%s/packages", filepath.ToSlash(filepath.Dir(i.Path))), nil + return "https://github.com/" + filepath.ToSlash(filepath.Dir(i.Path)) + "/packages", nil case "gcr.io": - return fmt.Sprintf("https://%s/%s", i.Domain, i.Path), nil + return "https://" + i.Domain + "/" + i.Path, nil case "ghcr.io": ref := strings.Split(i.Path, "/") ghUser, ghPackage := ref[0], ref[1] - return fmt.Sprintf("https://github.com/users/%s/packages/container/package/%s", ghUser, ghPackage), nil + return "https://github.com/users/" + ghUser + "/packages/container/package/" + ghPackage, nil case "quay.io": - return fmt.Sprintf("https://quay.io/repository/%s", i.Path), nil + return "https://quay.io/repository/" + i.Path, nil case "registry.access.redhat.com": - return fmt.Sprintf("https://access.redhat.com/containers/#/registry.access.redhat.com/%s", i.Path), nil + return "https://access.redhat.com/containers/#/registry.access.redhat.com/" + i.Path, nil case "registry.gitlab.com": - return fmt.Sprintf("https://gitlab.com/%s/container_registry", i.Path), nil + return "https://gitlab.com/" + i.Path + "/container_registry", nil default: return "", nil } diff --git a/api/docker/images/ref.go b/api/docker/images/ref.go index a52de1c44..50b82f512 100644 --- a/api/docker/images/ref.go +++ b/api/docker/images/ref.go @@ -1,7 +1,6 @@ package images import ( - "fmt" "strings" "github.com/containers/image/v5/docker" @@ -10,7 +9,7 @@ import ( func ParseReference(imageStr string) (types.ImageReference, error) { if !strings.HasPrefix(imageStr, "//") { - imageStr = fmt.Sprintf("//%s", imageStr) + imageStr = "//" + imageStr } return docker.ParseReference(imageStr) } diff --git a/api/exec/compose_stack_integration_test.go b/api/exec/compose_stack_integration_test.go index fb933cb65..f82e26430 100644 --- a/api/exec/compose_stack_integration_test.go +++ b/api/exec/compose_stack_integration_test.go @@ -2,7 +2,6 @@ package exec import ( "context" - "fmt" "os" "os/exec" "path/filepath" @@ -60,8 +59,7 @@ func Test_UpAndDown(t *testing.T) { ctx := context.TODO() - err = w.Up(ctx, stack, endpoint, portainer.ComposeUpOptions{}) - if err != nil { + if err := w.Up(ctx, stack, endpoint, portainer.ComposeUpOptions{}); err != nil { t.Fatalf("Error calling docker-compose up: %s", err) } @@ -69,8 +67,7 @@ func Test_UpAndDown(t *testing.T) { t.Fatal("container should exist") } - err = w.Down(ctx, stack, endpoint) - if err != nil { + if err := w.Down(ctx, stack, endpoint); err != nil { t.Fatalf("Error calling docker-compose down: %s", err) } @@ -80,7 +77,7 @@ func Test_UpAndDown(t *testing.T) { } func containerExists(containerName string) bool { - cmd := exec.Command("docker", "ps", "-a", "-f", fmt.Sprintf("name=%s", containerName)) + cmd := exec.Command("docker", "ps", "-a", "-f", "name="+containerName) out, err := cmd.Output() if err != nil { diff --git a/api/exec/kubernetes_deploy.go b/api/exec/kubernetes_deploy.go index 50ccfbb07..1941a6513 100644 --- a/api/exec/kubernetes_deploy.go +++ b/api/exec/kubernetes_deploy.go @@ -71,7 +71,7 @@ func (deployer *KubernetesDeployer) getToken(userID portainer.UserID, endpoint * } if token == "" { - return "", fmt.Errorf("can not get a valid user service account token") + return "", errors.New("can not get a valid user service account token") } return token, nil diff --git a/api/filesystem/filesystem.go b/api/filesystem/filesystem.go index b5b1b4ec8..df49a2706 100644 --- a/api/filesystem/filesystem.go +++ b/api/filesystem/filesystem.go @@ -8,6 +8,7 @@ import ( "io" "os" "path/filepath" + "strconv" "strings" portainer "github.com/portainer/portainer/api" @@ -357,7 +358,7 @@ func (service *Service) RollbackStackFile(stackIdentifier, fileName string) erro stackStorePath := JoinPaths(ComposeStorePath, stackIdentifier) composeFilePath := JoinPaths(stackStorePath, fileName) path := service.wrapFileStore(composeFilePath) - backupPath := fmt.Sprintf("%s.bak", path) + backupPath := path + ".bak" exists, err := service.FileExists(backupPath) if err != nil { @@ -381,12 +382,12 @@ func (service *Service) RollbackStackFile(stackIdentifier, fileName string) erro func (service *Service) RollbackStackFileByVersion(stackIdentifier string, version int, fileName string) error { versionStr := "" if version != 0 { - versionStr = fmt.Sprintf("v%d", version) + versionStr = "v" + strconv.Itoa(version) } stackStorePath := JoinPaths(ComposeStorePath, stackIdentifier, versionStr) composeFilePath := JoinPaths(stackStorePath, fileName) path := service.wrapFileStore(composeFilePath) - backupPath := fmt.Sprintf("%s.bak", path) + backupPath := path + ".bak" exists, err := service.FileExists(backupPath) if err != nil { @@ -671,7 +672,7 @@ func (service *Service) createFileInStore(filePath string, r io.Reader) error { // createBackupFileInStore makes a copy in the file store. func (service *Service) createBackupFileInStore(filePath string) error { path := service.wrapFileStore(filePath) - backupPath := fmt.Sprintf("%s.bak", path) + backupPath := path + ".bak" return service.Copy(path, backupPath, true) } @@ -679,7 +680,7 @@ func (service *Service) createBackupFileInStore(filePath string) error { // removeBackupFileInStore removes the copy in the file store. func (service *Service) removeBackupFileInStore(filePath string) error { path := service.wrapFileStore(filePath) - backupPath := fmt.Sprintf("%s.bak", path) + backupPath := path + ".bak" exists, err := service.FileExists(backupPath) if err != nil { @@ -799,7 +800,7 @@ func (service *Service) StoreEdgeJobTaskLogFileFromBytes(edgeJobID, taskID strin return err } - filePath := JoinPaths(edgeJobStorePath, fmt.Sprintf("logs_%s", taskID)) + filePath := JoinPaths(edgeJobStorePath, "logs_"+taskID) r := bytes.NewReader(data) return service.createFileInStore(filePath, r) } @@ -990,7 +991,7 @@ func MoveDirectory(originalPath, newPath string, overwriteTargetPath bool) error if alreadyExists { if !overwriteTargetPath { - return fmt.Errorf("Target path already exists") + return errors.New("Target path already exists") } if err = os.RemoveAll(newPath); err != nil { diff --git a/api/filesystem/serialize.go b/api/filesystem/serialize.go index 084b82db9..821277038 100644 --- a/api/filesystem/serialize.go +++ b/api/filesystem/serialize.go @@ -51,7 +51,7 @@ func FilterDirForEntryFile(dirEntries []DirEntry, entryFile string) []DirEntry { // FilterDirForCompatibility returns the content of the entry file if agent version is less than 2.19.0 func FilterDirForCompatibility(dirEntries []DirEntry, entryFilePath, agentVersion string) (string, error) { - if semver.Compare(fmt.Sprintf("v%s", agentVersion), "v2.19.0") == -1 { + if semver.Compare("v"+agentVersion, "v2.19.0") == -1 { for _, dirEntry := range dirEntries { if dirEntry.IsFile { if dirEntry.Name == entryFilePath { diff --git a/api/filesystem/serialize_per_dev_configs.go b/api/filesystem/serialize_per_dev_configs.go index 121c00710..c9d02ad0d 100644 --- a/api/filesystem/serialize_per_dev_configs.go +++ b/api/filesystem/serialize_per_dev_configs.go @@ -116,7 +116,7 @@ func shouldIncludeFile(dirEntry DirEntry, deviceName, configPath string) bool { filterEqual := filepath.Join(configPath, deviceName) // example: A/B/C// - filterPrefix := fmt.Sprintf("%s.", filterEqual) + filterPrefix := filterEqual + "." // include file entries: A/B/C/ or A/B/C/.* return dirEntry.Name == filterEqual || strings.HasPrefix(dirEntry.Name, filterPrefix) diff --git a/api/git/backup.go b/api/git/backup.go index 465a05af1..286b51876 100644 --- a/api/git/backup.go +++ b/api/git/backup.go @@ -1,12 +1,11 @@ package git import ( - "fmt" - - "github.com/pkg/errors" portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/filesystem" gittypes "github.com/portainer/portainer/api/git/types" + + "github.com/pkg/errors" "github.com/rs/zerolog/log" ) @@ -25,32 +24,28 @@ type CloneOptions struct { } func CloneWithBackup(gitService portainer.GitService, fileService portainer.FileService, options CloneOptions) (clean func(), err error) { - backupProjectPath := fmt.Sprintf("%s-old", options.ProjectPath) + backupProjectPath := options.ProjectPath + "-old" cleanUp := false cleanFn := func() { if !cleanUp { return } - err = fileService.RemoveDirectory(backupProjectPath) - if err != nil { + if err := fileService.RemoveDirectory(backupProjectPath); err != nil { log.Warn().Err(err).Msg("unable to remove git repository directory") } } - err = filesystem.MoveDirectory(options.ProjectPath, backupProjectPath, true) - if err != nil { + if err := filesystem.MoveDirectory(options.ProjectPath, backupProjectPath, true); err != nil { return cleanFn, errors.WithMessage(err, "Unable to move git repository directory") } cleanUp = true - err = gitService.CloneRepository(options.ProjectPath, options.URL, options.ReferenceName, options.Username, options.Password, options.TLSSkipVerify) - if err != nil { + if err := gitService.CloneRepository(options.ProjectPath, options.URL, options.ReferenceName, options.Username, options.Password, options.TLSSkipVerify); err != nil { cleanUp = false - restoreError := filesystem.MoveDirectory(backupProjectPath, options.ProjectPath, false) - if restoreError != nil { - log.Warn().Err(restoreError).Msg("failed restoring backup folder") + if err := filesystem.MoveDirectory(backupProjectPath, options.ProjectPath, false); err != nil { + log.Warn().Err(err).Msg("failed restoring backup folder") } if errors.Is(err, gittypes.ErrAuthenticationFailure) { diff --git a/api/hostmanagement/openamt/configCIRA.go b/api/hostmanagement/openamt/configCIRA.go index f76c8938a..8e57070dd 100644 --- a/api/hostmanagement/openamt/configCIRA.go +++ b/api/hostmanagement/openamt/configCIRA.go @@ -123,7 +123,7 @@ func (service *Service) getCIRACertificate(configuration portainer.OpenAMTConfig if err != nil { return "", err } - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", configuration.MPSToken)) + req.Header.Set("Authorization", "Bearer "+configuration.MPSToken) response, err := service.httpsClient.Do(req) if err != nil { diff --git a/api/hostmanagement/openamt/openamt.go b/api/hostmanagement/openamt/openamt.go index 82fbeafbf..b27b78878 100644 --- a/api/hostmanagement/openamt/openamt.go +++ b/api/hostmanagement/openamt/openamt.go @@ -97,7 +97,7 @@ func (service *Service) executeSaveRequest(method string, url string, token stri return nil, err } req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) + req.Header.Set("Authorization", "Bearer "+token) response, err := service.httpsClient.Do(req) if err != nil { @@ -128,7 +128,7 @@ func (service *Service) executeGetRequest(url string, token string) ([]byte, err } req.Header.Set("Content-Type", "application/json") - req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) + req.Header.Set("Authorization", "Bearer "+token) response, err := service.httpsClient.Do(req) if err != nil { diff --git a/api/http/handler/backup/backup.go b/api/http/handler/backup/backup.go index 108c94096..26f1a3eaf 100644 --- a/api/http/handler/backup/backup.go +++ b/api/http/handler/backup/backup.go @@ -1,7 +1,6 @@ package backup import ( - "fmt" "net/http" "os" "path/filepath" @@ -37,8 +36,7 @@ func (p *backupPayload) Validate(r *http.Request) error { // @router /backup [post] func (h *Handler) backup(w http.ResponseWriter, r *http.Request) *httperror.HandlerError { var payload backupPayload - err := request.DecodeAndValidateJSONPayload(r, &payload) - if err != nil { + if err := request.DecodeAndValidateJSONPayload(r, &payload); err != nil { return httperror.BadRequest("Invalid request payload", err) } @@ -48,7 +46,7 @@ func (h *Handler) backup(w http.ResponseWriter, r *http.Request) *httperror.Hand } defer os.RemoveAll(filepath.Dir(archivePath)) - w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fmt.Sprintf("portainer-backup_%s", filepath.Base(archivePath)))) + w.Header().Set("Content-Disposition", "attachment; filename=portainer-backup_"+filepath.Base(archivePath)) http.ServeFile(w, r, archivePath) return nil diff --git a/api/http/handler/customtemplates/customtemplate_create.go b/api/http/handler/customtemplates/customtemplate_create.go index 22bff40bc..a5b6ecdee 100644 --- a/api/http/handler/customtemplates/customtemplate_create.go +++ b/api/http/handler/customtemplates/customtemplate_create.go @@ -2,7 +2,6 @@ package customtemplates import ( "errors" - "fmt" "net/http" "os" "regexp" @@ -52,15 +51,13 @@ func (handler *Handler) customTemplateCreate(w http.ResponseWriter, r *http.Requ } } - err = handler.DataStore.CustomTemplate().Create(customTemplate) - if err != nil { + if err := handler.DataStore.CustomTemplate().Create(customTemplate); err != nil { return httperror.InternalServerError("Unable to create custom template", err) } resourceControl := authorization.NewPrivateResourceControl(strconv.Itoa(int(customTemplate.ID)), portainer.CustomTemplateResourceControl, tokenData.ID) - err = handler.DataStore.ResourceControl().Create(resourceControl) - if err != nil { + if err := handler.DataStore.ResourceControl().Create(resourceControl); err != nil { return httperror.InternalServerError("Unable to persist resource control inside the database", err) } @@ -155,8 +152,7 @@ func isValidNote(note string) bool { // @router /custom_templates/create/string [post] func (handler *Handler) createCustomTemplateFromFileContent(r *http.Request) (*portainer.CustomTemplate, error) { var payload customTemplateFromFileContentPayload - err := request.DecodeAndValidateJSONPayload(r, &payload) - if err != nil { + if err := request.DecodeAndValidateJSONPayload(r, &payload); err != nil { return nil, err } @@ -272,8 +268,7 @@ func (payload *customTemplateFromGitRepositoryPayload) Validate(r *http.Request) // @router /custom_templates/create/repository [post] func (handler *Handler) createCustomTemplateFromGitRepository(r *http.Request) (*portainer.CustomTemplate, error) { var payload customTemplateFromGitRepositoryPayload - err := request.DecodeAndValidateJSONPayload(r, &payload) - if err != nil { + if err := request.DecodeAndValidateJSONPayload(r, &payload); err != nil { return nil, err } @@ -423,12 +418,10 @@ func (payload *customTemplateFromFileUploadPayload) Validate(r *http.Request) er varsString, _ := request.RetrieveMultiPartFormValue(r, "Variables", true) if varsString != "" { - err = json.Unmarshal([]byte(varsString), &payload.Variables) - if err != nil { + if err := json.Unmarshal([]byte(varsString), &payload.Variables); err != nil { return errors.New("Invalid variables. Ensure that the variables are valid JSON") } - err = validateVariablesDefinitions(payload.Variables) - if err != nil { + if err := validateVariablesDefinitions(payload.Variables); err != nil { return err } } @@ -462,8 +455,7 @@ func (payload *customTemplateFromFileUploadPayload) Validate(r *http.Request) er // @router /custom_templates/create/file [post] func (handler *Handler) createCustomTemplateFromFileUpload(r *http.Request) (*portainer.CustomTemplate, error) { payload := &customTemplateFromFileUploadPayload{} - err := payload.Validate(r) - if err != nil { + if err := payload.Validate(r); err != nil { return nil, err } @@ -513,6 +505,5 @@ func deprecatedCustomTemplateCreateUrlParser(w http.ResponseWriter, r *http.Requ return "", httperror.BadRequest("Invalid query parameter: method", err) } - url := fmt.Sprintf("/custom_templates/create/%s", method) - return url, nil + return "/custom_templates/create/" + method, nil } diff --git a/api/http/handler/customtemplates/customtemplate_git_fetch.go b/api/http/handler/customtemplates/customtemplate_git_fetch.go index 59da73b1f..ef808257f 100644 --- a/api/http/handler/customtemplates/customtemplate_git_fetch.go +++ b/api/http/handler/customtemplates/customtemplate_git_fetch.go @@ -1,7 +1,6 @@ package customtemplates import ( - "fmt" "net/http" "os" "sync" @@ -80,8 +79,7 @@ func (handler *Handler) customTemplateGitFetch(w http.ResponseWriter, r *http.Re if customTemplate.GitConfig.ConfigHash != commitHash { customTemplate.GitConfig.ConfigHash = commitHash - err = handler.DataStore.CustomTemplate().Update(customTemplate.ID, customTemplate) - if err != nil { + if err := handler.DataStore.CustomTemplate().Update(customTemplate.ID, customTemplate); err != nil { return httperror.InternalServerError("Unable to persist custom template changes inside the database", err) } } @@ -100,9 +98,8 @@ func backupCustomTemplate(projectPath string) (string, error) { return "", err } - backupPath := fmt.Sprintf("%s-backup", projectPath) - err = os.Rename(projectPath, backupPath) - if err != nil { + backupPath := projectPath + "-backup" + if err := os.Rename(projectPath, backupPath); err != nil { return "", err } @@ -110,8 +107,7 @@ func backupCustomTemplate(projectPath string) (string, error) { } func rollbackCustomTemplate(backupPath, projectPath string) error { - err := os.RemoveAll(projectPath) - if err != nil { + if err := os.RemoveAll(projectPath); err != nil { return err } diff --git a/api/http/handler/edgejobs/edgejob_create.go b/api/http/handler/edgejobs/edgejob_create.go index 6c019bd62..0446c107b 100644 --- a/api/http/handler/edgejobs/edgejob_create.go +++ b/api/http/handler/edgejobs/edgejob_create.go @@ -2,7 +2,6 @@ package edgejobs import ( "errors" - "fmt" "maps" "net/http" "strconv" @@ -300,5 +299,5 @@ func deprecatedEdgeJobCreateUrlParser(w http.ResponseWriter, r *http.Request) (s return "", httperror.BadRequest("Invalid query parameter: method. Valid values are: file or string", err) } - return fmt.Sprintf("/edge_jobs/create/%s", method), nil + return "/edge_jobs/create/" + method, nil } diff --git a/api/http/handler/edgestacks/edgestack_create.go b/api/http/handler/edgestacks/edgestack_create.go index 5fdc43590..cad8a0065 100644 --- a/api/http/handler/edgestacks/edgestack_create.go +++ b/api/http/handler/edgestacks/edgestack_create.go @@ -1,7 +1,6 @@ package edgestacks import ( - "fmt" "net/http" portainer "github.com/portainer/portainer/api" @@ -78,5 +77,5 @@ func deprecatedEdgeStackCreateUrlParser(w http.ResponseWriter, r *http.Request) return "", httperror.BadRequest("Invalid query parameter: method. Valid values are: file or string", err) } - return fmt.Sprintf("/edge_stacks/create/%s", method), nil + return "/edge_stacks/create/" + method, nil } diff --git a/api/http/handler/edgestacks/edgestack_create_git.go b/api/http/handler/edgestacks/edgestack_create_git.go index a1992db06..3e0b701b9 100644 --- a/api/http/handler/edgestacks/edgestack_create_git.go +++ b/api/http/handler/edgestacks/edgestack_create_git.go @@ -133,7 +133,7 @@ func (handler *Handler) storeManifestFromGitRepository(tx dataservices.DataStore return "", "", "", fmt.Errorf("unable to check for existence of non fitting environments: %w", err) } if hasWrongType { - return "", "", "", fmt.Errorf("edge stack with config do not match the environment type") + return "", "", "", errors.New("edge stack with config do not match the environment type") } projectPath = handler.FileService.GetEdgeStackProjectPath(stackFolder) diff --git a/api/http/handler/edgestacks/edgestack_create_string.go b/api/http/handler/edgestacks/edgestack_create_string.go index 81f24fe95..071c73c19 100644 --- a/api/http/handler/edgestacks/edgestack_create_string.go +++ b/api/http/handler/edgestacks/edgestack_create_string.go @@ -92,7 +92,7 @@ func (handler *Handler) storeFileContent(tx dataservices.DataStoreTx, stackFolde return "", "", "", fmt.Errorf("unable to check for existence of non fitting environments: %w", err) } if hasWrongType { - return "", "", "", fmt.Errorf("edge stack with config do not match the environment type") + return "", "", "", errors.New("edge stack with config do not match the environment type") } if deploymentType == portainer.EdgeStackDeploymentCompose { @@ -107,7 +107,6 @@ func (handler *Handler) storeFileContent(tx dataservices.DataStoreTx, stackFolde } if deploymentType == portainer.EdgeStackDeploymentKubernetes { - manifestPath = filesystem.ManifestFileDefaultName projectPath, err := handler.FileService.StoreEdgeStackFileFromBytes(stackFolder, manifestPath, fileContent) diff --git a/api/http/handler/edgestacks/edgestack_create_test.go b/api/http/handler/edgestacks/edgestack_create_test.go index 850dfa31a..739d727ab 100644 --- a/api/http/handler/edgestacks/edgestack_create_test.go +++ b/api/http/handler/edgestacks/edgestack_create_test.go @@ -207,7 +207,7 @@ func TestCreateWithInvalidPayload(t *testing.T) { r := bytes.NewBuffer(jsonPayload) // Create EdgeStack - req, err := http.NewRequest(http.MethodPost, fmt.Sprintf("/edge_stacks/create/%s", tc.Method), r) + req, err := http.NewRequest(http.MethodPost, "/edge_stacks/create/"+tc.Method, r) if err != nil { t.Fatal("request error:", err) } diff --git a/api/http/handler/endpoints/endpoint_delete.go b/api/http/handler/endpoints/endpoint_delete.go index 0ae0eb920..0add2ccdf 100644 --- a/api/http/handler/endpoints/endpoint_delete.go +++ b/api/http/handler/endpoints/endpoint_delete.go @@ -2,7 +2,6 @@ package endpoints import ( "errors" - "fmt" "net/http" "slices" "strconv" @@ -33,7 +32,7 @@ type endpointDeleteBatchPartialResponse struct { func (payload *endpointDeleteBatchPayload) Validate(r *http.Request) error { if payload == nil || len(payload.Endpoints) == 0 { - return fmt.Errorf("invalid request payload. You must provide a list of environments to delete") + return errors.New("invalid request payload. You must provide a list of environments to delete") } return nil diff --git a/api/http/handler/endpoints/endpoint_dockerhub_status.go b/api/http/handler/endpoints/endpoint_dockerhub_status.go index 4207d7735..7427a8750 100644 --- a/api/http/handler/endpoints/endpoint_dockerhub_status.go +++ b/api/http/handler/endpoints/endpoint_dockerhub_status.go @@ -137,7 +137,7 @@ func getDockerHubLimits(httpClient *client.HTTPClient, token string) (*dockerhub return nil, err } - req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", token)) + req.Header.Add("Authorization", "Bearer "+token) resp, err := httpClient.Do(req) if err != nil { diff --git a/api/http/handler/endpoints/endpoint_list_test.go b/api/http/handler/endpoints/endpoint_list_test.go index 94a058875..90b74c4ee 100644 --- a/api/http/handler/endpoints/endpoint_list_test.go +++ b/api/http/handler/endpoints/endpoint_list_test.go @@ -202,7 +202,7 @@ func setupEndpointListHandler(t *testing.T, endpoints []portainer.Endpoint) *Han } func buildEndpointListRequest(query string) *http.Request { - req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/endpoints?%s", query), nil) + req := httptest.NewRequest(http.MethodGet, "/endpoints?"+query, nil) ctx := security.StoreTokenData(req, &portainer.TokenData{ID: 1, Username: "admin", Role: 1}) req = req.WithContext(ctx) diff --git a/api/http/handler/endpoints/filter.go b/api/http/handler/endpoints/filter.go index 96fc53198..df230f99e 100644 --- a/api/http/handler/endpoints/filter.go +++ b/api/http/handler/endpoints/filter.go @@ -557,7 +557,7 @@ func filter(endpoints []portainer.Endpoint, predicate func(endpoint portainer.En } func getArrayQueryParameter(r *http.Request, parameter string) []string { - list, exists := r.Form[fmt.Sprintf("%s[]", parameter)] + list, exists := r.Form[parameter+"[]"] if !exists { list = []string{} } @@ -576,7 +576,6 @@ func getNumberArrayQueryParameter[T ~int](r *http.Request, parameter string) ([] number, err := strconv.Atoi(item) if err != nil { return nil, errors.Wrapf(err, "Unable to parse parameter %s", parameter) - } result = append(result, T(number)) diff --git a/api/http/handler/helm/helm_delete_test.go b/api/http/handler/helm/helm_delete_test.go index bfe4f66ae..7d676fab9 100644 --- a/api/http/handler/helm/helm_delete_test.go +++ b/api/http/handler/helm/helm_delete_test.go @@ -1,7 +1,6 @@ package helm import ( - "fmt" "net/http" "net/http/httptest" "testing" @@ -46,7 +45,7 @@ func Test_helmDelete(t *testing.T) { h.helmPackageManager.Install(options) t.Run("helmDelete succeeds with admin user", func(t *testing.T) { - req := httptest.NewRequest(http.MethodDelete, fmt.Sprintf("/1/kubernetes/helm/%s", options.Name), nil) + req := httptest.NewRequest(http.MethodDelete, "/1/kubernetes/helm/"+options.Name, nil) ctx := security.StoreTokenData(req, &portainer.TokenData{ID: 1, Username: "admin", Role: 1}) req = req.WithContext(ctx) testhelpers.AddTestSecurityCookie(req, "Bearer dummytoken") diff --git a/api/http/handler/helm/helm_repo_search_test.go b/api/http/handler/helm/helm_repo_search_test.go index 5f9cec615..5fde5e642 100644 --- a/api/http/handler/helm/helm_repo_search_test.go +++ b/api/http/handler/helm/helm_repo_search_test.go @@ -1,7 +1,6 @@ package helm import ( - "fmt" "io" "net/http" "net/http/httptest" @@ -26,7 +25,7 @@ func Test_helmRepoSearch(t *testing.T) { for _, repo := range repos { t.Run(repo, func(t *testing.T) { repoUrlEncoded := url.QueryEscape(repo) - req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/templates/helm?repo=%s", repoUrlEncoded), nil) + req := httptest.NewRequest(http.MethodGet, "/templates/helm?repo="+repoUrlEncoded, nil) rr := httptest.NewRecorder() h.ServeHTTP(rr, req) @@ -41,7 +40,7 @@ func Test_helmRepoSearch(t *testing.T) { t.Run("fails on invalid URL", func(t *testing.T) { repo := "abc.com" repoUrlEncoded := url.QueryEscape(repo) - req := httptest.NewRequest(http.MethodGet, fmt.Sprintf("/templates/helm?repo=%s", repoUrlEncoded), nil) + req := httptest.NewRequest(http.MethodGet, "/templates/helm?repo="+repoUrlEncoded, nil) rr := httptest.NewRecorder() h.ServeHTTP(rr, req) diff --git a/api/http/handler/hostmanagement/openamt/amtactivation.go b/api/http/handler/hostmanagement/openamt/amtactivation.go index 204ed5228..95ea6542d 100644 --- a/api/http/handler/hostmanagement/openamt/amtactivation.go +++ b/api/http/handler/hostmanagement/openamt/amtactivation.go @@ -2,7 +2,6 @@ package openamt import ( "errors" - "fmt" "net/http" portainer "github.com/portainer/portainer/api" @@ -37,7 +36,7 @@ func (handler *Handler) openAMTActivate(w http.ResponseWriter, r *http.Request) } else if err != nil { return httperror.InternalServerError("Unable to find an endpoint with the specified identifier inside the database", err) } else if !endpointutils.IsAgentEndpoint(endpoint) { - errMsg := fmt.Sprintf("%s is not an agent environment", endpoint.Name) + errMsg := endpoint.Name + " is not an agent environment" return httperror.BadRequest(errMsg, errors.New(errMsg)) } @@ -46,8 +45,7 @@ func (handler *Handler) openAMTActivate(w http.ResponseWriter, r *http.Request) return httperror.InternalServerError("Unable to retrieve settings from the database", err) } - err = handler.activateDevice(endpoint, *settings) - if err != nil { + if err := handler.activateDevice(endpoint, *settings); err != nil { return httperror.InternalServerError("Unable to activate device", err) } @@ -63,8 +61,7 @@ func (handler *Handler) openAMTActivate(w http.ResponseWriter, r *http.Request) } endpoint.AMTDeviceGUID = hostInfo.UUID - err = handler.DataStore.Endpoint().UpdateEndpoint(endpoint.ID, endpoint) - if err != nil { + if err := handler.DataStore.Endpoint().UpdateEndpoint(endpoint.ID, endpoint); err != nil { return httperror.InternalServerError("Unable to persist environment changes inside the database", err) } diff --git a/api/http/handler/kubernetes/config.go b/api/http/handler/kubernetes/config.go index e5bae6c4e..aad9c03a8 100644 --- a/api/http/handler/kubernetes/config.go +++ b/api/http/handler/kubernetes/config.go @@ -172,13 +172,12 @@ func (handler *Handler) buildCluster(r *http.Request, endpoint portainer.Endpoin } func buildClusterName(endpointName string) string { - return fmt.Sprintf("portainer-cluster-%s", endpointName) + return "portainer-cluster-" + endpointName } func buildContext(serviceAccountName string, endpoint portainer.Endpoint) clientV1.NamedContext { - contextName := fmt.Sprintf("portainer-ctx-%s", endpoint.Name) return clientV1.NamedContext{ - Name: contextName, + Name: "portainer-ctx-" + endpoint.Name, Context: clientV1.Context{ AuthInfo: serviceAccountName, Cluster: buildClusterName(endpoint.Name), diff --git a/api/http/handler/kubernetes/namespaces.go b/api/http/handler/kubernetes/namespaces.go index 6a02d8fb8..2efde3b85 100644 --- a/api/http/handler/kubernetes/namespaces.go +++ b/api/http/handler/kubernetes/namespaces.go @@ -185,7 +185,7 @@ func (handler *Handler) createKubernetesNamespace(w http.ResponseWriter, r *http } log.Error().Err(err).Str("context", "CreateKubernetesNamespace").Str("namespace", namespaceName).Msg("Unable to create the namespace") - return httperror.InternalServerError(fmt.Sprintf("an error occurred during the CreateKubernetesNamespace operation, unable to create the namespace: %s", namespaceName), err) + return httperror.InternalServerError("an error occurred during the CreateKubernetesNamespace operation, unable to create the namespace: "+namespaceName, err) } return response.JSON(w, namespace) @@ -217,15 +217,14 @@ func (handler *Handler) deleteKubernetesNamespace(w http.ResponseWriter, r *http } for _, namespaceName := range *namespaceNames { - _, err := cli.DeleteNamespace(namespaceName) - if err != nil { + if _, err := cli.DeleteNamespace(namespaceName); err != nil { if k8serrors.IsNotFound(err) { log.Error().Err(err).Str("context", "DeleteKubernetesNamespace").Str("namespace", namespaceName).Msg("Unable to find the namespace") - return httperror.NotFound(fmt.Sprintf("an error occurred during the DeleteKubernetesNamespace operation for the namespace %s, unable to find the namespace. Error: ", namespaceName), err) + return httperror.NotFound("an error occurred during the DeleteKubernetesNamespace operation for the namespace "+namespaceName+", unable to find the namespace. Error: ", err) } log.Error().Err(err).Str("context", "DeleteKubernetesNamespace").Str("namespace", namespaceName).Msg("Unable to delete the namespace") - return httperror.InternalServerError(fmt.Sprintf("an error occurred during the DeleteKubernetesNamespace operation for the namespace %s, unable to delete the Kubernetes namespace. Error: ", namespaceName), err) + return httperror.InternalServerError("an error occurred during the DeleteKubernetesNamespace operation for the namespace "+namespaceName+", unable to delete the Kubernetes namespace. Error: ", err) } } @@ -262,8 +261,7 @@ func (payload deleteKubernetesNamespacePayload) Validate(r *http.Request) error // @router /kubernetes/{id}/namespaces/{namespace} [put] func (handler *Handler) updateKubernetesNamespace(w http.ResponseWriter, r *http.Request) *httperror.HandlerError { payload := models.K8sNamespaceDetails{} - err := request.DecodeAndValidateJSONPayload(r, &payload) - if err != nil { + if err := request.DecodeAndValidateJSONPayload(r, &payload); err != nil { return httperror.BadRequest("an error occurred during the UpdateKubernetesNamespace operation, invalid request payload. Error: ", err) } diff --git a/api/http/handler/websocket/pod.go b/api/http/handler/websocket/pod.go index 0099abfe0..eb17ff9f7 100644 --- a/api/http/handler/websocket/pod.go +++ b/api/http/handler/websocket/pod.go @@ -1,7 +1,7 @@ package websocket import ( - "fmt" + "errors" "io" "net/http" "strings" @@ -69,8 +69,7 @@ func (handler *Handler) websocketPodExec(w http.ResponseWriter, r *http.Request) return httperror.InternalServerError("Unable to find the environment associated to the stack inside the database", err) } - err = handler.requestBouncer.AuthorizedEndpointOperation(r, endpoint) - if err != nil { + if err := handler.requestBouncer.AuthorizedEndpointOperation(r, endpoint); err != nil { return httperror.Forbidden("Permission denied to access environment", err) } @@ -87,15 +86,13 @@ func (handler *Handler) websocketPodExec(w http.ResponseWriter, r *http.Request) r.Header.Del("Origin") if endpoint.Type == portainer.AgentOnKubernetesEnvironment { - err := handler.proxyAgentWebsocketRequest(w, r, params) - if err != nil { + if err := handler.proxyAgentWebsocketRequest(w, r, params); err != nil { return httperror.InternalServerError("Unable to proxy websocket request to agent", err) } return nil } else if endpoint.Type == portainer.EdgeAgentOnKubernetesEnvironment { - err := handler.proxyEdgeAgentWebsocketRequest(w, r, params) - if err != nil { + if err := handler.proxyEdgeAgentWebsocketRequest(w, r, params); err != nil { return httperror.InternalServerError("Unable to proxy websocket request to Edge agent", err) } @@ -187,7 +184,7 @@ func (handler *Handler) getToken(request *http.Request, endpoint *portainer.Endp } if token == "" { - return "", false, fmt.Errorf("can not get a valid user service account token") + return "", false, errors.New("can not get a valid user service account token") } return token, false, nil diff --git a/api/http/handler/websocket/proxy.go b/api/http/handler/websocket/proxy.go index be1b94b06..c8ee8b82b 100644 --- a/api/http/handler/websocket/proxy.go +++ b/api/http/handler/websocket/proxy.go @@ -2,7 +2,6 @@ package websocket import ( "context" - "fmt" "net" "net/http" "net/url" @@ -34,7 +33,7 @@ func (handler *Handler) proxyEdgeAgentWebsocketRequest(w http.ResponseWriter, r func (handler *Handler) proxyAgentWebsocketRequest(w http.ResponseWriter, r *http.Request, params *webSocketRequestParams) error { endpointURL := params.endpoint.URL if params.endpoint.Type == portainer.AgentOnKubernetesEnvironment { - endpointURL = fmt.Sprintf("http://%s", params.endpoint.URL) + endpointURL = "http://" + params.endpoint.URL } agentURL, err := url.Parse(endpointURL) diff --git a/api/http/models/kubernetes/namespaces.go b/api/http/models/kubernetes/namespaces.go index dbb71b3ef..355d6f372 100644 --- a/api/http/models/kubernetes/namespaces.go +++ b/api/http/models/kubernetes/namespaces.go @@ -22,13 +22,11 @@ type K8sResourceQuota struct { func (r *K8sNamespaceDetails) Validate(request *http.Request) error { if r.ResourceQuota != nil && r.ResourceQuota.Enabled { - _, err := resource.ParseQuantity(r.ResourceQuota.Memory) - if err != nil { + if _, err := resource.ParseQuantity(r.ResourceQuota.Memory); err != nil { return fmt.Errorf("error parsing memory quota value: %w", err) } - _, err = resource.ParseQuantity(r.ResourceQuota.CPU) - if err != nil { + if _, err := resource.ParseQuantity(r.ResourceQuota.CPU); err != nil { return fmt.Errorf("error parsing cpu quota value: %w", err) } } diff --git a/api/http/proxy/factory/azure/containergroup.go b/api/http/proxy/factory/azure/containergroup.go index d16d7109a..a955dc583 100644 --- a/api/http/proxy/factory/azure/containergroup.go +++ b/api/http/proxy/factory/azure/containergroup.go @@ -2,7 +2,6 @@ package azure import ( "errors" - "fmt" "net/http" portainer "github.com/portainer/portainer/api" @@ -40,7 +39,7 @@ func (transport *Transport) proxyContainerGroupPutRequest(request *http.Request) Method: http.MethodGet, URL: request.URL, Header: http.Header{ - "Authorization": []string{fmt.Sprintf("Bearer %s", tokenData.Token)}, + "Authorization": []string{"Bearer " + tokenData.Token}, }, } diff --git a/api/http/proxy/factory/azure/containergroups.go b/api/http/proxy/factory/azure/containergroups.go index 92018c120..f609fb2a0 100644 --- a/api/http/proxy/factory/azure/containergroups.go +++ b/api/http/proxy/factory/azure/containergroups.go @@ -1,7 +1,7 @@ package azure import ( - "fmt" + "errors" "net/http" "github.com/portainer/portainer/api/http/proxy/factory/utils" @@ -41,7 +41,7 @@ func (transport *Transport) proxyContainerGroupsGetRequest(request *http.Request utils.RewriteResponse(response, responseObject, http.StatusOK) } else { - return nil, fmt.Errorf("The container groups response has no value property") + return nil, errors.New("The container groups response has no value property") } return response, nil diff --git a/api/http/proxy/factory/kubernetes/transport.go b/api/http/proxy/factory/kubernetes/transport.go index aa6031eae..76e9daa68 100644 --- a/api/http/proxy/factory/kubernetes/transport.go +++ b/api/http/proxy/factory/kubernetes/transport.go @@ -120,7 +120,7 @@ func (transport *baseTransport) prepareRoundTrip(request *http.Request) (string, return "", err } - request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", token)) + request.Header.Set("Authorization", "Bearer "+token) return token, nil } diff --git a/api/http/security/bouncer.go b/api/http/security/bouncer.go index 11b7ee745..7ac8e2367 100644 --- a/api/http/security/bouncer.go +++ b/api/http/security/bouncer.go @@ -1,7 +1,6 @@ package security import ( - "fmt" "net/http" "strings" "sync" @@ -426,7 +425,7 @@ func (bouncer *RequestBouncer) apiKeyLookup(r *http.Request) (*portainer.TokenDa } if _, _, err := bouncer.jwtService.GenerateToken(tokenData); err != nil { log.Debug().Err(err).Msg("Failed to generate token") - return nil, fmt.Errorf("failed to generate token") + return nil, errors.New("failed to generate token") } if now := time.Now().UTC().Unix(); now-apiKey.LastUsed > 60 { // [seconds] diff --git a/api/internal/endpointutils/endpointutils.go b/api/internal/endpointutils/endpointutils.go index b26e165cf..1ab31e01d 100644 --- a/api/internal/endpointutils/endpointutils.go +++ b/api/internal/endpointutils/endpointutils.go @@ -1,7 +1,7 @@ package endpointutils import ( - "fmt" + "errors" "strings" "time" @@ -171,7 +171,7 @@ func storageDetect(endpoint *portainer.Endpoint, endpointService dataservices.En } else if len(storage) == 0 { log.Info().Err(err).Msg("zero storage classes found: they may be still building, retrying in 30 seconds") - return fmt.Errorf("zero storage classes found: they may be still building, retrying in 30 seconds") + return errors.New("zero storage classes found: they may be still building, retrying in 30 seconds") } endpoint.Kubernetes.Configuration.StorageClasses = storage diff --git a/api/internal/registryutils/access/access.go b/api/internal/registryutils/access/access.go index 70524b3bb..0d14cba39 100644 --- a/api/internal/registryutils/access/access.go +++ b/api/internal/registryutils/access/access.go @@ -1,7 +1,7 @@ package access import ( - "fmt" + "errors" portainer "github.com/portainer/portainer/api" "github.com/portainer/portainer/api/dataservices" @@ -52,7 +52,7 @@ func GetAccessibleRegistry( } if !hasPermission { - err = fmt.Errorf("user does not has permission to get the registry") + err = errors.New("user does not has permission to get the registry") return nil, err } diff --git a/api/kubernetes/cli/applications.go b/api/kubernetes/cli/applications.go index cc89d20be..03f623d9e 100644 --- a/api/kubernetes/cli/applications.go +++ b/api/kubernetes/cli/applications.go @@ -2,7 +2,6 @@ package cli import ( "context" - "fmt" models "github.com/portainer/portainer/api/http/models/kubernetes" "github.com/rs/zerolog/log" @@ -28,7 +27,7 @@ func (kcl *KubeClient) GetApplications(namespace, nodeName string, withDependenc func (kcl *KubeClient) fetchApplications(namespace, nodeName string, withDependencies bool) ([]models.K8sApplication, error) { podListOptions := metav1.ListOptions{} if nodeName != "" { - podListOptions.FieldSelector = fmt.Sprintf("spec.nodeName=%s", nodeName) + podListOptions.FieldSelector = "spec.nodeName=" + nodeName } if !withDependencies { // TODO: make sure not to fetch services in fetchAllApplicationsListResources from this call @@ -59,7 +58,7 @@ func (kcl *KubeClient) fetchApplicationsForNonAdmin(namespace, nodeName string, podListOptions := metav1.ListOptions{} if nodeName != "" { - podListOptions.FieldSelector = fmt.Sprintf("spec.nodeName=%s", nodeName) + podListOptions.FieldSelector = "spec.nodeName=" + nodeName } if !withDependencies { @@ -125,7 +124,7 @@ func (kcl *KubeClient) GetApplicationsResource(namespace, node string) (models.K resource := models.K8sApplicationResource{} podListOptions := metav1.ListOptions{} if node != "" { - podListOptions.FieldSelector = fmt.Sprintf("spec.nodeName=%s", node) + podListOptions.FieldSelector = "spec.nodeName=" + node } pods, err := kcl.cli.CoreV1().Pods(namespace).List(context.Background(), podListOptions) diff --git a/api/kubernetes/cli/client.go b/api/kubernetes/cli/client.go index 5c8e32792..ce76f725f 100644 --- a/api/kubernetes/cli/client.go +++ b/api/kubernetes/cli/client.go @@ -273,7 +273,7 @@ func (factory *ClientFactory) buildEdgeConfig(endpoint *portainer.Endpoint) (*re func (factory *ClientFactory) CreateRemoteMetricsClient(endpoint *portainer.Endpoint) (*metricsv.Clientset, error) { config, err := factory.CreateConfig(endpoint) if err != nil { - return nil, fmt.Errorf("failed to create metrics KubeConfig") + return nil, errors.New("failed to create metrics KubeConfig") } return metricsv.NewForConfig(config) } diff --git a/api/kubernetes/cli/cluster_role.go b/api/kubernetes/cli/cluster_role.go index d5194ccd2..17a59dc08 100644 --- a/api/kubernetes/cli/cluster_role.go +++ b/api/kubernetes/cli/cluster_role.go @@ -2,7 +2,7 @@ package cli import ( "context" - "fmt" + "errors" models "github.com/portainer/portainer/api/http/models/kubernetes" rbacv1 "k8s.io/api/rbac/v1" @@ -16,7 +16,7 @@ func (kcl *KubeClient) GetClusterRoles() ([]models.K8sClusterRole, error) { return kcl.fetchClusterRoles() } - return []models.K8sClusterRole{}, fmt.Errorf("non-admin users are not allowed to access cluster roles") + return []models.K8sClusterRole{}, errors.New("non-admin users are not allowed to access cluster roles") } // fetchClusterRoles returns a list of all Roles in the specified namespace. diff --git a/api/kubernetes/cli/cluster_role_binding.go b/api/kubernetes/cli/cluster_role_binding.go index 070ef1c50..2a4e84a15 100644 --- a/api/kubernetes/cli/cluster_role_binding.go +++ b/api/kubernetes/cli/cluster_role_binding.go @@ -2,7 +2,7 @@ package cli import ( "context" - "fmt" + "errors" models "github.com/portainer/portainer/api/http/models/kubernetes" rbacv1 "k8s.io/api/rbac/v1" @@ -16,7 +16,7 @@ func (kcl *KubeClient) GetClusterRoleBindings() ([]models.K8sClusterRoleBinding, return kcl.fetchClusterRoleBindings() } - return []models.K8sClusterRoleBinding{}, fmt.Errorf("non-admin users are not allowed to access cluster role bindings") + return []models.K8sClusterRoleBinding{}, errors.New("non-admin users are not allowed to access cluster role bindings") } // fetchClusterRoleBindings returns a list of all cluster roles in the cluster. diff --git a/api/scheduler/scheduler_test.go b/api/scheduler/scheduler_test.go index 279c8d8b6..aa5a13f3e 100644 --- a/api/scheduler/scheduler_test.go +++ b/api/scheduler/scheduler_test.go @@ -3,7 +3,6 @@ package scheduler import ( "context" "errors" - "fmt" "sync/atomic" "testing" "time" @@ -59,7 +58,7 @@ func Test_JobShouldStop_UponPermError(t *testing.T) { s.StartJobEvery(jobInterval, func() error { acc++ close(ch) - return NewPermanentError(fmt.Errorf("failed")) + return NewPermanentError(errors.New("failed")) }) <-time.After(3 * jobInterval) @@ -76,7 +75,7 @@ func Test_JobShouldNotStop_UponError(t *testing.T) { s.StartJobEvery(jobInterval, func() error { if acc.Add(1) == 2 { close(ch) - return NewPermanentError(fmt.Errorf("failed")) + return NewPermanentError(errors.New("failed")) } return errors.New("non-permanent error") diff --git a/pkg/libhelm/binary/search_repo.go b/pkg/libhelm/binary/search_repo.go index 60450d2ee..f875589cb 100644 --- a/pkg/libhelm/binary/search_repo.go +++ b/pkg/libhelm/binary/search_repo.go @@ -4,7 +4,6 @@ package binary // The functionality does not rely on the implementation of `HelmPackageManager` import ( - "fmt" "net/http" "net/url" "path" @@ -72,7 +71,7 @@ func (hbpm *helmBinaryPackageManager) SearchRepo(searchRepoOpts options.SearchRe url, err := url.ParseRequestURI(searchRepoOpts.Repo) if err != nil { - return nil, errors.Wrap(err, fmt.Sprintf("invalid helm chart URL: %s", searchRepoOpts.Repo)) + return nil, errors.Wrap(err, "invalid helm chart URL: "+searchRepoOpts.Repo) } url.Path = path.Join(url.Path, "index.yaml") diff --git a/pkg/libstack/compose/compose_test.go b/pkg/libstack/compose/compose_test.go index 3678a5159..c27ef64ad 100644 --- a/pkg/libstack/compose/compose_test.go +++ b/pkg/libstack/compose/compose_test.go @@ -2,7 +2,6 @@ package compose_test import ( "context" - "fmt" "log" "os" "os/exec" @@ -94,7 +93,7 @@ func createFile(dir, fileName, content string) (string, error) { } func containerExists(containerName string) bool { - cmd := exec.Command("docker", "ps", "-a", "-f", fmt.Sprintf("name=%s", containerName)) + cmd := exec.Command("docker", "ps", "-a", "-f", "name="+containerName) out, err := cmd.Output() if err != nil { diff --git a/pkg/libstack/compose/internal/composeplugin/composeplugin_test.go b/pkg/libstack/compose/internal/composeplugin/composeplugin_test.go index 960d33aa6..9970a2368 100644 --- a/pkg/libstack/compose/internal/composeplugin/composeplugin_test.go +++ b/pkg/libstack/compose/internal/composeplugin/composeplugin_test.go @@ -2,7 +2,6 @@ package composeplugin import ( "context" - "fmt" "log" "os" "os/exec" @@ -134,7 +133,7 @@ func createFile(dir, fileName, content string) (string, error) { } func containerExists(containerName string) bool { - cmd := exec.Command("docker", "ps", "-a", "-f", fmt.Sprintf("name=%s", containerName)) + cmd := exec.Command("docker", "ps", "-a", "-f", "name="+containerName) out, err := cmd.Output() if err != nil { diff --git a/pkg/libstack/compose/internal/composeplugin/status.go b/pkg/libstack/compose/internal/composeplugin/status.go index 7930a3865..79def8af8 100644 --- a/pkg/libstack/compose/internal/composeplugin/status.go +++ b/pkg/libstack/compose/internal/composeplugin/status.go @@ -124,7 +124,7 @@ func (wrapper *PluginWrapper) WaitForStatus(ctx context.Context, name string, st for { select { case <-ctx.Done(): - waitResult.ErrorMsg = fmt.Sprintf("failed to wait for status: %s", ctx.Err().Error()) + waitResult.ErrorMsg = "failed to wait for status: " + ctx.Err().Error() waitResultCh <- waitResult default: }