diff --git a/.golangci.yml b/.golangci.yml index dcc8354447..acc05ada09 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -261,6 +261,11 @@ linters-settings: allow-case-traling-whitespace: true # Allow declarations (var) to be cuddled. allow-cuddle-declarations: false + testifylint: + disable: + - float-compare + - negative-positive + - go-require linters: fast: false @@ -317,3 +322,5 @@ linters: - goconst - tagalign - inamedparam + - canonicalheader + - fatcontext diff --git a/Makefile b/Makefile index d2e37480f7..a97cfbd37e 100644 --- a/Makefile +++ b/Makefile @@ -119,9 +119,9 @@ test: lint: verify-linter-installed verify-linter-version ifdef LINT_BASE @echo "LINT_BASE is set to "$(LINT_BASE)". Linter will only check diff." - $(GOLANGCI_LINT) run --timeout=20m --new-from-rev $(shell git rev-parse $(LINT_BASE)) + $(GOLANGCI_LINT) run --timeout=20m --max-same-issues 0 --max-issues-per-linter 0 --new-from-rev $(shell git rev-parse $(LINT_BASE)) else - $(GOLANGCI_LINT) run --timeout=20m + $(GOLANGCI_LINT) run --timeout=20m --max-same-issues 0 --max-issues-per-linter 0 endif ################################################################################ diff --git a/bindings/alicloud/sls/sls.go b/bindings/alicloud/sls/sls.go index 84ea79690f..42d7b4a55c 100644 --- a/bindings/alicloud/sls/sls.go +++ b/bindings/alicloud/sls/sls.go @@ -3,7 +3,7 @@ package sls import ( "context" "encoding/json" - "fmt" + "errors" "reflect" "time" @@ -61,16 +61,16 @@ func NewAliCloudSlsLogstorage(logger logger.Logger) bindings.OutputBinding { func (s *AliCloudSlsLogstorage) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bindings.InvokeResponse, error) { // verify the metadata property if logProject := req.Metadata["project"]; logProject == "" { - return nil, fmt.Errorf("SLS binding error: project property not supplied") + return nil, errors.New("SLS binding error: project property not supplied") } if logstore := req.Metadata["logstore"]; logstore == "" { - return nil, fmt.Errorf("SLS binding error: logstore property not supplied") + return nil, errors.New("SLS binding error: logstore property not supplied") } if topic := req.Metadata["topic"]; topic == "" { - return nil, fmt.Errorf("SLS binding error: topic property not supplied") + return nil, errors.New("SLS binding error: topic property not supplied") } if source := req.Metadata["source"]; source == "" { - return nil, fmt.Errorf("SLS binding error: source property not supplied") + return nil, errors.New("SLS binding error: source property not supplied") } log, err := s.parseLog(req) @@ -96,6 +96,7 @@ func (s *AliCloudSlsLogstorage) parseLog(req *bindings.InvokeRequest) (*sls.Log, if err != nil { return nil, err } + //nolint:gosec return producer.GenerateLog(uint32(time.Now().Unix()), logInfo), nil } diff --git a/bindings/alicloud/tablestore/tablestore.go b/bindings/alicloud/tablestore/tablestore.go index 13cc61aa98..c153f2c1e0 100644 --- a/bindings/alicloud/tablestore/tablestore.go +++ b/bindings/alicloud/tablestore/tablestore.go @@ -271,7 +271,6 @@ func (s *AliCloudTableStore) create(req *bindings.InvokeRequest, resp *bindings. } _, err = s.client.PutRow(putRequest) - if err != nil { return err } @@ -302,7 +301,6 @@ func (s *AliCloudTableStore) delete(req *bindings.InvokeRequest, resp *bindings. change.SetCondition(tablestore.RowExistenceExpectation_IGNORE) //nolint:nosnakecase deleteReq := &tablestore.DeleteRowRequest{DeleteRowChange: change} _, err = s.client.DeleteRow(deleteReq) - if err != nil { return err } diff --git a/bindings/aws/kinesis/kinesis.go b/bindings/aws/kinesis/kinesis.go index 94bf590bb4..dbe0ceb918 100644 --- a/bindings/aws/kinesis/kinesis.go +++ b/bindings/aws/kinesis/kinesis.go @@ -300,7 +300,6 @@ func (a *AWSKinesis) registerConsumer(ctx context.Context, streamARN *string) (* ConsumerName: &a.metadata.ConsumerName, StreamARN: streamARN, }) - if err != nil { return nil, err } diff --git a/bindings/aws/s3/s3.go b/bindings/aws/s3/s3.go index 70a0c8a518..cc67cec94f 100644 --- a/bindings/aws/s3/s3.go +++ b/bindings/aws/s3/s3.go @@ -313,7 +313,7 @@ func (s *AWSS3) get(ctx context.Context, req *bindings.InvokeRequest) (*bindings if err != nil { var awsErr awserr.Error if errors.As(err, &awsErr) && awsErr.Code() == s3.ErrCodeNoSuchKey { - return nil, fmt.Errorf("object not found") + return nil, errors.New("object not found") } return nil, fmt.Errorf("s3 binding error: error downloading S3 object: %w", err) } @@ -348,7 +348,7 @@ func (s *AWSS3) delete(ctx context.Context, req *bindings.InvokeRequest) (*bindi if err != nil { var awsErr awserr.Error if errors.As(err, &awsErr) && awsErr.Code() == s3.ErrCodeNoSuchKey { - return nil, fmt.Errorf("object not found") + return nil, errors.New("object not found") } return nil, fmt.Errorf("s3 binding error: delete operation failed: %w", err) } diff --git a/bindings/aws/ses/ses.go b/bindings/aws/ses/ses.go index 6b59657c9c..483fde8c64 100644 --- a/bindings/aws/ses/ses.go +++ b/bindings/aws/ses/ses.go @@ -15,6 +15,7 @@ package ses import ( "context" + "errors" "fmt" "reflect" "strconv" @@ -92,13 +93,13 @@ func (a *AWSSES) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bind metadata := a.metadata.mergeWithRequestMetadata(req) if metadata.EmailFrom == "" { - return nil, fmt.Errorf("SES binding error: emailFrom property not supplied in configuration- or request-metadata") + return nil, errors.New("SES binding error: emailFrom property not supplied in configuration- or request-metadata") } if metadata.EmailTo == "" { - return nil, fmt.Errorf("SES binding error: emailTo property not supplied in configuration- or request-metadata") + return nil, errors.New("SES binding error: emailTo property not supplied in configuration- or request-metadata") } if metadata.Subject == "" { - return nil, fmt.Errorf("SES binding error: subject property not supplied in configuration- or request-metadata") + return nil, errors.New("SES binding error: subject property not supplied in configuration- or request-metadata") } body, err := strconv.Unquote(string(req.Data)) diff --git a/bindings/azure/blobstorage/blobstorage.go b/bindings/azure/blobstorage/blobstorage.go index ba38ae9b6d..b132f9bf4a 100644 --- a/bindings/azure/blobstorage/blobstorage.go +++ b/bindings/azure/blobstorage/blobstorage.go @@ -154,7 +154,6 @@ func (a *AzureBlobStorage) create(ctx context.Context, req *bindings.InvokeReque blockBlobClient := a.containerClient.NewBlockBlobClient(blobName) _, err = blockBlobClient.UploadBuffer(ctx, req.Data, &uploadOptions) - if err != nil { return nil, fmt.Errorf("error uploading az blob: %w", err) } @@ -192,7 +191,7 @@ func (a *AzureBlobStorage) get(ctx context.Context, req *bindings.InvokeRequest) blobDownloadResponse, err := blockBlobClient.DownloadStream(ctx, &downloadOptions) if err != nil { if bloberror.HasCode(err, bloberror.BlobNotFound) { - return nil, fmt.Errorf("blob not found") + return nil, errors.New("blob not found") } return nil, fmt.Errorf("error downloading az blob: %w", err) } @@ -261,7 +260,7 @@ func (a *AzureBlobStorage) delete(ctx context.Context, req *bindings.InvokeReque _, err := blockBlobClient.Delete(ctx, &deleteOptions) if bloberror.HasCode(err, bloberror.BlobNotFound) { - return nil, fmt.Errorf("blob not found") + return nil, errors.New("blob not found") } return nil, err diff --git a/bindings/azure/cosmosdb/cosmosdb.go b/bindings/azure/cosmosdb/cosmosdb.go index 41571a1042..c210d440ec 100644 --- a/bindings/azure/cosmosdb/cosmosdb.go +++ b/bindings/azure/cosmosdb/cosmosdb.go @@ -16,6 +16,7 @@ package cosmosdb import ( "context" "encoding/json" + "errors" "fmt" "reflect" "strings" @@ -158,7 +159,7 @@ func (c *CosmosDB) getPartitionKeyValue(key string, obj interface{}) (string, er } val, ok := valI.(string) if !ok { - return "", fmt.Errorf("partition key is not a string") + return "", errors.New("partition key is not a string") } if val == "" { @@ -172,7 +173,7 @@ func (c *CosmosDB) lookup(m map[string]interface{}, ks []string) (val interface{ var ok bool if len(ks) == 0 { - return nil, fmt.Errorf("needs at least one key") + return nil, errors.New("needs at least one key") } if val, ok = m[ks[0]]; !ok { diff --git a/bindings/azure/signalr/signalr.go b/bindings/azure/signalr/signalr.go index 23d1804477..c0de8dd358 100644 --- a/bindings/azure/signalr/signalr.go +++ b/bindings/azure/signalr/signalr.go @@ -156,7 +156,7 @@ func (s *SignalR) parseMetadata(md map[string]string) (err error) { s.accessKey = connectionValue[i+1:] case "AuthType": if connectionValue[i+1:] != "aad" { - return fmt.Errorf("invalid value for AuthType in the connection string; only 'aad' is supported") + return errors.New("invalid value for AuthType in the connection string; only 'aad' is supported") } useAAD = true case "ClientId", "ClientSecret", "TenantId": @@ -171,14 +171,14 @@ func (s *SignalR) parseMetadata(md map[string]string) (err error) { } } } else if len(connectionValue) != 0 { - return fmt.Errorf("the connection string is invalid or malformed") + return errors.New("the connection string is invalid or malformed") } } // Check here because if we use a connection string, we'd have an explicit "AuthType=aad" option // We would otherwise catch this issue later, but here we can be more explicit with the error if s.accessKey == "" && !useAAD { - return fmt.Errorf("missing AccessKey in the connection string") + return errors.New("missing AccessKey in the connection string") } } @@ -198,7 +198,7 @@ func (s *SignalR) parseMetadata(md map[string]string) (err error) { // Check for required values if s.endpoint == "" { - return fmt.Errorf("missing endpoint in the metadata or connection string") + return errors.New("missing endpoint in the metadata or connection string") } return nil @@ -333,7 +333,7 @@ func (s *SignalR) GetAadClientAccessToken(ctx context.Context, hub string, user u := fmt.Sprintf("%s/api/hubs/%s/:generateToken?api-version=%s", s.endpoint, hub, apiVersion) if user != "" { - u += fmt.Sprintf("&userId=%s", url.QueryEscape(user)) + u += "&userId=" + url.QueryEscape(user) } body, err := s.sendRequestToSignalR(ctx, u, aadToken, nil) diff --git a/bindings/azure/signalr/signalr_test.go b/bindings/azure/signalr/signalr_test.go index 44d7121c28..fef7b94abd 100644 --- a/bindings/azure/signalr/signalr_test.go +++ b/bindings/azure/signalr/signalr_test.go @@ -394,7 +394,6 @@ func TestWriteShouldSucceed(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.name, func(t *testing.T) { httpTransport.reset() s.hub = tt.hubInMetadata diff --git a/bindings/azure/storagequeues/storagequeues.go b/bindings/azure/storagequeues/storagequeues.go index 78e5540281..aa14f00d2e 100644 --- a/bindings/azure/storagequeues/storagequeues.go +++ b/bindings/azure/storagequeues/storagequeues.go @@ -220,7 +220,7 @@ func (d *AzureQueueHelper) Read(ctx context.Context, consumer *consumer) error { } return nil } else { - return fmt.Errorf("could not delete message from queue: message ID or pop receipt is nil") + return errors.New("could not delete message from queue: message ID or pop receipt is nil") } } diff --git a/bindings/commercetools/commercetools.go b/bindings/commercetools/commercetools.go index 7efd4053cf..1da4183e63 100644 --- a/bindings/commercetools/commercetools.go +++ b/bindings/commercetools/commercetools.go @@ -65,7 +65,7 @@ func (ct *Binding) Init(_ context.Context, metadata bindings.Metadata) error { baseURLdomain := fmt.Sprintf("%s.%s.commercetools.com", commercetoolsM.Region, commercetoolsM.Provider) authURL := fmt.Sprintf("https://auth.%s/oauth/token", baseURLdomain) - apiURL := fmt.Sprintf("https://api.%s", baseURLdomain) + apiURL := "https://api." + baseURLdomain // Create the new client. When an empty value is passed it will use the CTP_* // environment variables to get the value. The HTTPClient arg is optional, diff --git a/bindings/cron/cron.go b/bindings/cron/cron.go index cefd4057f5..dec1faa2ae 100644 --- a/bindings/cron/cron.go +++ b/bindings/cron/cron.go @@ -76,7 +76,7 @@ func (b *Binding) Init(ctx context.Context, meta bindings.Metadata) error { return err } if m.Schedule == "" { - return fmt.Errorf("schedule not set") + return errors.New("schedule not set") } _, err = b.parser.Parse(m.Schedule) if err != nil { diff --git a/bindings/cron/cron_test.go b/bindings/cron/cron_test.go index e64dd6eb07..06c2024209 100644 --- a/bindings/cron/cron_test.go +++ b/bindings/cron/cron_test.go @@ -109,7 +109,7 @@ func TestCronRead(t *testing.T) { return nil, nil }) // Check if cron triggers 5 times in 5 seconds - for i := int32(0); i < expectedCount; i++ { + for range expectedCount { // Add time to mock clock in 1 second intervals using loop to allow cron go routine to run clk.Step(time.Second) runtime.Gosched() @@ -143,7 +143,7 @@ func TestCronReadWithContextCancellation(t *testing.T) { return nil, nil }) // Check if cron triggers only 5 times in 10 seconds since context should be cancelled after 5 triggers - for i := 0; i < 10; i++ { + for range 10 { // Add time to mock clock in 1 second intervals using loop to allow cron go routine to run clk.Step(time.Second) runtime.Gosched() diff --git a/bindings/gcp/bucket/bucket.go b/bindings/gcp/bucket/bucket.go index 7fa929ae40..2a8b5e1faa 100644 --- a/bindings/gcp/bucket/bucket.go +++ b/bindings/gcp/bucket/bucket.go @@ -220,7 +220,7 @@ func (g *GCPStorage) get(ctx context.Context, req *bindings.InvokeRequest) (*bin if val, ok := req.Metadata[metadataKey]; ok && val != "" { key = val } else { - return nil, fmt.Errorf("gcp bucket binding error: can't read key value") + return nil, errors.New("gcp bucket binding error: can't read key value") } var rc io.ReadCloser @@ -256,7 +256,7 @@ func (g *GCPStorage) delete(ctx context.Context, req *bindings.InvokeRequest) (* if val, ok := req.Metadata[metadataKey]; ok && val != "" { key = val } else { - return nil, fmt.Errorf("gcp bucketgcp bucket binding error: can't read key value") + return nil, errors.New("gcp bucketgcp bucket binding error: can't read key value") } object := g.client.Bucket(g.metadata.Bucket).Object(key) @@ -355,7 +355,7 @@ func (g *GCPStorage) sign(ctx context.Context, req *bindings.InvokeRequest) (*bi if val, ok := req.Metadata[metadataKey]; ok && val != "" { key = val } else { - return nil, fmt.Errorf("gcp bucket binding error: can't read key value") + return nil, errors.New("gcp bucket binding error: can't read key value") } if metadata.SignTTL == "" { diff --git a/bindings/graphql/graphql.go b/bindings/graphql/graphql.go index 606c04253c..55cf556e3d 100644 --- a/bindings/graphql/graphql.go +++ b/bindings/graphql/graphql.go @@ -16,6 +16,7 @@ package graphql import ( "context" "encoding/json" + "errors" "fmt" "reflect" "regexp" @@ -73,7 +74,7 @@ func (gql *GraphQL) Init(_ context.Context, meta bindings.Metadata) error { } if m.Endpoint == "" { - return fmt.Errorf("GraphQL Error: Missing GraphQL URL") + return errors.New("GraphQL Error: Missing GraphQL URL") } // Connect to GraphQL Server @@ -101,11 +102,11 @@ func (gql *GraphQL) Operations() []bindings.OperationKind { // Invoke handles all invoke operations. func (gql *GraphQL) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bindings.InvokeResponse, error) { if req == nil { - return nil, fmt.Errorf("GraphQL Error: Invoke request required") + return nil, errors.New("GraphQL Error: Invoke request required") } if req.Metadata == nil { - return nil, fmt.Errorf("GraphQL Error: Metadata required") + return nil, errors.New("GraphQL Error: Metadata required") } gql.logger.Debugf("operation: %v", req.Operation) diff --git a/bindings/http/http_test.go b/bindings/http/http_test.go index ecc297d7b3..58661f35f9 100644 --- a/bindings/http/http_test.go +++ b/bindings/http/http_test.go @@ -330,7 +330,7 @@ func (h *HTTPHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) { h.Path = req.URL.Path if strings.TrimPrefix(h.Path, "/") == "large" { // Write 5KB - for i := 0; i < 1<<10; i++ { + for range 1 << 10 { fmt.Fprint(w, "12345") } return diff --git a/bindings/huawei/obs/obs.go b/bindings/huawei/obs/obs.go index 65085f3f87..c393da6ad5 100644 --- a/bindings/huawei/obs/obs.go +++ b/bindings/huawei/obs/obs.go @@ -104,16 +104,16 @@ func (o *HuaweiOBS) parseMetadata(meta bindings.Metadata) (*obsMetadata, error) } if m.Bucket == "" { - return nil, fmt.Errorf("missing obs bucket name") + return nil, errors.New("missing obs bucket name") } if m.Endpoint == "" { - return nil, fmt.Errorf("missing obs endpoint") + return nil, errors.New("missing obs endpoint") } if m.AccessKey == "" { - return nil, fmt.Errorf("missing the huawei access key") + return nil, errors.New("missing the huawei access key") } if m.SecretKey == "" { - return nil, fmt.Errorf("missing the huawei secret key") + return nil, errors.New("missing the huawei secret key") } o.logger.Debugf("Huawei OBS metadata=[%s]", m) @@ -212,7 +212,7 @@ func (o *HuaweiOBS) get(ctx context.Context, req *bindings.InvokeRequest) (*bind if val, ok := req.Metadata[metadataKey]; ok && val != "" { key = val } else { - return nil, fmt.Errorf("obs binding error: can't read key value") + return nil, errors.New("obs binding error: can't read key value") } input := &obs.GetObjectInput{} @@ -252,7 +252,7 @@ func (o *HuaweiOBS) delete(ctx context.Context, req *bindings.InvokeRequest) (*b if val, ok := req.Metadata[metadataKey]; ok && val != "" { key = val } else { - return nil, fmt.Errorf("obs binding error: can't read key value") + return nil, errors.New("obs binding error: can't read key value") } input := &obs.DeleteObjectInput{} diff --git a/bindings/huawei/obs/obs_test.go b/bindings/huawei/obs/obs_test.go index b87762f563..5ab85def17 100644 --- a/bindings/huawei/obs/obs_test.go +++ b/bindings/huawei/obs/obs_test.go @@ -17,7 +17,6 @@ import ( "context" "encoding/json" "errors" - "fmt" "io" "strings" "testing" @@ -107,7 +106,7 @@ func TestInit(t *testing.T) { } err := obs.Init(context.Background(), m) require.Error(t, err) - assert.Equal(t, err, fmt.Errorf("missing obs bucket name")) + assert.Equal(t, err, errors.New("missing obs bucket name")) }) t.Run("Init with missing access key", func(t *testing.T) { m := bindings.Metadata{} @@ -118,7 +117,7 @@ func TestInit(t *testing.T) { } err := obs.Init(context.Background(), m) require.Error(t, err) - assert.Equal(t, err, fmt.Errorf("missing the huawei access key")) + assert.Equal(t, err, errors.New("missing the huawei access key")) }) t.Run("Init with missing secret key", func(t *testing.T) { m := bindings.Metadata{} @@ -129,7 +128,7 @@ func TestInit(t *testing.T) { } err := obs.Init(context.Background(), m) require.Error(t, err) - assert.Equal(t, err, fmt.Errorf("missing the huawei secret key")) + assert.Equal(t, err, errors.New("missing the huawei secret key")) }) t.Run("Init with missing endpoint", func(t *testing.T) { m := bindings.Metadata{} @@ -140,7 +139,7 @@ func TestInit(t *testing.T) { } err := obs.Init(context.Background(), m) require.Error(t, err) - assert.Equal(t, err, fmt.Errorf("missing obs endpoint")) + assert.Equal(t, err, errors.New("missing obs endpoint")) }) } @@ -251,7 +250,7 @@ func TestCreateOperation(t *testing.T) { mo := &HuaweiOBS{ service: &MockHuaweiOBSService{ PutObjectFn: func(ctx context.Context, input *obs.PutObjectInput) (output *obs.PutObjectOutput, err error) { - return nil, fmt.Errorf("error while creating object") + return nil, errors.New("error while creating object") }, }, logger: logger.NewLogger("test"), @@ -343,7 +342,7 @@ func TestUploadOperation(t *testing.T) { mo := &HuaweiOBS{ service: &MockHuaweiOBSService{ PutFileFn: func(ctx context.Context, input *obs.PutFileInput) (output *obs.PutObjectOutput, err error) { - return nil, fmt.Errorf("error while creating object") + return nil, errors.New("error while creating object") }, }, logger: logger.NewLogger("test"), @@ -419,7 +418,7 @@ func TestGetOperation(t *testing.T) { mo := &HuaweiOBS{ service: &MockHuaweiOBSService{ GetObjectFn: func(ctx context.Context, input *obs.GetObjectInput) (output *obs.GetObjectOutput, err error) { - return nil, fmt.Errorf("error while getting object") + return nil, errors.New("error while getting object") }, }, logger: logger.NewLogger("test"), @@ -527,7 +526,7 @@ func TestDeleteOperation(t *testing.T) { mo := &HuaweiOBS{ service: &MockHuaweiOBSService{ DeleteObjectFn: func(ctx context.Context, input *obs.DeleteObjectInput) (output *obs.DeleteObjectOutput, err error) { - return nil, fmt.Errorf("error while deleting object") + return nil, errors.New("error while deleting object") }, }, logger: logger.NewLogger("test"), @@ -582,7 +581,7 @@ func TestListOperation(t *testing.T) { mo := &HuaweiOBS{ service: &MockHuaweiOBSService{ ListObjectsFn: func(ctx context.Context, input *obs.ListObjectsInput) (output *obs.ListObjectsOutput, err error) { - return nil, fmt.Errorf("error while listing objects") + return nil, errors.New("error while listing objects") }, }, logger: logger.NewLogger("test"), diff --git a/bindings/input_binding.go b/bindings/input_binding.go index b87f7b9d4c..8649dfb696 100644 --- a/bindings/input_binding.go +++ b/bindings/input_binding.go @@ -15,7 +15,7 @@ package bindings import ( "context" - "fmt" + "errors" "io" "github.com/dapr/components-contrib/health" @@ -43,6 +43,6 @@ func PingInpBinding(ctx context.Context, inputBinding InputBinding) error { if inputBindingWithPing, ok := inputBinding.(health.Pinger); ok { return inputBindingWithPing.Ping(ctx) } else { - return fmt.Errorf("ping is not implemented by this input binding") + return errors.New("ping is not implemented by this input binding") } } diff --git a/bindings/kafka/metadata.yaml b/bindings/kafka/metadata.yaml index 3b1a077a7b..ab24f3e8fe 100644 --- a/bindings/kafka/metadata.yaml +++ b/bindings/kafka/metadata.yaml @@ -331,4 +331,12 @@ metadata: description: | The TTL for schema caching when publishing a message with latest schema available. example: '"5m"' - default: '"5m"' \ No newline at end of file + default: '"5m"' + - name: escapeHeaders + type: bool + required: false + description: | + Enables URL escaping of the message header values. + It allows sending headers with special characters that are usually not allowed in HTTP headers. + example: "true" + default: "false" diff --git a/bindings/kubemq/options.go b/bindings/kubemq/options.go index 9b642c661c..a73f58b0e9 100644 --- a/bindings/kubemq/options.go +++ b/bindings/kubemq/options.go @@ -1,7 +1,7 @@ package kubemq import ( - "fmt" + "errors" "strconv" "strings" @@ -27,15 +27,15 @@ func parseAddress(address string) (string, int, error) { var err error hostPort := strings.Split(address, ":") if len(hostPort) != 2 { - return "", 0, fmt.Errorf("invalid kubemq address, address format is invalid") + return "", 0, errors.New("invalid kubemq address, address format is invalid") } host = hostPort[0] if len(host) == 0 { - return "", 0, fmt.Errorf("invalid kubemq address, host is empty") + return "", 0, errors.New("invalid kubemq address, host is empty") } port, err = strconv.Atoi(hostPort[1]) if err != nil { - return "", 0, fmt.Errorf("invalid kubemq address, port is invalid") + return "", 0, errors.New("invalid kubemq address, port is invalid") } return host, port, nil } @@ -64,19 +64,19 @@ func createOptions(md bindings.Metadata) (*options, error) { return nil, err } } else { - return nil, fmt.Errorf("invalid kubemq address, address is empty") + return nil, errors.New("invalid kubemq address, address is empty") } if result.Channel == "" { - return nil, fmt.Errorf("invalid kubemq channel, channel is empty") + return nil, errors.New("invalid kubemq channel, channel is empty") } if result.PollMaxItems < 1 { - return nil, fmt.Errorf("invalid kubemq pollMaxItems value, value must be greater than 0") + return nil, errors.New("invalid kubemq pollMaxItems value, value must be greater than 0") } if result.PollTimeoutSeconds < 1 { - return nil, fmt.Errorf("invalid kubemq pollTimeoutSeconds value, value must be greater than 0") + return nil, errors.New("invalid kubemq pollTimeoutSeconds value, value must be greater than 0") } return result, nil diff --git a/bindings/mqtt3/mqtt.go b/bindings/mqtt3/mqtt.go index bac9ae5ea6..401f18e236 100644 --- a/bindings/mqtt3/mqtt.go +++ b/bindings/mqtt3/mqtt.go @@ -95,7 +95,7 @@ func (m *MQTT) getProducer() (mqtt.Client, error) { } // mqtt broker allows only one connection at a given time from a clientID. - producerClientID := fmt.Sprintf("%s-producer", m.metadata.ClientID) + producerClientID := m.metadata.ClientID + "-producer" p, err := m.connect(producerClientID, false) if err != nil { return nil, err @@ -170,7 +170,7 @@ func (m *MQTT) Read(ctx context.Context, handler bindings.Handler) error { m.readHandler = handler // mqtt broker allows only one connection at a given time from a clientID - consumerClientID := fmt.Sprintf("%s-consumer", m.metadata.ClientID) + consumerClientID := m.metadata.ClientID + "-consumer" // Establish the connection // This will also create the subscription in the OnConnect handler @@ -299,7 +299,7 @@ func (m *MQTT) handleMessage() func(client mqtt.Client, mqttMsg mqtt.Message) { return func(client mqtt.Client, mqttMsg mqtt.Message) { bo := m.backOff if m.metadata.BackOffMaxRetries >= 0 { - bo = backoff.WithMaxRetries(bo, uint64(m.metadata.BackOffMaxRetries)) + bo = backoff.WithMaxRetries(bo, uint64(m.metadata.BackOffMaxRetries)) //nolint:gosec } err := retry.NotifyRecover( diff --git a/bindings/mysql/mysql.go b/bindings/mysql/mysql.go index 2064be8b25..4bcd99a009 100644 --- a/bindings/mysql/mysql.go +++ b/bindings/mysql/mysql.go @@ -114,7 +114,7 @@ func (m *Mysql) Init(ctx context.Context, md bindings.Metadata) error { } if meta.URL == "" { - return fmt.Errorf("missing MySql connection string") + return errors.New("missing MySql connection string") } m.db, err = initDB(meta.URL, meta.PemPath) @@ -281,7 +281,7 @@ func initDB(url, pemPath string) (*sql.DB, error) { ok := rootCertPool.AppendCertsFromPEM(pem) if !ok { - return nil, fmt.Errorf("failed to append PEM") + return nil, errors.New("failed to append PEM") } err = mysql.RegisterTLSConfig("custom", &tls.Config{ diff --git a/bindings/mysql/mysql_integration_test.go b/bindings/mysql/mysql_integration_test.go index 6c86396f7b..eadeaa31c1 100644 --- a/bindings/mysql/mysql_integration_test.go +++ b/bindings/mysql/mysql_integration_test.go @@ -91,7 +91,7 @@ func TestMysqlIntegration(t *testing.T) { }) t.Run("Invoke insert", func(t *testing.T) { - for i := 0; i < 10; i++ { + for i := range 10 { res, err := b.Invoke(context.Background(), &bindings.InvokeRequest{ Operation: execOperation, Metadata: map[string]string{ @@ -106,7 +106,7 @@ func TestMysqlIntegration(t *testing.T) { t.Run("Invoke update", func(t *testing.T) { date := time.Now().Add(time.Hour) - for i := 0; i < 10; i++ { + for i := range 10 { res, err := b.Invoke(context.Background(), &bindings.InvokeRequest{ Operation: execOperation, Metadata: map[string]string{ @@ -122,7 +122,7 @@ func TestMysqlIntegration(t *testing.T) { t.Run("Invoke update with parameters", func(t *testing.T) { date := time.Now().Add(2 * time.Hour) - for i := 0; i < 10; i++ { + for i := range 10 { res, err := b.Invoke(context.Background(), &bindings.InvokeRequest{ Operation: execOperation, Metadata: map[string]string{ diff --git a/bindings/output_binding.go b/bindings/output_binding.go index ac20b7dce8..69ecbccbe3 100644 --- a/bindings/output_binding.go +++ b/bindings/output_binding.go @@ -15,7 +15,7 @@ package bindings import ( "context" - "fmt" + "errors" "io" "github.com/dapr/components-contrib/health" @@ -37,6 +37,6 @@ func PingOutBinding(ctx context.Context, outputBinding OutputBinding) error { if outputBindingWithPing, ok := outputBinding.(health.Pinger); ok { return outputBindingWithPing.Ping(ctx) } else { - return fmt.Errorf("ping is not implemented by this output binding") + return errors.New("ping is not implemented by this output binding") } } diff --git a/bindings/postgres/postgres_test.go b/bindings/postgres/postgres_test.go index 9f9cf207b5..c24fc099fb 100644 --- a/bindings/postgres/postgres_test.go +++ b/bindings/postgres/postgres_test.go @@ -87,7 +87,7 @@ func TestPostgresIntegration(t *testing.T) { }) t.Run("Invoke insert", func(t *testing.T) { - for i := 0; i < 10; i++ { + for i := range 10 { req.Metadata[commandSQLKey] = fmt.Sprintf(testInsert, i, i, time.Now().Format(time.RFC3339)) res, err := b.Invoke(ctx, req) assertResponse(t, res, err) @@ -95,7 +95,7 @@ func TestPostgresIntegration(t *testing.T) { }) t.Run("Invoke update", func(t *testing.T) { - for i := 0; i < 10; i++ { + for i := range 10 { req.Metadata[commandSQLKey] = fmt.Sprintf(testUpdate, time.Now().Format(time.RFC3339), i) res, err := b.Invoke(ctx, req) assertResponse(t, res, err) diff --git a/bindings/postmark/postmark.go b/bindings/postmark/postmark.go index 30197f03b4..526d2b4e70 100644 --- a/bindings/postmark/postmark.go +++ b/bindings/postmark/postmark.go @@ -104,7 +104,7 @@ func (p *Postmark) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bi email.From = req.Metadata["emailFrom"] } if len(email.From) == 0 { - return nil, fmt.Errorf("error Postmark from email not supplied") + return nil, errors.New("error Postmark from email not supplied") } // Build email to address, this is required @@ -115,7 +115,7 @@ func (p *Postmark) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bi email.To = req.Metadata["emailTo"] } if len(email.To) == 0 { - return nil, fmt.Errorf("error Postmark to email not supplied") + return nil, errors.New("error Postmark to email not supplied") } // Build email subject, this is required @@ -126,7 +126,7 @@ func (p *Postmark) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*bi email.Subject = req.Metadata["subject"] } if len(email.Subject) == 0 { - return nil, fmt.Errorf("error Postmark subject not supplied") + return nil, errors.New("error Postmark subject not supplied") } // Build email cc address, this is optional diff --git a/bindings/rocketmq/rocketmq.go b/bindings/rocketmq/rocketmq.go index 8b9ed0e50f..65eaad967b 100644 --- a/bindings/rocketmq/rocketmq.go +++ b/bindings/rocketmq/rocketmq.go @@ -89,7 +89,7 @@ func (a *RocketMQ) Read(ctx context.Context, handler bindings.Handler) error { } if len(a.settings.Topics) == 0 { - return fmt.Errorf("binding-rocketmq error: must configure topics") + return errors.New("binding-rocketmq error: must configure topics") } for _, topicStr := range a.settings.Topics { diff --git a/bindings/rocketmq/rocketmq_test.go b/bindings/rocketmq/rocketmq_test.go index 4cb162257e..885e7d8cea 100644 --- a/bindings/rocketmq/rocketmq_test.go +++ b/bindings/rocketmq/rocketmq_test.go @@ -55,7 +55,7 @@ func TestInputBindingRead(t *testing.T) { //nolint:paralleltest require.NoError(t, err) time.Sleep(10 * time.Second) - for i := 0; i < 30; i++ { + for range 30 { if atomic.LoadInt32(&count) > 0 { break } diff --git a/bindings/smtp/smtp.go b/bindings/smtp/smtp.go index 47467e092d..dd317a061d 100644 --- a/bindings/smtp/smtp.go +++ b/bindings/smtp/smtp.go @@ -88,13 +88,13 @@ func (s *Mailer) Invoke(_ context.Context, req *bindings.InvokeRequest) (*bindin return nil, err } if metadata.EmailFrom == "" { - return nil, fmt.Errorf("smtp binding error: emailFrom property not supplied in configuration- or request-metadata") + return nil, errors.New("smtp binding error: emailFrom property not supplied in configuration- or request-metadata") } if metadata.EmailTo == "" { - return nil, fmt.Errorf("smtp binding error: emailTo property not supplied in configuration- or request-metadata") + return nil, errors.New("smtp binding error: emailTo property not supplied in configuration- or request-metadata") } if metadata.Subject == "" { - return nil, fmt.Errorf("smtp binding error: subject property not supplied in configuration- or request-metadata") + return nil, errors.New("smtp binding error: subject property not supplied in configuration- or request-metadata") } // Compose message @@ -168,7 +168,6 @@ func (s *Mailer) parseMetadata(meta bindings.Metadata) (Metadata, error) { } err = smtpMeta.parsePriority(meta.Properties["priority"]) - if err != nil { return smtpMeta, err } diff --git a/bindings/twilio/sendgrid/sendgrid.go b/bindings/twilio/sendgrid/sendgrid.go index a065b9813f..1e2229c84c 100644 --- a/bindings/twilio/sendgrid/sendgrid.go +++ b/bindings/twilio/sendgrid/sendgrid.go @@ -136,7 +136,7 @@ func (sg *SendGrid) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*b fromAddress = mail.NewEmail(fromName, req.Metadata["emailFrom"]) } if fromAddress == nil { - return nil, fmt.Errorf("error SendGrid from email not supplied") + return nil, errors.New("error SendGrid from email not supplied") } // Build email to address, this is required @@ -160,7 +160,7 @@ func (sg *SendGrid) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*b toAddress = mail.NewEmail(toName, req.Metadata["emailTo"]) } if toAddress == nil { - return nil, fmt.Errorf("error SendGrid to email not supplied") + return nil, errors.New("error SendGrid to email not supplied") } // Build email subject, this is required @@ -172,7 +172,7 @@ func (sg *SendGrid) Invoke(ctx context.Context, req *bindings.InvokeRequest) (*b subject = req.Metadata["subject"] } if subject == "" { - return nil, fmt.Errorf("error SendGrid subject not supplied") + return nil, errors.New("error SendGrid subject not supplied") } // Build email cc address, this is optional diff --git a/bindings/wasm/output.go b/bindings/wasm/output.go index 424b2dd7f3..8855d1f7de 100644 --- a/bindings/wasm/output.go +++ b/bindings/wasm/output.go @@ -16,6 +16,7 @@ package wasm import ( "bytes" "context" + "errors" "fmt" "io" "reflect" @@ -91,7 +92,7 @@ func (out *outputBinding) Init(ctx context.Context, metadata bindings.Metadata) if _, found := imports[modeWasiHTTP]; found { if out.meta.StrictSandbox { _ = out.runtime.Close(context.Background()) - return fmt.Errorf("can not instantiate wasi-http with strict sandbox") + return errors.New("can not instantiate wasi-http with strict sandbox") } err = wasi_http.MakeWasiHTTP().Instantiate(ctx, out.runtime) } diff --git a/bindings/wasm/output_test.go b/bindings/wasm/output_test.go index b5e765c0b1..502591e454 100644 --- a/bindings/wasm/output_test.go +++ b/bindings/wasm/output_test.go @@ -172,7 +172,7 @@ func Test_Invoke(t *testing.T) { if tc.expectedErr == "" { // execute twice to prove idempotency - for i := 0; i < 2; i++ { + for range 2 { resp, outputErr := output.Invoke(reqCtx, tc.request) require.NoError(t, outputErr) require.Equal(t, tc.expectedData, string(resp.Data)) @@ -258,7 +258,7 @@ func Test_InvokeHttp(t *testing.T) { if tc.expectedErr == "" { // execute twice to prove idempotency - for i := 0; i < 2; i++ { + for range 2 { resp, outputErr := output.Invoke(reqCtx, tc.request) require.NoError(t, outputErr) require.Equal(t, tc.expectedData, string(resp.Data)) @@ -292,7 +292,7 @@ func TestEnsureConcurrency(t *testing.T) { // Wasm is running in goroutine, use wait group to ensure all goroutines are finished wg := sync.WaitGroup{} // 100 is enough to trigger concurrency, and wasm should be executed run fast enough to not consuming too much time - for i := 0; i < 100; i++ { + for i := range 100 { wg.Add(1) go func(i int) { request := &bindings.InvokeRequest{ diff --git a/bindings/zeebe/jobworker/jobworker.go b/bindings/zeebe/jobworker/jobworker.go index 63384c5aa3..ff3299cc73 100644 --- a/bindings/zeebe/jobworker/jobworker.go +++ b/bindings/zeebe/jobworker/jobworker.go @@ -104,7 +104,7 @@ func (z *ZeebeJobWorker) Init(ctx context.Context, metadata bindings.Metadata) e func (z *ZeebeJobWorker) Read(ctx context.Context, handler bindings.Handler) error { if z.closed.Load() { - return fmt.Errorf("binding is closed") + return errors.New("binding is closed") } var retryBackOff *time.Duration diff --git a/common/authentication/aws/aws.go b/common/authentication/aws/aws.go index 26d4c9fe63..48c8b209a4 100644 --- a/common/authentication/aws/aws.go +++ b/common/authentication/aws/aws.go @@ -148,7 +148,7 @@ func (opts *AWSIAMAuthOptions) GetAccessToken(ctx context.Context) (string, erro return authenticationToken, nil case err != nil: - return "", fmt.Errorf("failed to load default AWS authentication configuration") + return "", errors.New("failed to load default AWS authentication configuration") } authenticationToken, err = auth.BuildAuthToken( diff --git a/common/authentication/azure/auth.go b/common/authentication/azure/auth.go index 98418dc14f..cf588a7e84 100644 --- a/common/authentication/azure/auth.go +++ b/common/authentication/azure/auth.go @@ -234,7 +234,7 @@ func (s EnvironmentSettings) GetTokenCredential() (azcore.TokenCredential, error break } else { // If authMethod is "none", we don't add any provider and return an error - return nil, fmt.Errorf("all Azure auth methods have been disabled with auth method 'None'") + return nil, errors.New("all Azure auth methods have been disabled with auth method 'None'") } } } @@ -412,7 +412,7 @@ func (c CertConfig) decodePEM(data []byte) (certificate *x509.Certificate, priva parsedKey any ok bool ) - for i := 0; i < 2; i++ { + for range 2 { block, data = pem.Decode(data) if block == nil { break diff --git a/common/authentication/postgresql/metadata.go b/common/authentication/postgresql/metadata.go index ce86ca2eee..7cacecfaa4 100644 --- a/common/authentication/postgresql/metadata.go +++ b/common/authentication/postgresql/metadata.go @@ -109,7 +109,7 @@ func (m *PostgresAuthMetadata) GetPgxPoolConfig() (*pgxpool.Config, error) { config.MaxConnIdleTime = m.ConnectionMaxIdleTime } if m.MaxConns > 1 { - config.MaxConns = int32(m.MaxConns) + config.MaxConns = int32(m.MaxConns) //nolint:gosec } if m.QueryExecMode != "" { diff --git a/common/authentication/sqlite/metadata.go b/common/authentication/sqlite/metadata.go index ef54cffb79..e0a4a436a5 100644 --- a/common/authentication/sqlite/metadata.go +++ b/common/authentication/sqlite/metadata.go @@ -190,7 +190,7 @@ func ValidIdentifier(v string) bool { // Loop through the string as byte slice as we only care about ASCII characters b := []byte(v) - for i := 0; i < len(b); i++ { + for i := range b { if (b[i] >= '0' && b[i] <= '9') || (b[i] >= 'a' && b[i] <= 'z') || (b[i] >= 'A' && b[i] <= 'Z') || diff --git a/common/authentication/sqlserver/metadata.go b/common/authentication/sqlserver/metadata.go index 6543b301a0..003fbdba7f 100644 --- a/common/authentication/sqlserver/metadata.go +++ b/common/authentication/sqlserver/metadata.go @@ -51,10 +51,10 @@ func (m *SQLServerAuthMetadata) Validate(meta map[string]string) (err error) { return errors.New("missing connection string") } if !IsValidSQLName(m.DatabaseName) { - return fmt.Errorf("invalid database name, accepted characters are (A-Z, a-z, 0-9, _)") + return errors.New("invalid database name, accepted characters are (A-Z, a-z, 0-9, _)") } if !IsValidSQLName(m.SchemaName) { - return fmt.Errorf("invalid schema name, accepted characters are (A-Z, a-z, 0-9, _)") + return errors.New("invalid schema name, accepted characters are (A-Z, a-z, 0-9, _)") } // If using Azure AD diff --git a/common/component/azure/blobstorage/client.go b/common/component/azure/blobstorage/client.go index 70e0f87f25..ca054a4f37 100644 --- a/common/component/azure/blobstorage/client.go +++ b/common/component/azure/blobstorage/client.go @@ -109,7 +109,7 @@ func (opts *ContainerClientOpts) GetContainerURL(azEnvSettings azauth.Environmen if opts.customEndpoint != "" { u, err = url.Parse(fmt.Sprintf("%s/%s/%s", opts.customEndpoint, opts.AccountName, opts.ContainerName)) if err != nil { - return nil, fmt.Errorf("failed to get container's URL with custom endpoint") + return nil, errors.New("failed to get container's URL with custom endpoint") } } else { u = opts.getAzureBlobStorageContainerURL(azEnvSettings) diff --git a/common/component/azure/blobstorage/request.go b/common/component/azure/blobstorage/request.go index 6aa6d7945b..34ccd8dcd0 100644 --- a/common/component/azure/blobstorage/request.go +++ b/common/component/azure/blobstorage/request.go @@ -15,7 +15,7 @@ package blobstorage import ( b64 "encoding/base64" - "fmt" + "errors" "strings" "github.com/Azure/azure-sdk-for-go/sdk/storage/azblob/blob" @@ -56,7 +56,7 @@ func CreateBlobHTTPHeadersFromRequest(meta map[string]string, contentType *strin if val, ok := meta[caseMap[contentMD5Key]]; ok && val != "" { sDec, err := b64.StdEncoding.DecodeString(val) if err != nil || len(sDec) != 16 { - return blob.HTTPHeaders{}, fmt.Errorf("the MD5 value specified in Content MD5 is invalid, MD5 value must be 128 bits and base64 encoded") + return blob.HTTPHeaders{}, errors.New("the MD5 value specified in Content MD5 is invalid, MD5 value must be 128 bits and base64 encoded") } blobHTTPHeaders.BlobContentMD5 = sDec delete(meta, caseMap[contentMD5Key]) @@ -88,7 +88,7 @@ func SanitizeMetadata(log logger.Logger, metadata map[string]string) map[string] // Keep only letters and digits n := 0 newKey := make([]byte, len(key)) - for i := 0; i < len(key); i++ { + for i := range len(key) { if (key[i] >= 'A' && key[i] <= 'Z') || (key[i] >= 'a' && key[i] <= 'z') || (key[i] >= '0' && key[i] <= '9') { @@ -106,7 +106,7 @@ func SanitizeMetadata(log logger.Logger, metadata map[string]string) map[string] // Remove all non-ascii characters n = 0 newVal := make([]byte, len(val)) - for i := 0; i < len(val); i++ { + for i := range len(val) { if val[i] > 127 || val[i] == 0 { continue } diff --git a/common/component/azure/eventhubs/eventhubs.go b/common/component/azure/eventhubs/eventhubs.go index e4e80412ec..f5724e891f 100644 --- a/common/component/azure/eventhubs/eventhubs.go +++ b/common/component/azure/eventhubs/eventhubs.go @@ -115,7 +115,7 @@ func (aeh *AzureEventHubs) Init(metadata map[string]string) error { aeh.backOffConfig.MaxRetries = 3 err = retry.DecodeConfigWithPrefix(&aeh.backOffConfig, metadata, "backOff") if err != nil { - return fmt.Errorf("failed to decode backoff configuration") + return errors.New("failed to decode backoff configuration") } return nil @@ -365,15 +365,13 @@ func (aeh *AzureEventHubs) processEvents(subscribeCtx context.Context, partition // Loop to receive messages var ( - ctx context.Context - cancel context.CancelFunc events []*azeventhubs.ReceivedEventData err error ) counter := 0 for { // Maximum duration to wait till bulk message is sent to app is `maxBulkSubAwaitDurationMs` - ctx, cancel = context.WithTimeout(subscribeCtx, time.Duration(config.MaxBulkSubAwaitDurationMs)*time.Millisecond) + ctx, cancel := context.WithTimeout(subscribeCtx, time.Duration(config.MaxBulkSubAwaitDurationMs)*time.Millisecond) // Receive events with batchsize of `maxBulkSubCount` events, err = partitionClient.ReceiveEvents(ctx, config.MaxBulkSubCount, nil) cancel() diff --git a/common/component/azure/servicebus/client.go b/common/component/azure/servicebus/client.go index 7aa74eebf3..a775b45eba 100644 --- a/common/component/azure/servicebus/client.go +++ b/common/component/azure/servicebus/client.go @@ -185,7 +185,7 @@ func (c *Client) CloseAllSenders(log logger.Logger) { <-workersCh }(k, t) } - for i := 0; i < cap(workersCh); i++ { + for range cap(workersCh) { // Wait for all workers to be done workersCh <- true } diff --git a/common/component/azure/servicebus/message_pubsub_test.go b/common/component/azure/servicebus/message_pubsub_test.go index 3495897515..4e15560c3d 100644 --- a/common/component/azure/servicebus/message_pubsub_test.go +++ b/common/component/azure/servicebus/message_pubsub_test.go @@ -76,7 +76,6 @@ func TestAddMessageAttributesToMetadata(t *testing.T) { } for _, tc := range testCases { - tc := tc for mType, mMap := range metadataMap { t.Run(fmt.Sprintf("%s, metadata is %s", tc.name, mType), func(t *testing.T) { actual := addMessageAttributesToMetadata(mMap, &tc.ASBMessage) diff --git a/common/component/azure/servicebus/publisher.go b/common/component/azure/servicebus/publisher.go index 372cc1f1f2..26b4ac22a4 100644 --- a/common/component/azure/servicebus/publisher.go +++ b/common/component/azure/servicebus/publisher.go @@ -191,7 +191,7 @@ func (c *Client) PublishBinding(ctx context.Context, req *bindings.InvokeRequest func (c *Client) publishBackOff(ctx context.Context) (bo backoff.BackOff) { ebo := backoff.NewExponentialBackOff() ebo.InitialInterval = time.Duration(c.metadata.PublishInitialRetryIntervalInMs) * time.Millisecond - bo = backoff.WithMaxRetries(ebo, uint64(c.metadata.PublishMaxRetries)) + bo = backoff.WithMaxRetries(ebo, uint64(c.metadata.PublishMaxRetries)) //nolint:gosec bo = backoff.WithContext(bo, ctx) return bo } diff --git a/common/component/azure/servicebus/subscription.go b/common/component/azure/servicebus/subscription.go index a37e8777e5..7ff5949fe9 100644 --- a/common/component/azure/servicebus/subscription.go +++ b/common/component/azure/servicebus/subscription.go @@ -331,7 +331,7 @@ func (s *Subscription) doRenewLocks(ctx context.Context, receiver *MessageReceiv err error errored int ) - for i := 0; i < len(msgs); i++ { + for range len(msgs) { // This is a nop if the received error is nil if multierr.AppendInto(&err, <-errCh) { errored++ @@ -548,7 +548,7 @@ func (s *Subscription) CompleteMessage(ctx context.Context, receiver Receiver, m func (s *Subscription) addActiveMessage(m *azservicebus.ReceivedMessage) error { if m.SequenceNumber == nil { - return fmt.Errorf("message sequence number is nil") + return errors.New("message sequence number is nil") } var logSuffix string diff --git a/common/component/cloudflare/workers/workers.go b/common/component/cloudflare/workers/workers.go index 9038d78d1a..fd89135a89 100644 --- a/common/component/cloudflare/workers/workers.go +++ b/common/component/cloudflare/workers/workers.go @@ -20,6 +20,7 @@ import ( "crypto/x509" "encoding/json" "encoding/pem" + "errors" "fmt" "io" "mime/multipart" @@ -188,7 +189,7 @@ func (w *Base) getWorkersSubdomain() (string, error) { } if data.Result.Subdomain == "" { - return "", fmt.Errorf("response does not contain a value for 'subdomain'") + return "", errors.New("response does not contain a value for 'subdomain'") } return data.Result.Subdomain, nil diff --git a/common/component/kafka/auth.go b/common/component/kafka/auth.go index 43d195e28c..bd61690c05 100644 --- a/common/component/kafka/auth.go +++ b/common/component/kafka/auth.go @@ -43,7 +43,7 @@ func updatePasswordAuthInfo(config *sarama.Config, metadata *KafkaMetadata, sasl func updateMTLSAuthInfo(config *sarama.Config, metadata *KafkaMetadata) error { if metadata.TLSDisable { - return fmt.Errorf("kafka: cannot configure mTLS authentication when TLSDisable is 'true'") + return errors.New("kafka: cannot configure mTLS authentication when TLSDisable is 'true'") } cert, err := tls.X509KeyPair([]byte(metadata.TLSClientCert), []byte(metadata.TLSClientKey)) if err != nil { diff --git a/common/component/kafka/consumer.go b/common/component/kafka/consumer.go index 4b30ed58b8..7cb923a455 100644 --- a/common/component/kafka/consumer.go +++ b/common/component/kafka/consumer.go @@ -16,6 +16,7 @@ package kafka import ( "errors" "fmt" + "net/url" "strconv" "sync" "time" @@ -132,11 +133,11 @@ func (consumer *consumer) doBulkCallback(session sarama.ConsumerGroupSession, messages []*sarama.ConsumerMessage, handler BulkEventHandler, topic string, ) error { consumer.k.logger.Debugf("Processing Kafka bulk message: %s", topic) - messageValues := make([]KafkaBulkMessageEntry, (len(messages))) + messageValues := make([]KafkaBulkMessageEntry, len(messages)) for i, message := range messages { if message != nil { - metadata := GetEventMetadata(message) + metadata := GetEventMetadata(message, consumer.k.escapeHeaders) handlerConfig, err := consumer.k.GetTopicHandlerConfig(message.Topic) if err != nil { return err @@ -196,7 +197,7 @@ func (consumer *consumer) doCallback(session sarama.ConsumerGroupSession, messag Topic: message.Topic, Data: messageVal, } - event.Metadata = GetEventMetadata(message) + event.Metadata = GetEventMetadata(message, consumer.k.escapeHeaders) err = handlerConfig.Handler(session.Context(), &event) if err == nil { @@ -205,18 +206,26 @@ func (consumer *consumer) doCallback(session sarama.ConsumerGroupSession, messag return err } -func GetEventMetadata(message *sarama.ConsumerMessage) map[string]string { +func GetEventMetadata(message *sarama.ConsumerMessage, escapeHeaders bool) map[string]string { if message != nil { metadata := make(map[string]string, len(message.Headers)+5) if message.Key != nil { - metadata[keyMetadataKey] = string(message.Key) + if escapeHeaders { + metadata[keyMetadataKey] = url.QueryEscape(string(message.Key)) + } else { + metadata[keyMetadataKey] = string(message.Key) + } } metadata[offsetMetadataKey] = strconv.FormatInt(message.Offset, 10) metadata[topicMetadataKey] = message.Topic metadata[timestampMetadataKey] = strconv.FormatInt(message.Timestamp.UnixMilli(), 10) metadata[partitionMetadataKey] = strconv.FormatInt(int64(message.Partition), 10) for _, header := range message.Headers { - metadata[string(header.Key)] = string(header.Value) + if escapeHeaders { + metadata[string(header.Key)] = url.QueryEscape(string(header.Value)) + } else { + metadata[string(header.Key)] = string(header.Value) + } } return metadata } diff --git a/common/component/kafka/kafka.go b/common/component/kafka/kafka.go index 3f3bfca8c4..2f3b67be0d 100644 --- a/common/component/kafka/kafka.go +++ b/common/component/kafka/kafka.go @@ -45,6 +45,7 @@ type Kafka struct { saslPassword string initialOffset int64 config *sarama.Config + escapeHeaders bool cg sarama.ConsumerGroup subscribeTopics TopicHandlerConfig @@ -136,6 +137,7 @@ func (k *Kafka) Init(ctx context.Context, metadata map[string]string) error { k.consumerGroup = meta.ConsumerGroup k.initialOffset = meta.internalInitialOffset k.authType = meta.AuthType + k.escapeHeaders = meta.EscapeHeaders config := sarama.NewConfig() config.Version = meta.internalVersion @@ -278,7 +280,7 @@ func (k *Kafka) DeserializeValue(message *sarama.ConsumerMessage, config Subscri return nil, err } if len(message.Value) < 5 { - return nil, fmt.Errorf("value is too short") + return nil, errors.New("value is too short") } schemaID := binary.BigEndian.Uint32(message.Value[1:5]) schema, err := srClient.GetSchema(int(schemaID)) @@ -385,7 +387,7 @@ func (k *Kafka) SerializeValue(topic string, data []byte, metadata map[string]st return nil, err } schemaIDBytes := make([]byte, 4) - binary.BigEndian.PutUint32(schemaIDBytes, uint32(schema.ID())) + binary.BigEndian.PutUint32(schemaIDBytes, uint32(schema.ID())) //nolint:gosec recordValue := make([]byte, 0, len(schemaIDBytes)+len(valueBytes)+1) recordValue = append(recordValue, byte(0)) diff --git a/common/component/kafka/kafka_test.go b/common/component/kafka/kafka_test.go index 2e9ac3fbe7..3fbe8c7a2e 100644 --- a/common/component/kafka/kafka_test.go +++ b/common/component/kafka/kafka_test.go @@ -65,7 +65,7 @@ func TestDeserializeValue(t *testing.T) { } schemaIDBytes := make([]byte, 4) - binary.BigEndian.PutUint32(schemaIDBytes, uint32(schema.ID())) + binary.BigEndian.PutUint32(schemaIDBytes, uint32(schema.ID())) //nolint:gosec valJSON, _ := json.Marshal(testValue1) codec, _ := goavro.NewCodecForStandardJSONFull(testSchema1) diff --git a/common/component/kafka/metadata.go b/common/component/kafka/metadata.go index 4c1c175cd8..c4d0a6bb56 100644 --- a/common/component/kafka/metadata.go +++ b/common/component/kafka/metadata.go @@ -89,6 +89,7 @@ type KafkaMetadata struct { HeartbeatInterval time.Duration `mapstructure:"heartbeatInterval"` SessionTimeout time.Duration `mapstructure:"sessionTimeout"` Version string `mapstructure:"version"` + EscapeHeaders bool `mapstructure:"escapeHeaders"` internalVersion sarama.KafkaVersion `mapstructure:"-"` internalOidcExtensions map[string]string `mapstructure:"-"` @@ -162,6 +163,7 @@ func (k *Kafka) getKafkaMetadata(meta map[string]string) (*KafkaMetadata, error) ClientConnectionKeepAliveInterval: defaultClientConnectionKeepAliveInterval, HeartbeatInterval: 3 * time.Second, SessionTimeout: 10 * time.Second, + EscapeHeaders: false, } err := metadata.DecodeMetadata(meta, &m) @@ -288,7 +290,7 @@ func (k *Kafka) getKafkaMetadata(meta map[string]string) (*KafkaMetadata, error) if err != nil { return nil, fmt.Errorf("kafka error: invalid value for '%s' attribute: %w", consumeRetryInterval, err) } - m.ConsumeRetryInterval = time.Duration(intVal) * time.Millisecond + m.ConsumeRetryInterval = time.Duration(intVal) * time.Millisecond //nolint:gosec } } diff --git a/common/component/kafka/metadata_test.go b/common/component/kafka/metadata_test.go index 3006f5f3fd..e53b1721d8 100644 --- a/common/component/kafka/metadata_test.go +++ b/common/component/kafka/metadata_test.go @@ -15,6 +15,7 @@ package kafka import ( "fmt" + "net/url" "strconv" "testing" "time" @@ -512,7 +513,7 @@ func TestGetEventMetadata(t *testing.T) { m := sarama.ConsumerMessage{ Headers: nil, Timestamp: ts, Key: []byte("MyKey"), Value: []byte("MyValue"), Partition: 0, Offset: 123, Topic: "TestTopic", } - act := GetEventMetadata(&m) + act := GetEventMetadata(&m, false) require.Len(t, act, 5) require.Equal(t, strconv.FormatInt(ts.UnixMilli(), 10), act["__timestamp"]) require.Equal(t, "MyKey", act["__key"]) @@ -529,7 +530,7 @@ func TestGetEventMetadata(t *testing.T) { m := sarama.ConsumerMessage{ Headers: headers, Timestamp: ts, Key: []byte("MyKey"), Value: []byte("MyValue"), Partition: 0, Offset: 123, Topic: "TestTopic", } - act := GetEventMetadata(&m) + act := GetEventMetadata(&m, false) require.Len(t, act, 7) require.Equal(t, strconv.FormatInt(ts.UnixMilli(), 10), act["__timestamp"]) require.Equal(t, "MyKey", act["__key"]) @@ -544,7 +545,7 @@ func TestGetEventMetadata(t *testing.T) { m := sarama.ConsumerMessage{ Headers: nil, Timestamp: ts, Key: nil, Value: []byte("MyValue"), Partition: 0, Offset: 123, Topic: "TestTopic", } - act := GetEventMetadata(&m) + act := GetEventMetadata(&m, false) require.Len(t, act, 4) require.Equal(t, strconv.FormatInt(ts.UnixMilli(), 10), act["__timestamp"]) require.Equal(t, "0", act["__partition"]) @@ -553,7 +554,59 @@ func TestGetEventMetadata(t *testing.T) { }) t.Run("null message", func(t *testing.T) { - act := GetEventMetadata(nil) + act := GetEventMetadata(nil, false) require.Nil(t, act) }) + + t.Run("key with invalid value escapeHeaders true", func(t *testing.T) { + keyValue := "key1\xFF" + escapedKeyValue := url.QueryEscape(keyValue) + + m := sarama.ConsumerMessage{ + Headers: nil, Timestamp: ts, Key: []byte(keyValue), Value: []byte("MyValue"), Partition: 0, Offset: 123, Topic: "TestTopic", + } + act := GetEventMetadata(&m, true) + require.Equal(t, escapedKeyValue, act[keyMetadataKey]) + }) + + t.Run("key with invalid value escapeHeaders false", func(t *testing.T) { + keyValue := "key1\xFF" + + m := sarama.ConsumerMessage{ + Headers: nil, Timestamp: ts, Key: []byte(keyValue), Value: []byte("MyValue"), Partition: 0, Offset: 123, Topic: "TestTopic", + } + act := GetEventMetadata(&m, false) + require.Equal(t, keyValue, act[keyMetadataKey]) + }) + + t.Run("header with invalid value escapeHeaders true", func(t *testing.T) { + headerKey := "key1" + headerValue := "value1\xFF" + escapedHeaderValue := url.QueryEscape(headerValue) + + headers := []*sarama.RecordHeader{ + {Key: []byte(headerKey), Value: []byte(headerValue)}, + } + m := sarama.ConsumerMessage{ + Headers: headers, Timestamp: ts, Key: []byte("MyKey"), Value: []byte("MyValue"), Partition: 0, Offset: 123, Topic: "TestTopic", + } + act := GetEventMetadata(&m, true) + require.Len(t, act, 6) + require.Equal(t, escapedHeaderValue, act[headerKey]) + }) + + t.Run("header with invalid value escapeHeaders false", func(t *testing.T) { + headerKey := "key1" + headerValue := "value1\xFF" + + headers := []*sarama.RecordHeader{ + {Key: []byte(headerKey), Value: []byte(headerValue)}, + } + m := sarama.ConsumerMessage{ + Headers: headers, Timestamp: ts, Key: []byte("MyKey"), Value: []byte("MyValue"), Partition: 0, Offset: 123, Topic: "TestTopic", + } + act := GetEventMetadata(&m, false) + require.Len(t, act, 6) + require.Equal(t, headerValue, act[headerKey]) + }) } diff --git a/common/component/kafka/sasl_oauthbearer.go b/common/component/kafka/sasl_oauthbearer.go index b591c1fbb8..125956617c 100644 --- a/common/component/kafka/sasl_oauthbearer.go +++ b/common/component/kafka/sasl_oauthbearer.go @@ -18,6 +18,7 @@ import ( "crypto/tls" "crypto/x509" "encoding/pem" + "errors" "fmt" "net/http" "time" @@ -58,7 +59,7 @@ func (ts *OAuthTokenSource) addCa(caPem string) error { block, _ := pem.Decode(pemBytes) if block == nil || block.Type != "CERTIFICATE" { - return fmt.Errorf("PEM data not valid or not of a valid type (CERTIFICATE)") + return errors.New("PEM data not valid or not of a valid type (CERTIFICATE)") } caCert, err := x509.ParseCertificate(block.Bytes) @@ -109,7 +110,7 @@ func (ts *OAuthTokenSource) Token() (*sarama.AccessToken, error) { } if ts.TokenEndpoint.TokenURL == "" || ts.ClientID == "" || ts.ClientSecret == "" { - return nil, fmt.Errorf("cannot generate token, OAuthTokenSource not fully configured") + return nil, errors.New("cannot generate token, OAuthTokenSource not fully configured") } oidcCfg := ccred.Config{ClientID: ts.ClientID, ClientSecret: ts.ClientSecret, Scopes: ts.Scopes, TokenURL: ts.TokenEndpoint.TokenURL, AuthStyle: ts.TokenEndpoint.AuthStyle} diff --git a/common/component/kafka/subscriber_test.go b/common/component/kafka/subscriber_test.go index f54948e341..57b87cf4f2 100644 --- a/common/component/kafka/subscriber_test.go +++ b/common/component/kafka/subscriber_test.go @@ -503,7 +503,7 @@ func Test_Subscribe(t *testing.T) { } ctx, cancel := context.WithCancel(context.Background()) - for i := 0; i < 100; i++ { + for i := range 100 { go func(i int) { k.Subscribe(ctx, SubscriptionHandlerConfig{}, strconv.Itoa(i)) }(i) diff --git a/common/component/redis/redis.go b/common/component/redis/redis.go index d5ecb187ab..818a4e6a1a 100644 --- a/common/component/redis/redis.go +++ b/common/component/redis/redis.go @@ -151,7 +151,7 @@ func ParseClientFromProperties(properties map[string]string, componentType metad if processingTimeoutMs, parseErr := strconv.ParseUint(val, 10, 64); parseErr == nil { // because of legacy reasons, we need to interpret a number as milliseconds // the library would default to seconds otherwise - settings.ProcessingTimeout = time.Duration(processingTimeoutMs) * time.Millisecond + settings.ProcessingTimeout = time.Duration(processingTimeoutMs) * time.Millisecond //nolint:gosec } // if there was an error we would try to interpret it as a duration string, which was already done in Decode() } @@ -160,7 +160,7 @@ func ParseClientFromProperties(properties map[string]string, componentType metad if redeliverIntervalMs, parseErr := strconv.ParseUint(val, 10, 64); parseErr == nil { // because of legacy reasons, we need to interpret a number as milliseconds // the library would default to seconds otherwise - settings.RedeliverInterval = time.Duration(redeliverIntervalMs) * time.Millisecond + settings.RedeliverInterval = time.Duration(redeliverIntervalMs) * time.Millisecond //nolint:gosec } // if there was an error we would try to interpret it as a duration string, which was already done in Decode() } @@ -364,7 +364,7 @@ func GetServerVersion(c RedisClient) (string, error) { return strings.TrimSpace(strings.Split(row, ":")[1]), nil } } - return "", fmt.Errorf("could not find redis_version in redis info response") + return "", errors.New("could not find redis_version in redis info response") } // GetConnectedSlaves returns the number of slaves connected to the Redis master. diff --git a/common/component/redis/v8client.go b/common/component/redis/v8client.go index ffce3f56d9..16571489f5 100644 --- a/common/component/redis/v8client.go +++ b/common/component/redis/v8client.go @@ -400,7 +400,7 @@ func newV8Client(s *Settings) (RedisClient, error) { /* #nosec */ if s.EnableTLS { options.TLSConfig = &tls.Config{ - InsecureSkipVerify: s.EnableTLS, //nolint:gosec + InsecureSkipVerify: s.EnableTLS, } err := s.SetCertificate(func(cert *tls.Certificate) { options.TLSConfig.Certificates = []tls.Certificate{*cert} @@ -440,7 +440,7 @@ func newV8Client(s *Settings) (RedisClient, error) { /* #nosec */ if s.EnableTLS { options.TLSConfig = &tls.Config{ - InsecureSkipVerify: s.EnableTLS, //nolint:gosec + InsecureSkipVerify: s.EnableTLS, } err := s.SetCertificate(func(cert *tls.Certificate) { options.TLSConfig.Certificates = []tls.Certificate{*cert} diff --git a/common/component/redis/v9client.go b/common/component/redis/v9client.go index 53c65b4c1a..f1e2d318b2 100644 --- a/common/component/redis/v9client.go +++ b/common/component/redis/v9client.go @@ -348,7 +348,7 @@ func newV9FailoverClient(s *Settings) (RedisClient, error) { /* #nosec */ if s.EnableTLS { opts.TLSConfig = &tls.Config{ - InsecureSkipVerify: s.EnableTLS, //nolint:gosec + InsecureSkipVerify: s.EnableTLS, } err := s.SetCertificate(func(cert *tls.Certificate) { opts.TLSConfig.Certificates = []tls.Certificate{*cert} @@ -404,7 +404,7 @@ func newV9Client(s *Settings) (RedisClient, error) { if s.EnableTLS { /* #nosec */ options.TLSConfig = &tls.Config{ - InsecureSkipVerify: s.EnableTLS, //nolint:gosec + InsecureSkipVerify: s.EnableTLS, } err := s.SetCertificate(func(cert *tls.Certificate) { options.TLSConfig.Certificates = []tls.Certificate{*cert} @@ -444,7 +444,7 @@ func newV9Client(s *Settings) (RedisClient, error) { if s.EnableTLS { /* #nosec */ options.TLSConfig = &tls.Config{ - InsecureSkipVerify: s.EnableTLS, //nolint:gosec + InsecureSkipVerify: s.EnableTLS, } err := s.SetCertificate(func(cert *tls.Certificate) { options.TLSConfig.Certificates = []tls.Certificate{*cert} diff --git a/common/component/sql/migrations/postgres/postgres_migrations.go b/common/component/sql/migrations/postgres/postgres_migrations.go index ac3626be91..e7a4ebae37 100644 --- a/common/component/sql/migrations/postgres/postgres_migrations.go +++ b/common/component/sql/migrations/postgres/postgres_migrations.go @@ -107,7 +107,7 @@ func (m Migrations) EnsureMetadataTable(ctx context.Context) (err error) { // Add an "IF NOT EXISTS" in case another Dapr sidecar is creating the same table at the same time // In the next step we'll acquire a lock so there won't be issues with concurrency // Note that this query can fail with error `23505` on constraint `pg_type_typname_nsp_index` if ran in parallel; we will just retry that up to 3 times - for i := 0; i < 3; i++ { + for range 3 { _, err = m.DB.Exec(ctx, fmt.Sprintf( `CREATE TABLE IF NOT EXISTS %s ( key text NOT NULL PRIMARY KEY, diff --git a/common/component/sql/migrations/sqlserver/sqlserver_migrations_test.go b/common/component/sql/migrations/sqlserver/sqlserver_migrations_test.go index 17de5001c9..074f18a608 100644 --- a/common/component/sql/migrations/sqlserver/sqlserver_migrations_test.go +++ b/common/component/sql/migrations/sqlserver/sqlserver_migrations_test.go @@ -158,7 +158,7 @@ func TestMigration(t *testing.T) { const parallel = 5 errs := make(chan error, parallel) hasLogs := atomic.Uint32{} - for i := 0; i < parallel; i++ { + for i := range parallel { go func(i int) { // Collect logs collectLog := logger.NewLogger("concurrent-" + strconv.Itoa(i)) @@ -188,7 +188,7 @@ func TestMigration(t *testing.T) { }(i) } - for i := 0; i < parallel; i++ { + for range parallel { select { case err := <-errs: assert.NoError(t, err) //nolint:testifylint @@ -213,7 +213,7 @@ func getUniqueDBSchema(t *testing.T) string { b := make([]byte, 4) _, err := io.ReadFull(rand.Reader, b) require.NoError(t, err) - return fmt.Sprintf("m%s", hex.EncodeToString(b)) + return "m%s" + hex.EncodeToString(b) } func assertTableExists(t *testing.T, db *sql.DB, schema, table string) { diff --git a/common/wasm/wasm.go b/common/wasm/wasm.go index f4da0d740f..de7f643073 100644 --- a/common/wasm/wasm.go +++ b/common/wasm/wasm.go @@ -141,6 +141,6 @@ func newFakeWalltime() sys.Walltime { t := time.Now().Unix() * int64(time.Second) return func() (sec int64, nsec int32) { wt := atomic.AddInt64(&t, int64(time.Millisecond)) - return wt / 1e9, int32(wt % 1e9) + return wt / 1e9, int32(wt % 1e9) //nolint:gosec } } diff --git a/configuration/azure/appconfig/appconfig.go b/configuration/azure/appconfig/appconfig.go index 0bc7e3a4c1..906a92a8a6 100644 --- a/configuration/azure/appconfig/appconfig.go +++ b/configuration/azure/appconfig/appconfig.go @@ -93,7 +93,7 @@ func (r *ConfigurationStore) Init(_ context.Context, md configuration.Metadata) ApplicationID: "dapr-" + logger.DaprVersion, }, Retry: policy.RetryOptions{ - MaxRetries: int32(r.metadata.MaxRetries), + MaxRetries: int32(r.metadata.MaxRetries), //nolint:gosec RetryDelay: r.metadata.MaxRetryDelay, MaxRetryDelay: r.metadata.MaxRetryDelay, }, @@ -231,7 +231,7 @@ func (r *ConfigurationStore) Subscribe(ctx context.Context, req *configuration.S sentinelKey := r.getSentinelKeyFromMetadata(req.Metadata) if sentinelKey == "" { - return "", fmt.Errorf("sentinel key is not provided in metadata") + return "", errors.New("sentinel key is not provided in metadata") } uuid, err := uuid.NewRandom() if err != nil { diff --git a/configuration/azure/appconfig/appconfig_test.go b/configuration/azure/appconfig/appconfig_test.go index 733d409f89..0ef05f418a 100644 --- a/configuration/azure/appconfig/appconfig_test.go +++ b/configuration/azure/appconfig/appconfig_test.go @@ -246,7 +246,7 @@ func TestInit(t *testing.T) { } func TestParseMetadata(t *testing.T) { - t.Run(fmt.Sprintf("parse metadata with %s", host), func(t *testing.T) { + t.Run("parse metadata with "+host, func(t *testing.T) { testProperties := make(map[string]string) testProperties[host] = "testHost" testProperties[maxRetries] = "3" @@ -279,7 +279,7 @@ func TestParseMetadata(t *testing.T) { assert.Equal(t, want.RequestTimeout, m.RequestTimeout) }) - t.Run(fmt.Sprintf("parse metadata with %s", connectionString), func(t *testing.T) { + t.Run("parse metadata with "+connectionString, func(t *testing.T) { testProperties := make(map[string]string) testProperties[connectionString] = "testConnectionString" testProperties[maxRetries] = "3" diff --git a/configuration/postgres/metadata.go b/configuration/postgres/metadata.go index e4d6492246..3ca391d3a8 100644 --- a/configuration/postgres/metadata.go +++ b/configuration/postgres/metadata.go @@ -14,6 +14,7 @@ limitations under the License. package postgres import ( + "errors" "fmt" "time" @@ -53,7 +54,7 @@ func (m *metadata) InitWithMetadata(meta map[string]string) error { // Validate and sanitize input if m.ConfigTable == "" { - return fmt.Errorf("missing postgreSQL configuration table name") + return errors.New("missing postgreSQL configuration table name") } if len(m.ConfigTable) > maxIdentifierLength { return fmt.Errorf("table name is too long - tableName : '%s'. max allowed field length is %d", m.ConfigTable, maxIdentifierLength) diff --git a/configuration/redis/redis.go b/configuration/redis/redis.go index c6c3e43697..0ca12a971f 100644 --- a/configuration/redis/redis.go +++ b/configuration/redis/redis.go @@ -102,7 +102,7 @@ func (r *ConfigurationStore) parseConnectedSlaves(res string) int { for _, info := range infos { if strings.Contains(info, connectedSlavesReplicas) { parsedReplicas, _ := strconv.ParseUint(info[len(connectedSlavesReplicas):], 10, 32) - return int(parsedReplicas) + return int(parsedReplicas) //nolint:gosec } } diff --git a/crypto/azure/keyvault/jwk.go b/crypto/azure/keyvault/jwk.go index 8c2185c7e3..eda8325b8a 100644 --- a/crypto/azure/keyvault/jwk.go +++ b/crypto/azure/keyvault/jwk.go @@ -92,7 +92,7 @@ func (key JSONWebKey) publicRSA() (*rsa.PublicKey, error) { if len(key.E) == 0 { return nil, errors.New("property e is empty") } - res.E = int(big.NewInt(0).SetBytes(key.E).Uint64()) + res.E = int(big.NewInt(0).SetBytes(key.E).Uint64()) //nolint:gosec return res, nil } diff --git a/crypto/pubkey_cache_test.go b/crypto/pubkey_cache_test.go index ed4ab134a7..dcbe7777ac 100644 --- a/crypto/pubkey_cache_test.go +++ b/crypto/pubkey_cache_test.go @@ -156,7 +156,7 @@ func TestPubKeyCacheGetKey(t *testing.T) { var wg sync.WaitGroup wg.Add(10) - for i := 0; i < 10; i++ { + for range 10 { go func() { defer wg.Done() result, err := cache.GetKey(context.Background(), "key") diff --git a/crypto/subtlecrypto.go b/crypto/subtlecrypto.go index 34c435e576..181e3cf6d2 100644 --- a/crypto/subtlecrypto.go +++ b/crypto/subtlecrypto.go @@ -23,6 +23,8 @@ import ( ) // SubtleCrypto offers an interface to perform low-level ("subtle") cryptographic operations with keys stored in a vault. +// +//nolint:interfacebloat type SubtleCrypto interface { metadata.ComponentWithMetadata diff --git a/lock/redis/standalone.go b/lock/redis/standalone.go index acb4d988dc..4ae6e29552 100644 --- a/lock/redis/standalone.go +++ b/lock/redis/standalone.go @@ -85,7 +85,7 @@ func (r *StandaloneRedisLock) TryLock(ctx context.Context, req *lock.TryLockRequ // Set a key if doesn't exist with an expiration time nxval, err := r.client.SetNX(ctx, req.ResourceID, req.LockOwner, time.Second*time.Duration(req.ExpiryInSeconds)) if nxval == nil { - return &lock.TryLockResponse{}, fmt.Errorf("setNX returned a nil response") + return &lock.TryLockResponse{}, errors.New("setNX returned a nil response") } if err != nil { diff --git a/metadata/utils.go b/metadata/utils.go index 7068dfd216..6c2ddd445d 100644 --- a/metadata/utils.go +++ b/metadata/utils.go @@ -86,6 +86,7 @@ func TryGetPriority(props map[string]string) (uint8, bool, error) { return 0, false, fmt.Errorf("%s value must be a valid integer: actual is '%s'", PriorityMetadataKey, val) } + //nolint:gosec priority := uint8(intVal) if intVal < 0 { priority = 0 @@ -220,7 +221,7 @@ func GetMetadataInfoFromStructType(t reflect.Type, metadataMap *MetadataMap, com *metadataMap = MetadataMap{} } - for i := 0; i < t.NumField(); i++ { + for i := range t.NumField() { currentField := t.Field(i) // fields that are not exported cannot be set via the mapstructure metadata decoding mechanism if !currentField.IsExported() { diff --git a/middleware/http/sentinel/middleware_test.go b/middleware/http/sentinel/middleware_test.go index c0b587e1fc..588d51c517 100644 --- a/middleware/http/sentinel/middleware_test.go +++ b/middleware/http/sentinel/middleware_test.go @@ -56,7 +56,7 @@ func TestRequestHandlerWithFlowRules(t *testing.T) { r := httptest.NewRequest(http.MethodGet, "http://localhost:5001/v1.0/nodeapp/healthz", nil) counter := &counter{} - for i := 0; i < 100; i++ { + for range 100 { w := httptest.NewRecorder() handler(http.HandlerFunc(counter.handle)).ServeHTTP(w, r) } @@ -126,7 +126,6 @@ func TestLoadRules(t *testing.T) { } for _, c := range cases { - c := c t.Run(c.name, func(t *testing.T) { sentinel, _ := NewMiddleware(nil).(*Middleware) err := sentinel.loadSentinelRules(&c.meta) diff --git a/middleware/http/wasm/benchmark_test.go b/middleware/http/wasm/benchmark_test.go index 24505eb0f7..42d884613e 100644 --- a/middleware/http/wasm/benchmark_test.go +++ b/middleware/http/wasm/benchmark_test.go @@ -91,11 +91,11 @@ var benches = map[string]struct { httputils.RespondWithErrorAndMessage(w, http.StatusInternalServerError, body) } if path := r.URL.Path; path != "/v1.0/hello" { - body := fmt.Sprintf("Expected wasm to rewrite path: %s", path) + body := "Expected wasm to rewrite path: " + path httputils.RespondWithErrorAndMessage(w, http.StatusInternalServerError, body) } if query := r.URL.RawQuery; query != "name=teddy" { - body := fmt.Sprintf("Expected wasm to retain query: %s", query) + body := "Expected wasm to retain query: " + query httputils.RespondWithErrorAndMessage(w, http.StatusInternalServerError, body) } w.Header().Set("Content-Type", "text/plain") diff --git a/middleware/http/wasm/internal/e2e_test.go b/middleware/http/wasm/internal/e2e_test.go index 21c91ce34f..bf31b5abe4 100644 --- a/middleware/http/wasm/internal/e2e_test.go +++ b/middleware/http/wasm/internal/e2e_test.go @@ -97,7 +97,7 @@ func Test_EndToEnd(t *testing.T) { guest: guestWasm[guestWasmOutput], test: func(t *testing.T, handler http.Handler, log *bytes.Buffer) { // Service more requests than one to ensure pooling works properly. - for i := 0; i < 3; i++ { + for range 3 { r := httptest.NewRequest(http.MethodGet, "/", nil) w := httptest.NewRecorder() handler.ServeHTTP(w, r) diff --git a/nameresolution/consul/configuration.go b/nameresolution/consul/configuration.go index 9fba047479..ccf4e58010 100644 --- a/nameresolution/consul/configuration.go +++ b/nameresolution/consul/configuration.go @@ -140,7 +140,7 @@ func mapChecks(config []*AgentServiceCheck) []*consul.AgentServiceCheck { mapped := []*consul.AgentServiceCheck{} - for i := 0; i < len(config); i++ { + for i := range config { mapped = append(mapped, mapCheck(config[i])) } @@ -211,7 +211,7 @@ func mapAdvancedRegistration(config *AgentServiceRegistration) *consul.AgentServ mapped.Checks = config.Checks - for i := 0; i < len(config.Paths); i++ { + for i := range len(config.Paths) { tmp := consul.ExposePath{ ListenerPort: config.Paths[i].ListenerPort, Path: config.Paths[i].Path, @@ -232,7 +232,7 @@ func mapAdvancedRegistration(config *AgentServiceRegistration) *consul.AgentServ mapped := []consul.Upstream{} - for i := 0; i < len(config); i++ { + for i := range config { tmp := consul.Upstream{ DestinationType: consul.UpstreamDestType(config[i].DestinationType), DestinationNamespace: config[i].DestinationNamespace, @@ -273,7 +273,7 @@ func mapAdvancedRegistration(config *AgentServiceRegistration) *consul.AgentServ mapped := consul.AgentServiceChecks{} - for i := 0; i < len(config); i++ { + for i := range config { mapped = append(mapped, mapCheck(config[i])) } diff --git a/nameresolution/consul/consul.go b/nameresolution/consul/consul.go index d07f9fdd80..8fc8eb2134 100644 --- a/nameresolution/consul/consul.go +++ b/nameresolution/consul/consul.go @@ -420,7 +420,7 @@ func getRegistrationConfig(cfg configSpec, props map[string]string) (*consul.Age cfg.Checks = []*consul.AgentServiceCheck{ { Name: "Dapr Health Status", - CheckID: fmt.Sprintf("daprHealth:%s", id), + CheckID: "daprHealth:" + id, Interval: "15s", HTTP: fmt.Sprintf("http://%s/v1.0/healthz?appid=%s", net.JoinHostPort(host, httpPort), appID), }, diff --git a/nameresolution/consul/consul_test.go b/nameresolution/consul/consul_test.go index 8dda8fc77c..2ab43f8c7b 100644 --- a/nameresolution/consul/consul_test.go +++ b/nameresolution/consul/consul_test.go @@ -15,6 +15,7 @@ package consul import ( "context" + "errors" "fmt" "net" "strconv" @@ -246,7 +247,6 @@ func TestInit(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.testName, func(t *testing.T) { tt.test(t, tt.metadata) }) @@ -589,7 +589,7 @@ func TestResolveID(t *testing.T) { LastIndex: 0, } - err := fmt.Errorf("oh no") + err := errors.New("oh no") serviceEntries := []*consul.ServiceEntry{ { @@ -909,7 +909,7 @@ func TestResolveID(t *testing.T) { total1 := 0 total2 := 0 - for i := 0; i < 100; i++ { + for range 100 { addr, _ := resolver.ResolveID(context.Background(), req) if addr == "10.3.245.137:50005" { @@ -1026,7 +1026,6 @@ func TestResolveID(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.testName, func(t *testing.T) { tt.test(t, tt.req) }) @@ -1111,7 +1110,6 @@ func TestClose(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.testName, func(t *testing.T) { t.Parallel() tt.test(t, tt.metadata) @@ -1265,7 +1263,6 @@ func TestRegistry(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.testName, func(t *testing.T) { t.Parallel() tt.test(t) @@ -1356,7 +1353,6 @@ func TestParseConfig(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.testName, func(t *testing.T) { actual, err := parseConfig(tt.input) @@ -1727,7 +1723,6 @@ func TestGetConfig(t *testing.T) { } for _, tt := range tests { - tt := tt t.Run(tt.testName, func(t *testing.T) { tt.test(t, tt.metadata) }) @@ -2015,7 +2010,7 @@ func TestMapConfig(t *testing.T) { compareRegistration(t, expected.AdvancedRegistration, actual.AdvancedRegistration) compareClientConfig(t, expected.Client, actual.Client) - for i := 0; i < len(expected.Checks); i++ { + for i := range len(expected.Checks) { compareCheck(t, expected.Checks[i], actual.Checks[i]) } @@ -2102,7 +2097,7 @@ func compareRegistration(t *testing.T, expected *AgentServiceRegistration, actua compareCheck(t, expected.Check, actual.Check) - for i := 0; i < len(expected.Checks); i++ { + for i := range len(expected.Checks) { compareCheck(t, expected.Checks[i], actual.Checks[i]) } @@ -2113,7 +2108,7 @@ func compareRegistration(t *testing.T, expected *AgentServiceRegistration, actua assert.Equal(t, expected.Proxy.LocalServicePort, actual.Proxy.LocalServicePort) assert.Equal(t, expected.Proxy.Config, actual.Proxy.Config) - for i := 0; i < len(expected.Proxy.Upstreams); i++ { + for i := range len(expected.Proxy.Upstreams) { assert.Equal(t, string(expected.Proxy.Upstreams[i].DestinationType), string(actual.Proxy.Upstreams[i].DestinationType)) assert.Equal(t, expected.Proxy.Upstreams[i].DestinationNamespace, actual.Proxy.Upstreams[i].DestinationNamespace) assert.Equal(t, expected.Proxy.Upstreams[i].DestinationName, actual.Proxy.Upstreams[i].DestinationName) @@ -2128,7 +2123,7 @@ func compareRegistration(t *testing.T, expected *AgentServiceRegistration, actua assert.Equal(t, expected.Proxy.Expose.Checks, actual.Proxy.Expose.Checks) - for i := 0; i < len(expected.Proxy.Expose.Paths); i++ { + for i := range len(expected.Proxy.Expose.Paths) { assert.Equal(t, expected.Proxy.Expose.Paths[i].ListenerPort, actual.Proxy.Expose.Paths[i].ListenerPort) assert.Equal(t, expected.Proxy.Expose.Paths[i].LocalPathPort, actual.Proxy.Expose.Paths[i].LocalPathPort) assert.Equal(t, expected.Proxy.Expose.Paths[i].ParsedFromCheck, actual.Proxy.Expose.Paths[i].ParsedFromCheck) @@ -2192,7 +2187,7 @@ func getInstanceInfoWithoutKey(removeKey string) nr.Instance { } func waitTillTrueOrTimeout(d time.Duration, condition func() bool) { - for i := 0; i < 100; i++ { + for range 100 { if condition() { return } diff --git a/nameresolution/consul/watcher.go b/nameresolution/consul/watcher.go index ece97ab05d..bf7a38c7f2 100644 --- a/nameresolution/consul/watcher.go +++ b/nameresolution/consul/watcher.go @@ -298,7 +298,7 @@ watchLoop: // generate set of keys serviceKeys := make(map[string]any) - for i := 0; i < len(services); i++ { + for i := range services { serviceKeys[services[i]] = nil } diff --git a/nameresolution/mdns/mdns.go b/nameresolution/mdns/mdns.go index 228d680f91..b9e699e20b 100644 --- a/nameresolution/mdns/mdns.go +++ b/nameresolution/mdns/mdns.go @@ -113,6 +113,7 @@ func (a *addressList) next() *string { a.mu.RLock() defer a.mu.RUnlock() + //nolint:gosec l := uint32(len(a.addresses)) if l == 0 { return nil @@ -299,14 +300,14 @@ func (m *Resolver) getZeroconfResolver() (resolver *zeroconf.Resolver, err error zeroconf.SelectIPTraffic(zeroconf.IPv4), zeroconf.SelectIPTraffic(zeroconf.IPv6), } - for i := 0; i < len(opts); i++ { + for i := range opts { resolver, err = zeroconf.NewResolver(opts[i]) if err == nil { break } } if err != nil { - return nil, fmt.Errorf("failed to initialize resolver after attempting IPv4+IPv6, IPv4-only, and IPv6-only") + return nil, errors.New("failed to initialize resolver after attempting IPv4+IPv6, IPv4-only, and IPv6-only") } return resolver, nil } diff --git a/nameresolution/mdns/mdns_test.go b/nameresolution/mdns/mdns_test.go index bbd50ee921..6417b96ac0 100644 --- a/nameresolution/mdns/mdns_test.go +++ b/nameresolution/mdns/mdns_test.go @@ -142,7 +142,7 @@ func TestResolver(t *testing.T) { // assert require.NoError(t, err) - assert.Equal(t, fmt.Sprintf("%s:1234", localhost), pt) + assert.Equal(t, localhost+":1234", pt) } func TestResolverClose(t *testing.T) { @@ -163,7 +163,7 @@ func TestResolverClose(t *testing.T) { // assert require.NoError(t, err) - assert.Equal(t, fmt.Sprintf("%s:1234", localhost), pt) + assert.Equal(t, localhost+":1234", pt) // act again err = resolver.Close() @@ -217,7 +217,7 @@ func TestResolverMultipleInstances(t *testing.T) { // instance A and instance B and we see them each atleast m times. instanceACount := atomic.Uint32{} instanceBCount := atomic.Uint32{} - for i := 0; i < 100; i++ { + for range 100 { addr, err := resolver.ResolveID(context.Background(), request) require.NoError(t, err) require.Contains(t, []string{instanceAPQDN, instanceBPQDN}, addr) @@ -294,14 +294,14 @@ func ResolverConcurrencySubsriberClear(t *testing.T) { request := nr.ResolveRequest{ID: "testAppID"} var wg sync.WaitGroup - for i := 0; i < 10; i++ { + for range 10 { wg.Add(1) go func() { defer wg.Done() pt, err := resolver.ResolveID(context.Background(), request) require.NoError(t, err) - require.Equal(t, fmt.Sprintf("%s:1234", localhost), pt) + require.Equal(t, localhost+":1234", pt) }() } @@ -354,7 +354,7 @@ func ResolverConcurrencyFound(t *testing.T) { // act... wg := sync.WaitGroup{} - for i := 0; i < numConcurrency; i++ { + for i := range numConcurrency { wg.Add(1) go func(i int) { defer wg.Done() @@ -401,7 +401,7 @@ func ResolverConcurrencyNotFound(t *testing.T) { // act... wg := sync.WaitGroup{} - for i := 0; i < numConcurrency; i++ { + for i := range numConcurrency { idx := i wg.Add(1) go func() { @@ -509,7 +509,7 @@ func TestAddressListAddExisitingAddress(t *testing.T) { // assert require.Len(t, addressList.addresses, 2) - require.Greater(t, deltaSec, 0) // Ensures expiry has been extended for existing address. + require.Positive(t, deltaSec, 0) // Ensures expiry has been extended for existing address. } func TestAddressListNext(t *testing.T) { diff --git a/nameresolution/sqlite/sqlite_test.go b/nameresolution/sqlite/sqlite_test.go index fce242e578..58c42ba792 100644 --- a/nameresolution/sqlite/sqlite_test.go +++ b/nameresolution/sqlite/sqlite_test.go @@ -102,7 +102,7 @@ func TestSqliteNameResolver(t *testing.T) { require.Equal(t, tc.expectOne, res) } } else { - for i := 0; i < 20; i++ { + for i := range 20 { res, err := nr.ResolveID(context.Background(), nameresolution.ResolveRequest{ID: tc.appID}) require.NoErrorf(t, err, "Error on iteration %d", i) require.Contains(t, tc.expectAny, res) diff --git a/pubsub/aws/snssqs/metadata.go b/pubsub/aws/snssqs/metadata.go index 113cf126b2..db45fb8d84 100644 --- a/pubsub/aws/snssqs/metadata.go +++ b/pubsub/aws/snssqs/metadata.go @@ -61,7 +61,7 @@ type snsSqsMetadata struct { func maskLeft(s string) string { rs := []rune(s) - for i := 0; i < len(rs)-4; i++ { + for i := range len(rs) - 4 { rs[i] = 'X' } return string(rs) diff --git a/pubsub/aws/snssqs/snssqs.go b/pubsub/aws/snssqs/snssqs.go index 501a7344aa..357cfcabb9 100644 --- a/pubsub/aws/snssqs/snssqs.go +++ b/pubsub/aws/snssqs/snssqs.go @@ -414,7 +414,7 @@ func (s *snsSqs) getSnsSqsSubscriptionArn(parentCtx context.Context, topicArn st } } - return "", fmt.Errorf("sns sqs subscription not found for topic arn") + return "", errors.New("sns sqs subscription not found for topic arn") } func (s *snsSqs) getOrCreateSnsSqsSubscription(ctx context.Context, queueArn, topicArn string) (subscriptionArn string, err error) { @@ -552,7 +552,7 @@ func (s *snsSqs) callHandler(ctx context.Context, message *sqs.Message, queueInf ) if handler, loadOK = s.subscriptionManager.GetSubscriptionTopicHandler(sanitizedTopic); loadOK { if len(handler.requestTopic) == 0 { - return fmt.Errorf("handler topic name is missing") + return errors.New("handler topic name is missing") } } else { return fmt.Errorf("handler for (sanitized) topic: %s was not found", sanitizedTopic) diff --git a/pubsub/aws/snssqs/snssqs_test.go b/pubsub/aws/snssqs/snssqs_test.go index 2a6ca77a0d..1c789b67be 100644 --- a/pubsub/aws/snssqs/snssqs_test.go +++ b/pubsub/aws/snssqs/snssqs_test.go @@ -335,7 +335,7 @@ func Test_replaceNameToAWSSanitizedExistingFifoName_NonMax(t *testing.T) { s := `0123456789` v := nameToAWSSanitizedName(s, true) - r.EqualValues(len(s)+len(".fifo"), len(v)) + r.Len(v, len(s)+len(".fifo")) r.Equal("0123456789.fifo", v) } diff --git a/pubsub/azure/servicebus/topics/servicebus.go b/pubsub/azure/servicebus/topics/servicebus.go index 0bf59f8fa3..2ba8358051 100644 --- a/pubsub/azure/servicebus/topics/servicebus.go +++ b/pubsub/azure/servicebus/topics/servicebus.go @@ -256,7 +256,7 @@ func (a *azureServiceBus) connectAndReceive(ctx context.Context, req pubsub.Subs func (a *azureServiceBus) connectAndReceiveWithSessions(ctx context.Context, req pubsub.SubscribeRequest, sub *impl.Subscription, handlerFn impl.HandlerFn, onFirstSuccess func(), maxConcurrentSessions int) { sessionsChan := make(chan struct{}, maxConcurrentSessions) - for i := 0; i < maxConcurrentSessions; i++ { + for range maxConcurrentSessions { sessionsChan <- struct{}{} } diff --git a/pubsub/envelope_test.go b/pubsub/envelope_test.go index 0904b24422..c00b268b78 100644 --- a/pubsub/envelope_test.go +++ b/pubsub/envelope_test.go @@ -213,7 +213,7 @@ func TestCreateCloudEventsEnvelopeExpiration(t *testing.T) { ApplyMetadata(envelope, []Feature{FeatureMessageTTL}, map[string]string{ "ttlInSeconds": "10000", }) - assert.Equal(t, nil, envelope[ExpirationField]) + assert.Nil(t, envelope[ExpirationField]) assert.False(t, HasExpired(envelope)) }) @@ -376,7 +376,7 @@ func TestCreateFromCloudEventsProtobufPayload(t *testing.T) { contenttypes := []string{contribContenttype.CloudEventProtobufContentType, contribContenttype.ProtobufContentType} - for i := 0; i < len(contenttypes); i++ { + for i := range contenttypes { envelope := NewCloudEventsEnvelope("", "", "", "", "", "", contenttypes[i], ceProtoBytes, "trace", "") diff --git a/pubsub/gcp/pubsub/pubsub.go b/pubsub/gcp/pubsub/pubsub.go index 22088f5ddc..d7e63627ec 100644 --- a/pubsub/gcp/pubsub/pubsub.go +++ b/pubsub/gcp/pubsub/pubsub.go @@ -320,7 +320,7 @@ func BuildSubscriptionID(consumerID, topic string) string { func (g *GCPPubSub) handleSubscriptionMessages(parentCtx context.Context, topic *gcppubsub.Topic, sub *gcppubsub.Subscription, handler pubsub.Handler) error { // Limit the number of attempted reconnects we make. reconnAttempts := make(chan struct{}, g.metadata.MaxReconnectionAttempts) - for i := 0; i < g.metadata.MaxReconnectionAttempts; i++ { + for range g.metadata.MaxReconnectionAttempts { reconnAttempts <- struct{}{} } diff --git a/pubsub/in-memory/in-memory.go b/pubsub/in-memory/in-memory.go index 8076f7b894..bbd4db6244 100644 --- a/pubsub/in-memory/in-memory.go +++ b/pubsub/in-memory/in-memory.go @@ -76,7 +76,7 @@ func (a *bus) Subscribe(ctx context.Context, req pubsub.SubscribeRequest, handle // For this component we allow built-in retries because it is backed by memory retryHandler := func(data []byte) { - for i := 0; i < 10; i++ { + for range 10 { handleErr := handler(ctx, &pubsub.NewMessage{Data: data, Topic: req.Topic, Metadata: req.Metadata}) if handleErr == nil { break diff --git a/pubsub/jetstream/metadata.go b/pubsub/jetstream/metadata.go index 4c91d7f8ec..8969dfdde5 100644 --- a/pubsub/jetstream/metadata.go +++ b/pubsub/jetstream/metadata.go @@ -14,6 +14,7 @@ limitations under the License. package jetstream import ( + "errors" "fmt" "time" @@ -70,23 +71,23 @@ func parseMetadata(psm pubsub.Metadata) (metadata, error) { } if m.NatsURL == "" { - return metadata{}, fmt.Errorf("missing nats URL") + return metadata{}, errors.New("missing nats URL") } if m.Jwt != "" && m.SeedKey == "" { - return metadata{}, fmt.Errorf("missing seed key") + return metadata{}, errors.New("missing seed key") } if m.Jwt == "" && m.SeedKey != "" { - return metadata{}, fmt.Errorf("missing jwt") + return metadata{}, errors.New("missing jwt") } if m.TLSClientCert != "" && m.TLSClientKey == "" { - return metadata{}, fmt.Errorf("missing tls client key") + return metadata{}, errors.New("missing tls client key") } if m.TLSClientCert == "" && m.TLSClientKey != "" { - return metadata{}, fmt.Errorf("missing tls client cert") + return metadata{}, errors.New("missing tls client cert") } if m.Name == "" { @@ -94,7 +95,7 @@ func parseMetadata(psm pubsub.Metadata) (metadata, error) { } if m.StartTime != nil { - m.internalStartTime = time.Unix(int64(*m.StartTime), 0) + m.internalStartTime = time.Unix(int64(*m.StartTime), 0) //nolint:gosec } switch m.DeliverPolicy { diff --git a/pubsub/kafka/metadata.yaml b/pubsub/kafka/metadata.yaml index 8d3638e837..b6536c2b43 100644 --- a/pubsub/kafka/metadata.yaml +++ b/pubsub/kafka/metadata.yaml @@ -322,4 +322,12 @@ metadata: description: | The TTL for schema caching when publishing a message with latest schema available. example: '"5m"' - default: '"5m"' \ No newline at end of file + default: '"5m"' + - name: escapeHeaders + type: bool + required: false + description: | + Enables URL escaping of the message header values. + It allows sending headers with special characters that are usually not allowed in HTTP headers. + example: "true" + default: "false" diff --git a/pubsub/kubemq/kubemq_events.go b/pubsub/kubemq/kubemq_events.go index 730ef00a09..0661480538 100644 --- a/pubsub/kubemq/kubemq_events.go +++ b/pubsub/kubemq/kubemq_events.go @@ -3,6 +3,7 @@ package kubemq import ( "context" "encoding/json" + "errors" "fmt" "sync" "time" @@ -104,7 +105,7 @@ func (k *kubeMQEvents) Publish(req *pubsub.PublishRequest) error { return err } if req.Topic == "" { - return fmt.Errorf("kubemq pub/sub error: topic is required") + return errors.New("kubemq pub/sub error: topic is required") } metadata := "" if req.Metadata != nil { diff --git a/pubsub/kubemq/kubemq_events_test.go b/pubsub/kubemq/kubemq_events_test.go index 57cdc79db3..92f46b7cce 100644 --- a/pubsub/kubemq/kubemq_events_test.go +++ b/pubsub/kubemq/kubemq_events_test.go @@ -2,7 +2,7 @@ package kubemq import ( "context" - "fmt" + "errors" "testing" "time" @@ -111,7 +111,7 @@ func Test_kubeMQEvents_Publish(t *testing.T) { Topic: "some-topic", }, resultError: nil, - publishErr: fmt.Errorf("some error"), + publishErr: errors.New("some error"), wantErr: true, }, } @@ -175,7 +175,7 @@ func Test_kubeMQEvents_Subscribe(t *testing.T) { subscribeHandler: func(ctx context.Context, msg *pubsub.NewMessage) error { return nil }, - subscribeError: fmt.Errorf("some error"), + subscribeError: errors.New("some error"), wantErr: true, }, } diff --git a/pubsub/kubemq/kubemq_eventstore.go b/pubsub/kubemq/kubemq_eventstore.go index de004129dd..12776d4295 100644 --- a/pubsub/kubemq/kubemq_eventstore.go +++ b/pubsub/kubemq/kubemq_eventstore.go @@ -3,6 +3,7 @@ package kubemq import ( "context" "encoding/json" + "errors" "fmt" "sync" "time" @@ -108,7 +109,7 @@ func (k *kubeMQEventStore) Publish(req *pubsub.PublishRequest) error { return err } if req.Topic == "" { - return fmt.Errorf("kubemq pub/sub error: topic is required") + return errors.New("kubemq pub/sub error: topic is required") } k.logger.Debugf("kubemq pub/sub: publishing message to %s", req.Topic) metadata := "" @@ -143,7 +144,7 @@ func (k *kubeMQEventStore) Publish(req *pubsub.PublishRequest) error { return res.Err } case <-time.After(k.waitForResultTimeout): - return fmt.Errorf("kubemq pub/sub error: timeout waiting for response") + return errors.New("kubemq pub/sub error: timeout waiting for response") } return nil } diff --git a/pubsub/kubemq/kubemq_eventstore_test.go b/pubsub/kubemq/kubemq_eventstore_test.go index e4d3bd1bca..6d79081eb5 100644 --- a/pubsub/kubemq/kubemq_eventstore_test.go +++ b/pubsub/kubemq/kubemq_eventstore_test.go @@ -2,7 +2,7 @@ package kubemq import ( "context" - "fmt" + "errors" "testing" "time" @@ -114,7 +114,7 @@ func Test_kubeMQEventsStore_Publish(t *testing.T) { Data: []byte("data"), Topic: "some-topic", }, - resultError: fmt.Errorf("some error"), + resultError: errors.New("some error"), wantErr: true, }, { @@ -134,7 +134,7 @@ func Test_kubeMQEventsStore_Publish(t *testing.T) { Topic: "some-topic", }, resultError: nil, - publishErr: fmt.Errorf("some error"), + publishErr: errors.New("some error"), wantErr: true, }, } @@ -198,7 +198,7 @@ func Test_kubeMQkubeMQEventsStore_Subscribe(t *testing.T) { subscribeHandler: func(ctx context.Context, msg *pubsub.NewMessage) error { return nil }, - subscribeError: fmt.Errorf("some error"), + subscribeError: errors.New("some error"), wantErr: true, }, } diff --git a/pubsub/kubemq/metadata.go b/pubsub/kubemq/metadata.go index 19f3f3bae8..3964f6c40c 100644 --- a/pubsub/kubemq/metadata.go +++ b/pubsub/kubemq/metadata.go @@ -1,7 +1,7 @@ package kubemq import ( - "fmt" + "errors" "strconv" "strings" @@ -26,15 +26,15 @@ func parseAddress(address string) (string, int, error) { var err error hostPort := strings.Split(address, ":") if len(hostPort) != 2 { - return "", 0, fmt.Errorf("invalid kubeMQ address, address format is invalid") + return "", 0, errors.New("invalid kubeMQ address, address format is invalid") } host = hostPort[0] if len(host) == 0 { - return "", 0, fmt.Errorf("invalid kubeMQ address, host is empty") + return "", 0, errors.New("invalid kubeMQ address, host is empty") } port, err = strconv.Atoi(hostPort[1]) if err != nil { - return "", 0, fmt.Errorf("invalid kubeMQ address, port is invalid") + return "", 0, errors.New("invalid kubeMQ address, port is invalid") } return host, port, nil } @@ -56,7 +56,7 @@ func createMetadata(pubSubMetadata pubsub.Metadata) (*kubemqMetadata, error) { return nil, err } } else { - return nil, fmt.Errorf("invalid kubeMQ address, address is empty") + return nil, errors.New("invalid kubeMQ address, address is empty") } return result, nil } diff --git a/pubsub/mqtt3/mqtt.go b/pubsub/mqtt3/mqtt.go index f36a7ceb37..75442b2714 100644 --- a/pubsub/mqtt3/mqtt.go +++ b/pubsub/mqtt3/mqtt.go @@ -459,7 +459,7 @@ func buildRegexForTopic(topicName string) string { if strings.ContainsAny(topicName, "#+") { regexStr = "^" // It's ok to iterate over bytes here (rather than codepoints) because all characters we're looking for are always single-byte - for i := 0; i < len(topicName); i++ { + for i := range len(topicName) { // Wildcard chars must either be at the beginning of the string or must follow a / okPos = (i == 0 || topicName[i-1] == '/') if topicName[i] == '#' && okPos { diff --git a/pubsub/pubsub.go b/pubsub/pubsub.go index 36e1541ff0..f61261108e 100644 --- a/pubsub/pubsub.go +++ b/pubsub/pubsub.go @@ -15,7 +15,7 @@ package pubsub import ( "context" - "fmt" + "errors" "io" "github.com/dapr/components-contrib/health" @@ -73,6 +73,6 @@ func Ping(ctx context.Context, pubsub PubSub) error { if pubsubWithPing, ok := pubsub.(health.Pinger); ok { return pubsubWithPing.Ping(ctx) } else { - return fmt.Errorf("ping is not implemented by this pubsub") + return errors.New("ping is not implemented by this pubsub") } } diff --git a/pubsub/pulsar/pulsar.go b/pubsub/pulsar/pulsar.go index 7a77cea601..6e4fb94d87 100644 --- a/pubsub/pulsar/pulsar.go +++ b/pubsub/pulsar/pulsar.go @@ -212,7 +212,7 @@ func (p *Pulsar) Init(ctx context.Context, metadata pubsub.Metadata) error { } }) if err != nil { - return fmt.Errorf("could not initialize pulsar lru cache for publisher") + return errors.New("could not initialize pulsar lru cache for publisher") } p.cache = c defer p.cache.Purge() @@ -318,7 +318,6 @@ func parsePublishMetadata(req *pubsub.PublishRequest, schema schemaMetadata) ( case jsonProtocol: var obj interface{} err = json.Unmarshal(req.Data, &obj) - if err != nil { return nil, err } @@ -332,7 +331,6 @@ func parsePublishMetadata(req *pubsub.PublishRequest, schema schemaMetadata) ( } err = avro.Unmarshal(avroSchema, req.Data, &obj) - if err != nil { return nil, err } diff --git a/pubsub/rabbitmq/metadata_test.go b/pubsub/rabbitmq/metadata_test.go index 435babeff4..6ebebe08a8 100644 --- a/pubsub/rabbitmq/metadata_test.go +++ b/pubsub/rabbitmq/metadata_test.go @@ -104,7 +104,7 @@ func TestCreateMetadata(t *testing.T) { invalidDeliveryModes := []string{"3", "10", "-1"} for _, deliveryMode := range invalidDeliveryModes { - t.Run(fmt.Sprintf("deliveryMode value=%s", deliveryMode), func(t *testing.T) { + t.Run("deliveryMode value="+deliveryMode, func(t *testing.T) { fakeProperties := getFakeProperties() fakeMetaData := pubsub.Metadata{ @@ -317,7 +317,7 @@ func TestCreateMetadata(t *testing.T) { }) for _, tt := range booleanFlagTests { - t.Run(fmt.Sprintf("autoAck value=%s", tt.in), func(t *testing.T) { + t.Run("autoAck value="+tt.in, func(t *testing.T) { fakeProperties := getFakeProperties() fakeMetaData := pubsub.Metadata{ @@ -337,7 +337,7 @@ func TestCreateMetadata(t *testing.T) { } for _, tt := range booleanFlagTests { - t.Run(fmt.Sprintf("requeueInFailure value=%s", tt.in), func(t *testing.T) { + t.Run("requeueInFailure value="+tt.in, func(t *testing.T) { fakeProperties := getFakeProperties() fakeMetaData := pubsub.Metadata{ @@ -357,7 +357,7 @@ func TestCreateMetadata(t *testing.T) { } for _, tt := range booleanFlagTests { - t.Run(fmt.Sprintf("deleteWhenUnused value=%s", tt.in), func(t *testing.T) { + t.Run("deleteWhenUnused value="+tt.in, func(t *testing.T) { fakeProperties := getFakeProperties() fakeMetaData := pubsub.Metadata{ @@ -377,7 +377,7 @@ func TestCreateMetadata(t *testing.T) { } for _, tt := range booleanFlagTests { - t.Run(fmt.Sprintf("durable value=%s", tt.in), func(t *testing.T) { + t.Run("durable value="+tt.in, func(t *testing.T) { fakeProperties := getFakeProperties() fakeMetaData := pubsub.Metadata{ @@ -397,7 +397,7 @@ func TestCreateMetadata(t *testing.T) { } for _, tt := range booleanFlagTests { - t.Run(fmt.Sprintf("publisherConfirm value=%s", tt.in), func(t *testing.T) { + t.Run("publisherConfirm value="+tt.in, func(t *testing.T) { fakeProperties := getFakeProperties() fakeMetaData := pubsub.Metadata{ @@ -417,7 +417,7 @@ func TestCreateMetadata(t *testing.T) { } for _, tt := range booleanFlagTests { - t.Run(fmt.Sprintf("enableDeadLetter value=%s", tt.in), func(t *testing.T) { + t.Run("enableDeadLetter value="+tt.in, func(t *testing.T) { fakeProperties := getFakeProperties() fakeMetaData := pubsub.Metadata{ @@ -438,7 +438,7 @@ func TestCreateMetadata(t *testing.T) { validExchangeKind := []string{amqp.ExchangeDirect, amqp.ExchangeTopic, amqp.ExchangeFanout, amqp.ExchangeHeaders} for _, exchangeKind := range validExchangeKind { - t.Run(fmt.Sprintf("exchangeKind value=%s", exchangeKind), func(t *testing.T) { + t.Run("exchangeKind value="+exchangeKind, func(t *testing.T) { fakeProperties := getFakeProperties() fakeMetaData := pubsub.Metadata{ diff --git a/pubsub/rabbitmq/rabbitmq.go b/pubsub/rabbitmq/rabbitmq.go index 4724fcec67..b696082ed5 100644 --- a/pubsub/rabbitmq/rabbitmq.go +++ b/pubsub/rabbitmq/rabbitmq.go @@ -134,7 +134,6 @@ func dial(protocol, uri, clientName string, heartBeat time.Duration, tlsCfg *tls } } conn, err = amqp.DialConfig(uri, cfg) - if err != nil { return nil, nil, err } @@ -272,7 +271,7 @@ func (r *rabbitMQ) publishSync(ctx context.Context, req *pubsub.PublishRequest) // Blocks until the server confirms ok := confirm.Wait() if !ok { - err = fmt.Errorf("did not receive confirmation of publishing") + err = errors.New("did not receive confirmation of publishing") r.logger.Errorf("%s publishing to %s failed: %v", logMessagePrefix, req.Topic, err) } } @@ -482,7 +481,7 @@ func (r *rabbitMQ) prepareSubscription(channel rabbitMQChannelBroker, req pubsub metadataRoutingKey = val } routingKeys := strings.Split(metadataRoutingKey, ",") - for i := 0; i < len(routingKeys); i++ { + for i := range routingKeys { routingKey := routingKeys[i] r.logger.Debugf("%s binding queue '%s' to exchange '%s' with routing key '%s'", logMessagePrefix, q.Name, req.Topic, routingKey) err = channel.QueueBind(q.Name, routingKey, req.Topic, false, nil) @@ -521,7 +520,6 @@ func (r *rabbitMQ) subscribeForever(ctx context.Context, req pubsub.SubscribeReq ) for { channel, connectionCount, q, err = r.ensureSubscription(req, queueName) - if err != nil { errFuncName = "ensureSubscription" break diff --git a/pubsub/redis/redis.go b/pubsub/redis/redis.go index 310eaddad1..7df54777f8 100644 --- a/pubsub/redis/redis.go +++ b/pubsub/redis/redis.go @@ -84,9 +84,9 @@ func (r *redisStreams) Init(ctx context.Context, metadata pubsub.Metadata) error if _, err = r.client.PingResult(ctx); err != nil { return fmt.Errorf("redis streams: error connecting to redis at %s: %s", r.clientSettings.Host, err) } - r.queue = make(chan redisMessageWrapper, int(r.clientSettings.QueueDepth)) + r.queue = make(chan redisMessageWrapper, int(r.clientSettings.QueueDepth)) //nolint:gosec - for i := uint(0); i < r.clientSettings.Concurrency; i++ { + for range r.clientSettings.Concurrency { r.wg.Add(1) go func() { defer r.wg.Done() @@ -268,6 +268,7 @@ func (r *redisStreams) pollNewMessagesLoop(ctx context.Context, stream string, h } // Read messages + //nolint:gosec streams, err := r.client.XReadGroupResult(ctx, r.clientSettings.ConsumerID, r.clientSettings.ConsumerID, []string{stream, ">"}, int64(r.clientSettings.QueueDepth), time.Duration(r.clientSettings.ReadTimeout)) if err != nil { if !errors.Is(err, r.client.GetNilValueError()) && err != context.Canceled { @@ -323,7 +324,7 @@ func (r *redisStreams) reclaimPendingMessages(ctx context.Context, stream string r.clientSettings.ConsumerID, "-", "+", - int64(r.clientSettings.QueueDepth), + int64(r.clientSettings.QueueDepth), //nolint:gosec ) if err != nil && !errors.Is(err, r.client.GetNilValueError()) { r.logger.Errorf("error retrieving pending Redis messages: %v", err) diff --git a/pubsub/rocketmq/rocketmq.go b/pubsub/rocketmq/rocketmq.go index f02f51abe5..f235910365 100644 --- a/pubsub/rocketmq/rocketmq.go +++ b/pubsub/rocketmq/rocketmq.go @@ -219,7 +219,7 @@ func (r *rocketMQ) setUpConsumer() (mq.PushConsumer, error) { if r.metadata.PullBatchSize > 0 { opts = append(opts, mqc.WithPullBatchSize(r.metadata.PullBatchSize)) } else if r.metadata.ConsumerBatchSize > 0 { - r.metadata.PullBatchSize = int32(r.metadata.ConsumerBatchSize) + r.metadata.PullBatchSize = int32(r.metadata.ConsumerBatchSize) //nolint:gosec opts = append(opts, mqc.WithPullBatchSize(r.metadata.PullBatchSize)) r.logger.Warn("set the number of msg pulled from the broker at a time, " + "please use pullBatchSize instead of consumerBatchSize") diff --git a/pubsub/solace/amqp/amqp.go b/pubsub/solace/amqp/amqp.go index 11a95e1977..16c3ad58c0 100644 --- a/pubsub/solace/amqp/amqp.go +++ b/pubsub/solace/amqp/amqp.go @@ -130,7 +130,6 @@ func (a *amqpPubSub) Publish(ctx context.Context, req *pubsub.PublishRequest) er a.logger.Errorf("Unable to create link to %s", req.Topic, err) } else { err = sender.Send(ctx, m, nil) - // If the publish operation has failed, attempt to republish a maximum number of times // before giving up if err != nil { @@ -139,7 +138,6 @@ func (a *amqpPubSub) Publish(ctx context.Context, req *pubsub.PublishRequest) er // Send message err = sender.Send(ctx, m, nil) - if err != nil { a.logger.Warnf("Failed to publish a message to the broker", err) } diff --git a/pubsub/tls.go b/pubsub/tls.go index fa031696ee..cab7977aee 100644 --- a/pubsub/tls.go +++ b/pubsub/tls.go @@ -65,7 +65,7 @@ func ConvertTLSPropertiesToTLSConfig(properties TLSProperties) (*tls.Config, err if properties.CACert != "" { tlsConfig.RootCAs = x509.NewCertPool() if ok := tlsConfig.RootCAs.AppendCertsFromPEM([]byte(properties.CACert)); !ok { - return tlsConfig, fmt.Errorf("unable to load CA certificate") + return tlsConfig, errors.New("unable to load CA certificate") } } diff --git a/secretstores/alicloud/parameterstore/parameterstore_test.go b/secretstores/alicloud/parameterstore/parameterstore_test.go index 530dc5965c..5760121c49 100644 --- a/secretstores/alicloud/parameterstore/parameterstore_test.go +++ b/secretstores/alicloud/parameterstore/parameterstore_test.go @@ -15,7 +15,7 @@ package parameterstore import ( "context" - "fmt" + "errors" "testing" oos "github.com/alibabacloud-go/oos-20190601/client" @@ -62,11 +62,11 @@ func (m *mockedParameterStore) GetSecretParametersByPathWithOptions(request *oos type mockedParameterStoreReturnError struct{} func (m *mockedParameterStoreReturnError) GetSecretParameterWithOptions(request *oos.GetSecretParameterRequest, runtime *util.RuntimeOptions) (*oos.GetSecretParameterResponse, error) { - return nil, fmt.Errorf("mocked error") + return nil, errors.New("mocked error") } func (m *mockedParameterStoreReturnError) GetSecretParametersByPathWithOptions(request *oos.GetSecretParametersByPathRequest, runtime *util.RuntimeOptions) (*oos.GetSecretParametersByPathResponse, error) { - return nil, fmt.Errorf("mocked error") + return nil, errors.New("mocked error") } func TestInit(t *testing.T) { diff --git a/secretstores/aws/parameterstore/parameterstore_test.go b/secretstores/aws/parameterstore/parameterstore_test.go index 9747f58b2a..8d9bcf6065 100644 --- a/secretstores/aws/parameterstore/parameterstore_test.go +++ b/secretstores/aws/parameterstore/parameterstore_test.go @@ -16,6 +16,7 @@ package parameterstore import ( "context" + "errors" "fmt" "strings" "testing" @@ -154,7 +155,7 @@ func TestGetSecret(t *testing.T) { s := ssmSecretStore{ client: &mockedSSM{ GetParameterFn: func(ctx context.Context, input *ssm.GetParameterInput, option ...request.Option) (*ssm.GetParameterOutput, error) { - return nil, fmt.Errorf("failed due to any reason") + return nil, errors.New("failed due to any reason") }, }, } @@ -253,7 +254,7 @@ func TestGetBulkSecrets(t *testing.T) { }}, nil }, GetParameterFn: func(ctx context.Context, input *ssm.GetParameterInput, option ...request.Option) (*ssm.GetParameterOutput, error) { - return nil, fmt.Errorf("failed due to any reason") + return nil, errors.New("failed due to any reason") }, }, } @@ -268,7 +269,7 @@ func TestGetBulkSecrets(t *testing.T) { s := ssmSecretStore{ client: &mockedSSM{ DescribeParametersFn: func(context.Context, *ssm.DescribeParametersInput, ...request.Option) (*ssm.DescribeParametersOutput, error) { - return nil, fmt.Errorf("failed due to any reason") + return nil, errors.New("failed due to any reason") }, }, } diff --git a/secretstores/aws/secretmanager/secretmanager_test.go b/secretstores/aws/secretmanager/secretmanager_test.go index 1a38452d94..85918237a3 100644 --- a/secretstores/aws/secretmanager/secretmanager_test.go +++ b/secretstores/aws/secretmanager/secretmanager_test.go @@ -16,7 +16,7 @@ package secretmanager import ( "context" - "fmt" + "errors" "testing" "github.com/aws/aws-sdk-go/aws/request" @@ -141,7 +141,7 @@ func TestGetSecret(t *testing.T) { s := smSecretStore{ client: &mockedSM{ GetSecretValueFn: func(ctx context.Context, input *secretsmanager.GetSecretValueInput, option ...request.Option) (*secretsmanager.GetSecretValueOutput, error) { - return nil, fmt.Errorf("failed due to any reason") + return nil, errors.New("failed due to any reason") }, }, } diff --git a/secretstores/gcp/secretmanager/secretmanager.go b/secretstores/gcp/secretmanager/secretmanager.go index 619c8ea201..19c795204c 100644 --- a/secretstores/gcp/secretmanager/secretmanager.go +++ b/secretstores/gcp/secretmanager/secretmanager.go @@ -16,6 +16,7 @@ package secretmanager import ( "context" "encoding/json" + "errors" "fmt" "reflect" @@ -103,11 +104,11 @@ func (s *Store) GetSecret(ctx context.Context, req secretstores.GetSecretRequest res := secretstores.GetSecretResponse{Data: nil} if s.client == nil { - return res, fmt.Errorf("client is not initialized") + return res, errors.New("client is not initialized") } if req.Name == "" { - return res, fmt.Errorf("missing secret name in request") + return res, errors.New("missing secret name in request") } secretName := fmt.Sprintf("projects/%s/secrets/%s", s.ProjectID, req.Name) @@ -131,11 +132,11 @@ func (s *Store) BulkGetSecret(ctx context.Context, req secretstores.BulkGetSecre response := map[string]map[string]string{} if s.client == nil { - return secretstores.BulkGetSecretResponse{Data: nil}, fmt.Errorf("client is not initialized") + return secretstores.BulkGetSecretResponse{Data: nil}, errors.New("client is not initialized") } request := &secretmanagerpb.ListSecretsRequest{ - Parent: fmt.Sprintf("projects/%s", s.ProjectID), + Parent: "projects/" + s.ProjectID, } it := s.client.ListSecrets(ctx, request) @@ -183,16 +184,16 @@ func (s *Store) parseSecretManagerMetadata(metadataRaw secretstores.Metadata) (* } if meta.Type == "" { - return nil, fmt.Errorf("missing property `type` in metadata") + return nil, errors.New("missing property `type` in metadata") } if meta.ProjectID == "" { - return nil, fmt.Errorf("missing property `project_id` in metadata") + return nil, errors.New("missing property `project_id` in metadata") } if meta.PrivateKey == "" { - return nil, fmt.Errorf("missing property `private_key` in metadata") + return nil, errors.New("missing property `private_key` in metadata") } if meta.ClientEmail == "" { - return nil, fmt.Errorf("missing property `client_email` in metadata") + return nil, errors.New("missing property `client_email` in metadata") } return &meta, nil diff --git a/secretstores/gcp/secretmanager/secretmanager_test.go b/secretstores/gcp/secretmanager/secretmanager_test.go index ce125ab49b..10db5d49d3 100644 --- a/secretstores/gcp/secretmanager/secretmanager_test.go +++ b/secretstores/gcp/secretmanager/secretmanager_test.go @@ -15,7 +15,7 @@ package secretmanager import ( "context" - "fmt" + "errors" "testing" secretmanager "cloud.google.com/go/secretmanager/apiv1" @@ -71,7 +71,7 @@ func TestInit(t *testing.T) { err := sm.Init(ctx, m) require.Error(t, err) - assert.Equal(t, err, fmt.Errorf("failed to setup secretmanager client: google: could not parse key: private key should be a PEM or plain PKCS1 or PKCS8; parse error: asn1: syntax error: truncated tag or length")) + assert.Equal(t, err, errors.New("failed to setup secretmanager client: google: could not parse key: private key should be a PEM or plain PKCS1 or PKCS8; parse error: asn1: syntax error: truncated tag or length")) }) t.Run("Init with missing `type` metadata", func(t *testing.T) { @@ -80,7 +80,7 @@ func TestInit(t *testing.T) { } err := sm.Init(ctx, m) require.Error(t, err) - assert.Equal(t, err, fmt.Errorf("missing property `type` in metadata")) + assert.Equal(t, err, errors.New("missing property `type` in metadata")) }) t.Run("Init with missing `project_id` metadata", func(t *testing.T) { @@ -89,7 +89,7 @@ func TestInit(t *testing.T) { } err := sm.Init(ctx, m) require.Error(t, err) - assert.Equal(t, err, fmt.Errorf("missing property `project_id` in metadata")) + assert.Equal(t, err, errors.New("missing property `project_id` in metadata")) }) } @@ -100,7 +100,7 @@ func TestGetSecret(t *testing.T) { t.Run("Get Secret - without Init", func(t *testing.T) { v, err := sm.GetSecret(context.Background(), secretstores.GetSecretRequest{Name: "test"}) require.Error(t, err) - assert.Equal(t, err, fmt.Errorf("client is not initialized")) + assert.Equal(t, err, errors.New("client is not initialized")) assert.Equal(t, secretstores.GetSecretResponse{Data: nil}, v) }) @@ -154,7 +154,7 @@ func TestBulkGetSecret(t *testing.T) { t.Run("Bulk Get Secret - without Init", func(t *testing.T) { v, err := sm.BulkGetSecret(context.Background(), secretstores.BulkGetSecretRequest{}) require.Error(t, err) - assert.Equal(t, err, fmt.Errorf("client is not initialized")) + assert.Equal(t, err, errors.New("client is not initialized")) assert.Equal(t, secretstores.BulkGetSecretResponse{Data: nil}, v) }) diff --git a/secretstores/hashicorp/vault/vault.go b/secretstores/hashicorp/vault/vault.go index ffb02bd470..beab8cc7eb 100644 --- a/secretstores/hashicorp/vault/vault.go +++ b/secretstores/hashicorp/vault/vault.go @@ -400,12 +400,12 @@ func (v *vaultSecretStore) isSecretPath(key string) bool { func (v *vaultSecretStore) initVaultToken() error { // Test that at least one of them are set if not return error if v.vaultToken == "" && v.vaultTokenMountPath == "" { - return fmt.Errorf("token mount path and token not set") + return errors.New("token mount path and token not set") } // Test that both are not set. If so return error if v.vaultToken != "" && v.vaultTokenMountPath != "" { - return fmt.Errorf("token mount path and token both set") + return errors.New("token mount path and token both set") } if v.vaultToken != "" { @@ -464,7 +464,7 @@ func (v *vaultSecretStore) getRootCAsPools(vaultCAPem string, vaultCAPath string certPool := x509.NewCertPool() cert := []byte(vaultCAPem) if ok := certPool.AppendCertsFromPEM(cert); !ok { - return nil, fmt.Errorf("couldn't read PEM") + return nil, errors.New("couldn't read PEM") } return certPool, nil @@ -505,7 +505,7 @@ func readCertificateFile(certPool *x509.CertPool, path string) error { } if ok := certPool.AppendCertsFromPEM(pemFile); !ok { - return fmt.Errorf("couldn't read PEM") + return errors.New("couldn't read PEM") } return nil diff --git a/secretstores/huaweicloud/csms/csms_test.go b/secretstores/huaweicloud/csms/csms_test.go index 93dd6d9e8e..a1e2eb15ad 100644 --- a/secretstores/huaweicloud/csms/csms_test.go +++ b/secretstores/huaweicloud/csms/csms_test.go @@ -15,7 +15,7 @@ package csms import ( "context" - "fmt" + "errors" "testing" "github.com/huaweicloud/huaweicloud-sdk-go-v3/services/csms/v1/model" @@ -72,17 +72,17 @@ func (m *mockedCsmsSecretStoreReturnError) ListSecrets(request *model.ListSecret } func (m *mockedCsmsSecretStoreReturnError) ShowSecretVersion(request *model.ShowSecretVersionRequest) (*model.ShowSecretVersionResponse, error) { - return nil, fmt.Errorf("mocked error") + return nil, errors.New("mocked error") } type mockedCsmsSecretStoreBothReturnError struct{} func (m *mockedCsmsSecretStoreBothReturnError) ListSecrets(request *model.ListSecretsRequest) (*model.ListSecretsResponse, error) { - return nil, fmt.Errorf("mocked error") + return nil, errors.New("mocked error") } func (m *mockedCsmsSecretStoreBothReturnError) ShowSecretVersion(request *model.ShowSecretVersionRequest) (*model.ShowSecretVersionResponse, error) { - return nil, fmt.Errorf("mocked error") + return nil, errors.New("mocked error") } func TestGetSecret(t *testing.T) { diff --git a/secretstores/local/file/filestore.go b/secretstores/local/file/filestore.go index 09e183237d..27bc71cfbe 100644 --- a/secretstores/local/file/filestore.go +++ b/secretstores/local/file/filestore.go @@ -196,7 +196,7 @@ func (j *localSecretStore) visitPrimitive(context string) error { } func (j *localSecretStore) visitArray(array []interface{}) error { - for i := 0; i < len(array); i++ { + for i := range array { j.enterContext(strconv.Itoa(i)) err := j.visitProperty(array[i]) if err != nil { @@ -244,7 +244,7 @@ func (j *localSecretStore) getLocalSecretStoreMetadata(spec secretstores.Metadat } if meta.SecretsFile == "" { - return nil, fmt.Errorf("missing local secrets file in metadata") + return nil, errors.New("missing local secrets file in metadata") } return &meta, nil diff --git a/secretstores/local/file/filestore_test.go b/secretstores/local/file/filestore_test.go index 374d8c8001..54df50e939 100644 --- a/secretstores/local/file/filestore_test.go +++ b/secretstores/local/file/filestore_test.go @@ -17,6 +17,7 @@ package file import ( "context" "encoding/json" + "errors" "fmt" "testing" @@ -52,7 +53,7 @@ func TestInit(t *testing.T) { } err := s.Init(context.Background(), m) require.Error(t, err) - assert.Equal(t, err, fmt.Errorf("missing local secrets file in metadata")) + assert.Equal(t, err, errors.New("missing local secrets file in metadata")) }) } diff --git a/secretstores/secret_store.go b/secretstores/secret_store.go index 6214c568cd..89875cf8aa 100644 --- a/secretstores/secret_store.go +++ b/secretstores/secret_store.go @@ -15,7 +15,7 @@ package secretstores import ( "context" - "fmt" + "errors" "io" "github.com/dapr/components-contrib/health" @@ -43,6 +43,6 @@ func Ping(ctx context.Context, secretStore SecretStore) error { if secretStoreWithPing, ok := secretStore.(health.Pinger); ok { return secretStoreWithPing.Ping(ctx) } else { - return fmt.Errorf("ping is not implemented by this secret store") + return errors.New("ping is not implemented by this secret store") } } diff --git a/secretstores/tencentcloud/ssm/ssm_test.go b/secretstores/tencentcloud/ssm/ssm_test.go index 9ca94965ee..187ec48234 100644 --- a/secretstores/tencentcloud/ssm/ssm_test.go +++ b/secretstores/tencentcloud/ssm/ssm_test.go @@ -15,7 +15,7 @@ package ssm import ( "context" - "fmt" + "errors" "testing" "github.com/stretchr/testify/assert" @@ -77,17 +77,17 @@ func (m *mockedSsmSecretStoreReturnError) ListSecretsWithContext(ctx context.Con } func (m *mockedSsmSecretStoreReturnError) GetSecretValueWithContext(ctx context.Context, request *ssm.GetSecretValueRequest) (*ssm.GetSecretValueResponse, error) { - return nil, fmt.Errorf("mocked error") + return nil, errors.New("mocked error") } type mockedSsmSecretStoreBothReturnError struct{} func (m *mockedSsmSecretStoreBothReturnError) ListSecretsWithContext(ctx context.Context, request *ssm.ListSecretsRequest) (*ssm.ListSecretsResponse, error) { - return nil, fmt.Errorf("mocked error") + return nil, errors.New("mocked error") } func (m *mockedSsmSecretStoreBothReturnError) GetSecretValueWithContext(ctx context.Context, request *ssm.GetSecretValueRequest) (*ssm.GetSecretValueResponse, error) { - return nil, fmt.Errorf("mocked error") + return nil, errors.New("mocked error") } func TestGetSecret(t *testing.T) { diff --git a/state/aerospike/aerospike.go b/state/aerospike/aerospike.go index 27206519b6..fc1bd00cf9 100644 --- a/state/aerospike/aerospike.go +++ b/state/aerospike/aerospike.go @@ -261,6 +261,7 @@ func parseHosts(hostsMeta string) ([]*as.Host, error) { if err != nil { return nil, errInvalidHosts } + //nolint:gosec hostPorts = append(hostPorts, as.NewHost(host, int(port))) } diff --git a/state/aws/dynamodb/dynamodb_test.go b/state/aws/dynamodb/dynamodb_test.go index 238fcd6919..d1f98b70ba 100644 --- a/state/aws/dynamodb/dynamodb_test.go +++ b/state/aws/dynamodb/dynamodb_test.go @@ -18,7 +18,6 @@ package dynamodb import ( "context" "errors" - "fmt" "testing" "time" @@ -109,7 +108,7 @@ func TestInit(t *testing.T) { } err := s.Init(context.Background(), m) require.Error(t, err) - assert.Equal(t, err, fmt.Errorf("missing dynamodb table name")) + assert.Equal(t, err, errors.New("missing dynamodb table name")) }) t.Run("Init with valid table", func(t *testing.T) { @@ -267,7 +266,7 @@ func TestGet(t *testing.T) { ss := StateStore{ client: &mockedDynamoDB{ GetItemWithContextFn: func(ctx context.Context, input *dynamodb.GetItemInput, op ...request.Option) (output *dynamodb.GetItemOutput, err error) { - return nil, fmt.Errorf("failed to retrieve data") + return nil, errors.New("failed to retrieve data") }, }, } @@ -606,7 +605,7 @@ func TestSet(t *testing.T) { } ss.client = &mockedDynamoDB{ PutItemWithContextFn: func(ctx context.Context, input *dynamodb.PutItemInput, op ...request.Option) (output *dynamodb.PutItemOutput, err error) { - return nil, fmt.Errorf("unable to put item") + return nil, errors.New("unable to put item") }, } req := &state.SetRequest{ @@ -790,7 +789,7 @@ func TestDelete(t *testing.T) { ss := StateStore{ client: &mockedDynamoDB{ DeleteItemWithContextFn: func(ctx context.Context, input *dynamodb.DeleteItemInput, op ...request.Option) (output *dynamodb.DeleteItemOutput, err error) { - return nil, fmt.Errorf("unable to delete item") + return nil, errors.New("unable to delete item") }, }, } diff --git a/state/azure/blobstorage/internal/blobstorage.go b/state/azure/blobstorage/internal/blobstorage.go index 69f1fa047a..cd4399068f 100644 --- a/state/azure/blobstorage/internal/blobstorage.go +++ b/state/azure/blobstorage/internal/blobstorage.go @@ -148,7 +148,6 @@ func (r *StateStore) writeFile(ctx context.Context, req *state.SetRequest) error blockBlobClient := r.containerClient.NewBlockBlobClient(r.getFileNameFn(req.Key)) _, err = blockBlobClient.UploadBuffer(ctx, r.marshal(req), &uploadOptions) - if err != nil { // Check if the error is due to ETag conflict if req.HasETag() && isETagConflictError(err) { diff --git a/state/azure/blobstorage/internal/blobstorage_test.go b/state/azure/blobstorage/internal/blobstorage_test.go index 233b24e028..d4814b490b 100644 --- a/state/azure/blobstorage/internal/blobstorage_test.go +++ b/state/azure/blobstorage/internal/blobstorage_test.go @@ -15,7 +15,7 @@ package internal import ( "context" - "fmt" + "errors" "testing" "github.com/stretchr/testify/assert" @@ -37,6 +37,6 @@ func TestInit(t *testing.T) { } err := s.Init(context.Background(), m) require.Error(t, err) - assert.Equal(t, err, fmt.Errorf("missing or empty accountName field from metadata")) + assert.Equal(t, err, errors.New("missing or empty accountName field from metadata")) }) } diff --git a/state/azure/cosmosdb/cosmosdb_query.go b/state/azure/cosmosdb/cosmosdb_query.go index 0495827f25..6e25104814 100644 --- a/state/azure/cosmosdb/cosmosdb_query.go +++ b/state/azure/cosmosdb/cosmosdb_query.go @@ -277,9 +277,8 @@ func (q *Query) execute(ctx context.Context, client *azcosmos.ContainerClient) ( token := "" for queryPager.More() { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, defaultTimeout) - queryResponse, innerErr := queryPager.NextPage(ctx) + ctxWithTimeout, cancel := context.WithTimeout(ctx, defaultTimeout) + queryResponse, innerErr := queryPager.NextPage(ctxWithTimeout) cancel() if innerErr != nil { return nil, "", innerErr diff --git a/state/azure/tablestorage/tablestorage.go b/state/azure/tablestorage/tablestorage.go index 7e87f71386..9a4af2ac2a 100644 --- a/state/azure/tablestorage/tablestorage.go +++ b/state/azure/tablestorage/tablestorage.go @@ -258,7 +258,6 @@ func (r *StateStore) writeRow(ctx context.Context, req *state.SetRequest) error // InsertOrReplace does not support ETag concurrency, therefore we will use Insert to check for key existence // and then use Update to update the key if it exists with the specified ETag _, err = r.client.AddEntity(writeContext, marshalledEntity, nil) - if err != nil { // If Insert failed because item already exists, try to Update instead per Upsert semantics if isEntityAlreadyExistsError(err) { diff --git a/state/bulk.go b/state/bulk.go index 3d7d8ac503..b07d57387f 100644 --- a/state/bulk.go +++ b/state/bulk.go @@ -102,7 +102,7 @@ func DoBulkGet(ctx context.Context, req []GetRequest, opts BulkGetOpts, getFn fu } // We can detect that all goroutines are done when limitCh is completely empty - for i := 0; i < opts.Parallelism; i++ { + for range opts.Parallelism { limitCh <- struct{}{} } @@ -149,7 +149,7 @@ func DoBulkSetDelete[T stateRequestConstraint](ctx context.Context, req []T, met } errs := make([]error, len(req)) - for i := 0; i < len(req); i++ { + for i := range req { errs[i] = <-errCh } diff --git a/state/bulk_test.go b/state/bulk_test.go index 0b2e47011e..7d94dabdda 100644 --- a/state/bulk_test.go +++ b/state/bulk_test.go @@ -80,7 +80,7 @@ func TestBulkStore(t *testing.T) { require.True(t, ok) errs := merr.Unwrap() require.Len(t, errs, 2) - for i := 0; i < 2; i++ { + for i := range 2 { var bse BulkStoreError require.ErrorAs(t, errs[i], &bse) assert.True(t, bse.key == "error-key1" || bse.key == "error-key2") diff --git a/state/cassandra/cassandra.go b/state/cassandra/cassandra.go index 370e9d6385..d1cf277252 100644 --- a/state/cassandra/cassandra.go +++ b/state/cassandra/cassandra.go @@ -196,7 +196,7 @@ func getCassandraMetadata(meta state.Metadata) (*cassandraMetadata, error) { } if m.Hosts == nil || len(m.Hosts) == 0 { - return nil, fmt.Errorf("missing or empty hosts field from metadata") + return nil, errors.New("missing or empty hosts field from metadata") } if val, ok := meta.Properties[port]; ok && val != "" { diff --git a/state/cockroachdb/cockroachdb_integration_test.go b/state/cockroachdb/cockroachdb_integration_test.go index 9969da3285..d72138bc3f 100644 --- a/state/cockroachdb/cockroachdb_integration_test.go +++ b/state/cockroachdb/cockroachdb_integration_test.go @@ -213,7 +213,7 @@ func testCreateTable(t *testing.T, db *pgxpool.Pool) { func dropTable(t *testing.T, db *pgxpool.Pool, tableName string) { t.Helper() - _, err := db.Exec(context.Background(), fmt.Sprintf("DROP TABLE %s", tableName)) + _, err := db.Exec(context.Background(), "DROP TABLE "+tableName) require.NoError(t, err) } @@ -237,9 +237,9 @@ func deleteItemThatDoesNotExist(t *testing.T, pgs *postgresql.PostgreSQL) { func multiWithSetOnly(t *testing.T, pgs *postgresql.PostgreSQL) { t.Helper() - var operations []state.TransactionalStateOperation - var setRequests []state.SetRequest - for i := 0; i < 3; i++ { + var operations []state.TransactionalStateOperation //nolint:prealloc + var setRequests []state.SetRequest //nolint:prealloc + for range 3 { req := state.SetRequest{ Key: randomKey(), Value: randomJSON(), @@ -270,9 +270,9 @@ func multiWithSetOnly(t *testing.T, pgs *postgresql.PostgreSQL) { func multiWithDeleteOnly(t *testing.T, pgs *postgresql.PostgreSQL) { t.Helper() - var operations []state.TransactionalStateOperation - var deleteRequests []state.DeleteRequest - for i := 0; i < 3; i++ { + var operations []state.TransactionalStateOperation //nolint:prealloc + var deleteRequests []state.DeleteRequest //nolint:prealloc + for range 3 { req := state.DeleteRequest{ Key: randomKey(), ETag: nil, @@ -307,9 +307,9 @@ func multiWithDeleteOnly(t *testing.T, pgs *postgresql.PostgreSQL) { func multiWithDeleteAndSet(t *testing.T, pgs *postgresql.PostgreSQL) { t.Helper() - var operations []state.TransactionalStateOperation - var deleteRequests []state.DeleteRequest - for i := 0; i < 3; i++ { + var operations []state.TransactionalStateOperation //nolint:prealloc + var deleteRequests []state.DeleteRequest //nolint:prealloc + for range 3 { req := state.DeleteRequest{ Key: randomKey(), ETag: nil, @@ -331,8 +331,8 @@ func multiWithDeleteAndSet(t *testing.T, pgs *postgresql.PostgreSQL) { } // Create the set requests. - var setRequests []state.SetRequest - for i := 0; i < 3; i++ { + var setRequests []state.SetRequest //nolint:prealloc + for range 3 { req := state.SetRequest{ Key: randomKey(), Value: randomJSON(), diff --git a/state/couchbase/couchbase.go b/state/couchbase/couchbase.go index 15060e47d0..c088a39c7a 100644 --- a/state/couchbase/couchbase.go +++ b/state/couchbase/couchbase.go @@ -15,6 +15,7 @@ package couchbase import ( "context" + "errors" "fmt" "reflect" "strconv" @@ -85,19 +86,19 @@ func parseAndValidateMetadata(meta state.Metadata) (*couchbaseMetadata, error) { } if m.CouchbaseURL == "" { - return nil, fmt.Errorf("couchbase URL is missing") + return nil, errors.New("couchbase URL is missing") } if m.Username == "" { - return nil, fmt.Errorf("couchbase username is missing") + return nil, errors.New("couchbase username is missing") } if m.Password == "" { - return nil, fmt.Errorf("couchbase password is missing") + return nil, errors.New("couchbase password is missing") } if m.BucketName == "" { - return nil, fmt.Errorf("couchbase bucket name is missing") + return nil, errors.New("couchbase bucket name is missing") } v := meta.Properties[numReplicasDurableReplication] diff --git a/state/gcp/firestore/firestore.go b/state/gcp/firestore/firestore.go index 5b94e76b9f..2e4b8eb62e 100644 --- a/state/gcp/firestore/firestore.go +++ b/state/gcp/firestore/firestore.go @@ -149,7 +149,6 @@ func (f *Firestore) Set(ctx context.Context, req *state.SetRequest) error { key := datastore.NameKey(f.entityKind, req.Key, nil) _, err = f.client.Put(ctx, key, entity) - if err != nil { return err } diff --git a/state/hazelcast/hazelcast.go b/state/hazelcast/hazelcast.go index 12b45ae67a..2fe56f0488 100644 --- a/state/hazelcast/hazelcast.go +++ b/state/hazelcast/hazelcast.go @@ -86,7 +86,6 @@ func (store *Hazelcast) Init(_ context.Context, metadata state.Metadata) error { return err } store.hzMap, err = client.GetMap(meta.HazelcastMap) - if err != nil { return err } @@ -117,7 +116,6 @@ func (store *Hazelcast) Set(ctx context.Context, req *state.SetRequest) error { } } _, err = store.hzMap.Put(req.Key, value) - if err != nil { return fmt.Errorf("failed to set key %s: %w", req.Key, err) } diff --git a/state/memcached/memcached.go b/state/memcached/memcached.go index 8d91508f5d..81378439fc 100644 --- a/state/memcached/memcached.go +++ b/state/memcached/memcached.go @@ -117,7 +117,7 @@ func getMemcachedMetadata(meta state.Metadata) (*memcachedMetadata, error) { if val, ok := meta.Properties[maxIdleConnections]; ok && val != "" { p, err := strconv.Atoi(val) if err != nil { - return nil, fmt.Errorf("error parsing maxIdleConnections") + return nil, errors.New("error parsing maxIdleConnections") } m.MaxIdleConnections = p } @@ -125,7 +125,7 @@ func getMemcachedMetadata(meta state.Metadata) (*memcachedMetadata, error) { if val, ok := meta.Properties[timeout]; ok && val != "" { p, err := strconv.Atoi(val) if err != nil { - return nil, fmt.Errorf("error parsing timeout") + return nil, errors.New("error parsing timeout") } m.Timeout = p } @@ -145,7 +145,7 @@ func (m *Memcached) parseTTL(req *state.SetRequest) (*int32, error) { // If ttl is more than 30 days, convert it to unix timestamp. // https://github.com/memcached/memcached/wiki/Commands#standard-protocol if parsedInt >= 60*60*24*30 { - parsedInt = int32(m.clock.Now().Unix()) + parsedInt + parsedInt = int32(m.clock.Now().Unix()) + parsedInt //nolint:gosec } // Notice that for Dapr, -1 means "persist with no TTL". diff --git a/state/mongodb/mongodb_query.go b/state/mongodb/mongodb_query.go index 27d132eed2..019f0ed24a 100644 --- a/state/mongodb/mongodb_query.go +++ b/state/mongodb/mongodb_query.go @@ -102,7 +102,7 @@ func (q *Query) VisitIN(f *query.IN) (string, error) { } str := fmt.Sprintf(`{ "value.%s": { "$in": [ `, f.Key) - for i := 0; i < len(f.Vals); i++ { + for i := range len(f.Vals) { if i > 0 { str += ", " } diff --git a/state/mysql/mySQLFactory.go b/state/mysql/mySQLFactory.go index 5cec7c9582..3776b10013 100644 --- a/state/mysql/mySQLFactory.go +++ b/state/mysql/mySQLFactory.go @@ -17,7 +17,7 @@ import ( "crypto/tls" "crypto/x509" "database/sql" - "fmt" + "errors" "os" "github.com/go-sql-driver/mysql" @@ -56,7 +56,7 @@ func (m *mySQLFactory) RegisterTLSConfig(pemPath string) error { ok := rootCertPool.AppendCertsFromPEM(pem) if !ok { - return fmt.Errorf("failed to append PEM") + return errors.New("failed to append PEM") } mysql.RegisterTLSConfig("custom", &tls.Config{RootCAs: rootCertPool, MinVersion: tls.VersionTLS12}) diff --git a/state/mysql/mysql.go b/state/mysql/mysql.go index 8bf90b814f..d963d483ac 100644 --- a/state/mysql/mysql.go +++ b/state/mysql/mysql.go @@ -189,7 +189,7 @@ func (m *MySQL) parseMetadata(md map[string]string) error { if meta.ConnectionString == "" { m.logger.Error("Missing MySql connection string") - return fmt.Errorf(errMissingConnectionString) + return errors.New(errMissingConnectionString) } m.connectionString = meta.ConnectionString @@ -328,7 +328,6 @@ func (m *MySQL) ensureStateSchema(ctx context.Context) error { // Close the connection we used to confirm and or create the schema err = m.db.Close() - if err != nil { return err } @@ -463,7 +462,7 @@ func (m *MySQL) Delete(ctx context.Context, req *state.DeleteRequest) error { // logic to state.DeleteWithRetries as a func. func (m *MySQL) deleteValue(parentCtx context.Context, querier querier, req *state.DeleteRequest) error { if req.Key == "" { - return fmt.Errorf("missing key in delete operation") + return errors.New("missing key in delete operation") } var ( @@ -636,7 +635,6 @@ func (m *MySQL) setValue(parentCtx context.Context, querier querier, req *state. ctx, cancel := context.WithTimeout(parentCtx, m.timeout) defer cancel() result, err = querier.ExecContext(ctx, query, params...) - if err != nil { return err } @@ -831,7 +829,7 @@ func validIdentifier(v string) bool { // Loop through the string as byte slice as we only care about ASCII characters b := []byte(v) - for i := 0; i < len(b); i++ { + for i := range b { if (b[i] >= '0' && b[i] <= '9') || (b[i] >= 'a' && b[i] <= 'z') || (b[i] >= 'A' && b[i] <= 'Z') || diff --git a/state/mysql/mysql_integration_test.go b/state/mysql/mysql_integration_test.go index 22052ad5e8..4bce423ba2 100644 --- a/state/mysql/mysql_integration_test.go +++ b/state/mysql/mysql_integration_test.go @@ -454,7 +454,7 @@ func TestMySQLIntegration(t *testing.T) { var operations []state.TransactionalStateOperation var deleteRequests []state.DeleteRequest - for i := 0; i < 3; i++ { + for range 3 { req := state.DeleteRequest{Key: randomKey()} // Add the item to the database @@ -469,7 +469,7 @@ func TestMySQLIntegration(t *testing.T) { // Create the set requests var setRequests []state.SetRequest - for i := 0; i < 3; i++ { + for range 3 { req := state.SetRequest{ Key: randomKey(), Value: randomJSON(), @@ -498,7 +498,7 @@ func TestMySQLIntegration(t *testing.T) { var operations []state.TransactionalStateOperation var deleteRequests []state.DeleteRequest - for i := 0; i < 3; i++ { + for range 3 { req := state.DeleteRequest{Key: randomKey()} // Add the item to the database @@ -526,7 +526,7 @@ func TestMySQLIntegration(t *testing.T) { var operations []state.TransactionalStateOperation var setRequests []state.SetRequest - for i := 0; i < 3; i++ { + for range 3 { req := state.SetRequest{ Key: randomKey(), Value: randomJSON(), diff --git a/state/mysql/mysql_test.go b/state/mysql/mysql_test.go index 0dacfaf158..4b6ea3da93 100644 --- a/state/mysql/mysql_test.go +++ b/state/mysql/mysql_test.go @@ -21,7 +21,6 @@ import ( "encoding/base64" "encoding/json" "errors" - "fmt" "testing" "time" @@ -65,7 +64,7 @@ func TestFinishInitHandlesSchemaExistsError(t *testing.T) { m, _ := mockDatabase(t) defer m.mySQL.Close() - expectedErr := fmt.Errorf("existsError") + expectedErr := errors.New("existsError") m.mock1.ExpectQuery("SELECT EXISTS").WillReturnError(expectedErr) // Act @@ -84,7 +83,7 @@ func TestFinishInitHandlesDatabaseCreateError(t *testing.T) { rows := sqlmock.NewRows([]string{"exists"}).AddRow(0) m.mock1.ExpectQuery("SELECT EXISTS").WillReturnRows(rows) - expectedErr := fmt.Errorf("createDatabaseError") + expectedErr := errors.New("createDatabaseError") m.mock1.ExpectExec("CREATE DATABASE").WillReturnError(expectedErr) // Act @@ -108,7 +107,7 @@ func TestFinishInitHandlesPingError(t *testing.T) { m.mock1.ExpectClose() - expectedErr := fmt.Errorf("pingError") + expectedErr := errors.New("pingError") m.mock2.ExpectPing().WillReturnError(expectedErr) // Act @@ -137,7 +136,7 @@ func TestFinishInitHandlesTableExistsError(t *testing.T) { // Execute use command m.mock2.ExpectPing() - m.mock2.ExpectQuery("SELECT EXISTS").WillReturnError(fmt.Errorf("tableExistsError")) + m.mock2.ExpectQuery("SELECT EXISTS").WillReturnError(errors.New("tableExistsError")) // Act err := m.mySQL.finishInit(context.Background(), m.mySQL.db) @@ -391,7 +390,7 @@ func TestGetHandlesGenericError(t *testing.T) { m, _ := mockDatabase(t) defer m.mySQL.Close() - m.mock1.ExpectQuery("").WillReturnError(fmt.Errorf("generic error")) + m.mock1.ExpectQuery("").WillReturnError(errors.New("generic error")) request := &state.GetRequest{ Key: "UnitTest", @@ -479,7 +478,7 @@ func TestEnsureStateTableHandlesCreateTableError(t *testing.T) { rows := sqlmock.NewRows([]string{"exists"}).AddRow(0) m.mock1.ExpectQuery("SELECT EXISTS").WillReturnRows(rows) - m.mock1.ExpectExec("CREATE TABLE").WillReturnError(fmt.Errorf("CreateTableError")) + m.mock1.ExpectExec("CREATE TABLE").WillReturnError(errors.New("CreateTableError")) // Act err := m.mySQL.ensureStateTable(context.Background(), "dapr_state_store", "state") @@ -550,7 +549,7 @@ func TestInitHandlesRegisterTLSConfigError(t *testing.T) { // Arrange t.Parallel() m, _ := mockDatabase(t) - m.factory.registerErr = fmt.Errorf("registerTLSConfigError") + m.factory.registerErr = errors.New("registerTLSConfigError") metadata := &state.Metadata{ Base: metadata.Base{ diff --git a/state/oci/objectstorage/objectstorage.go b/state/oci/objectstorage/objectstorage.go index 11d8903eaf..d2d87accb1 100644 --- a/state/oci/objectstorage/objectstorage.go +++ b/state/oci/objectstorage/objectstorage.go @@ -16,6 +16,7 @@ package objectstorage import ( "bytes" "context" + "errors" "fmt" "io" "net/http" @@ -256,11 +257,11 @@ func getIdentityAuthenticationDetails(meta objectStoreMetadata) (err error) { // functions that bridge from the Dapr State API to the OCI ObjectStorage Client. func (r *StateStore) writeDocument(ctx context.Context, req *state.SetRequest) error { if len(req.Key) == 0 || req.Key == "" { - return fmt.Errorf("key for value to set was missing from request") + return errors.New("key for value to set was missing from request") } if req.Options.Concurrency == state.FirstWrite && (req.ETag == nil || len(*req.ETag) == 0) { r.logger.Debugf("when FirstWrite is to be enforced, a value must be provided for the ETag") - return fmt.Errorf("when FirstWrite is to be enforced, a value must be provided for the ETag") + return errors.New("when FirstWrite is to be enforced, a value must be provided for the ETag") } metadata := (map[string]string{"category": daprStateStoreMetaLabel}) @@ -299,7 +300,7 @@ func (r *StateStore) convertTTLtoExpiryTime(req *state.SetRequest, metadata map[ func (r *StateStore) readDocument(ctx context.Context, req *state.GetRequest) ([]byte, *string, error) { if len(req.Key) == 0 || req.Key == "" { - return nil, nil, fmt.Errorf("key for value to get was missing from request") + return nil, nil, errors.New("key for value to get was missing from request") } objectName := getFileName(req.Key) content, etag, meta, err := r.client.getObject(ctx, objectName) @@ -331,7 +332,7 @@ func (r *StateStore) pingBucket(ctx context.Context) error { func (r *StateStore) deleteDocument(ctx context.Context, req *state.DeleteRequest) error { if len(req.Key) == 0 || req.Key == "" { - return fmt.Errorf("key for value to delete was missing from request") + return errors.New("key for value to delete was missing from request") } objectName := getFileName(req.Key) @@ -341,7 +342,7 @@ func (r *StateStore) deleteDocument(ctx context.Context, req *state.DeleteReques } if req.Options.Concurrency == state.FirstWrite && (etag == nil || len(*etag) == 0) { r.logger.Debugf("when FirstWrite is to be enforced, a value must be provided for the ETag") - return fmt.Errorf("when FirstWrite is to be enforced, a value must be provided for the ETag") + return errors.New("when FirstWrite is to be enforced, a value must be provided for the ETag") } err := r.client.deleteObject(ctx, objectName, etag) if err != nil { diff --git a/state/oci/objectstorage/objectstorage_integration_test.go b/state/oci/objectstorage/objectstorage_integration_test.go index 5ae2317eeb..c963fada2f 100644 --- a/state/oci/objectstorage/objectstorage_integration_test.go +++ b/state/oci/objectstorage/objectstorage_integration_test.go @@ -5,7 +5,7 @@ package objectstorage import ( "context" - "fmt" + "errors" "os" "testing" "time" @@ -159,7 +159,7 @@ func testSet(t *testing.T, ociProperties map[string]string) { err := statestore.Init(context.Background(), meta) require.NoError(t, err) err = statestore.Set(context.Background(), &state.SetRequest{Value: []byte("test-value")}) - assert.Equal(t, err, fmt.Errorf("key for value to set was missing from request"), "Lacking Key results in error") + assert.Equal(t, err, errors.New("key for value to set was missing from request"), "Lacking Key results in error") }) t.Run("Regular Set Operation", func(t *testing.T) { testKey := "local-test-key" @@ -235,7 +235,7 @@ func testDelete(t *testing.T, ociProperties map[string]string) { err := s.Init(context.Background(), m) require.NoError(t, err) err = s.Delete(context.Background(), &state.DeleteRequest{}) - assert.Equal(t, err, fmt.Errorf("key for value to delete was missing from request"), "Lacking Key results in error") + assert.Equal(t, err, errors.New("key for value to delete was missing from request"), "Lacking Key results in error") }) t.Run("Regular Delete Operation", func(t *testing.T) { testKey := "test-key" diff --git a/state/oci/objectstorage/objectstorage_test.go b/state/oci/objectstorage/objectstorage_test.go index 5f40a6ec00..b1ef3ddfb7 100644 --- a/state/oci/objectstorage/objectstorage_test.go +++ b/state/oci/objectstorage/objectstorage_test.go @@ -15,7 +15,7 @@ package objectstorage import ( "context" - "fmt" + "errors" "io" "testing" "time" @@ -55,42 +55,42 @@ func TestInit(t *testing.T) { meta.Properties[regionKey] = "" err := statestore.Init(context.Background(), meta) require.Error(t, err) - assert.Equal(t, fmt.Errorf("missing or empty region field from metadata"), err, "Lacking configuration property should be spotted") + assert.Equal(t, errors.New("missing or empty region field from metadata"), err, "Lacking configuration property should be spotted") }) t.Run("Init with missing tenancyOCID", func(t *testing.T) { meta.Properties = getDummyOCIObjectStorageConfiguration() meta.Properties["tenancyOCID"] = "" err := statestore.Init(context.Background(), meta) require.Error(t, err) - assert.Equal(t, fmt.Errorf("missing or empty tenancyOCID field from metadata"), err, "Lacking configuration property should be spotted") + assert.Equal(t, errors.New("missing or empty tenancyOCID field from metadata"), err, "Lacking configuration property should be spotted") }) t.Run("Init with missing userOCID", func(t *testing.T) { meta.Properties = getDummyOCIObjectStorageConfiguration() meta.Properties[userKey] = "" err := statestore.Init(context.Background(), meta) require.Error(t, err) - assert.Equal(t, fmt.Errorf("missing or empty userOCID field from metadata"), err, "Lacking configuration property should be spotted") + assert.Equal(t, errors.New("missing or empty userOCID field from metadata"), err, "Lacking configuration property should be spotted") }) t.Run("Init with missing compartmentOCID", func(t *testing.T) { meta.Properties = getDummyOCIObjectStorageConfiguration() meta.Properties[compartmentKey] = "" err := statestore.Init(context.Background(), meta) require.Error(t, err) - assert.Equal(t, fmt.Errorf("missing or empty compartmentOCID field from metadata"), err, "Lacking configuration property should be spotted") + assert.Equal(t, errors.New("missing or empty compartmentOCID field from metadata"), err, "Lacking configuration property should be spotted") }) t.Run("Init with missing fingerprint", func(t *testing.T) { meta.Properties = getDummyOCIObjectStorageConfiguration() meta.Properties[fingerPrintKey] = "" err := statestore.Init(context.Background(), meta) require.Error(t, err) - assert.Equal(t, fmt.Errorf("missing or empty fingerPrint field from metadata"), err, "Lacking configuration property should be spotted") + assert.Equal(t, errors.New("missing or empty fingerPrint field from metadata"), err, "Lacking configuration property should be spotted") }) t.Run("Init with missing private key", func(t *testing.T) { meta.Properties = getDummyOCIObjectStorageConfiguration() meta.Properties[privateKeyKey] = "" err := statestore.Init(context.Background(), meta) require.Error(t, err) - assert.Equal(t, fmt.Errorf("missing or empty privateKey field from metadata"), err, "Lacking configuration property should be spotted") + assert.Equal(t, errors.New("missing or empty privateKey field from metadata"), err, "Lacking configuration property should be spotted") }) t.Run("Init with incorrect value for instancePrincipalAuthentication", func(t *testing.T) { meta.Properties = getDummyOCIObjectStorageConfiguration() @@ -202,10 +202,10 @@ func (c *mockedObjectStoreClient) getObject(ctx context.Context, objectname stri func (c *mockedObjectStoreClient) deleteObject(ctx context.Context, objectname string, etag *string) (err error) { c.deleteIsCalled = true if objectname == "unknownKey" { - return fmt.Errorf("failed to delete object that does not exist - HTTP status code 404") + return errors.New("failed to delete object that does not exist - HTTP status code 404") } if etag != nil && *etag == "notTheCorrectETag" { - return fmt.Errorf("failed to delete object because of incorrect etag-value ") + return errors.New("failed to delete object because of incorrect etag-value ") } return nil } @@ -213,7 +213,7 @@ func (c *mockedObjectStoreClient) deleteObject(ctx context.Context, objectname s func (c *mockedObjectStoreClient) putObject(ctx context.Context, objectname string, contentLen int64, content io.ReadCloser, metadata map[string]string, etag *string) error { c.putIsCalled = true if etag != nil && *etag == "notTheCorrectETag" { - return fmt.Errorf("failed to delete object because of incorrect etag-value ") + return errors.New("failed to delete object because of incorrect etag-value ") } if etag != nil && *etag == "correctETag" { return nil @@ -290,7 +290,7 @@ func TestSetWithMockClient(t *testing.T) { statestore.client = mockClient t.Run("Set without a key", func(t *testing.T) { err := statestore.Set(context.Background(), &state.SetRequest{Value: []byte("test-value")}) - assert.Equal(t, err, fmt.Errorf("key for value to set was missing from request"), "Lacking Key results in error") + assert.Equal(t, err, errors.New("key for value to set was missing from request"), "Lacking Key results in error") }) t.Run("Regular Set Operation", func(t *testing.T) { testKey := "test-key" @@ -349,7 +349,7 @@ func TestDeleteWithMockClient(t *testing.T) { s.client = mockClient t.Run("Delete without a key", func(t *testing.T) { err := s.Delete(context.Background(), &state.DeleteRequest{}) - assert.Equal(t, err, fmt.Errorf("key for value to delete was missing from request"), "Lacking Key results in error") + assert.Equal(t, err, errors.New("key for value to delete was missing from request"), "Lacking Key results in error") }) t.Run("Delete with an unknown key", func(t *testing.T) { err := s.Delete(context.Background(), &state.DeleteRequest{Key: "unknownKey"}) diff --git a/state/oracledatabase/oracledatabase_integration_test.go b/state/oracledatabase/oracledatabase_integration_test.go index 27dd4d6769..aef87e6ef7 100644 --- a/state/oracledatabase/oracledatabase_integration_test.go +++ b/state/oracledatabase/oracledatabase_integration_test.go @@ -199,7 +199,7 @@ func testCreateTable(t *testing.T, dba *oracleDatabaseAccess) { } func dropTable(t *testing.T, db *sql.DB, tableName string) { - _, err := db.Exec(fmt.Sprintf("DROP TABLE %s", tableName)) + _, err := db.Exec("DROP TABLE " + tableName) require.NoError(t, err) } @@ -213,9 +213,9 @@ func deleteItemThatDoesNotExist(t *testing.T, ods state.Store) { } func multiWithSetOnly(t *testing.T, ods state.Store) { - var operations []state.TransactionalStateOperation - var setRequests []state.SetRequest - for i := 0; i < 3; i++ { + var operations []state.TransactionalStateOperation //nolint:prealloc + var setRequests []state.SetRequest //nolint:prealloc + for range 3 { req := state.SetRequest{ Key: randomKey(), Value: randomJSON(), @@ -238,9 +238,9 @@ func multiWithSetOnly(t *testing.T, ods state.Store) { } func multiWithDeleteOnly(t *testing.T, ods state.Store) { - var operations []state.TransactionalStateOperation - var deleteRequests []state.DeleteRequest - for i := 0; i < 3; i++ { + var operations []state.TransactionalStateOperation //nolint:prealloc + var deleteRequests []state.DeleteRequest //nolint:prealloc + for range 3 { req := state.DeleteRequest{Key: randomKey()} // Add the item to the database. @@ -265,9 +265,9 @@ func multiWithDeleteOnly(t *testing.T, ods state.Store) { } func multiWithDeleteAndSet(t *testing.T, ods state.Store) { - var operations []state.TransactionalStateOperation - var deleteRequests []state.DeleteRequest - for i := 0; i < 3; i++ { + var operations []state.TransactionalStateOperation //nolint:prealloc + var deleteRequests []state.DeleteRequest //nolint:prealloc + for range 3 { req := state.DeleteRequest{Key: randomKey()} // Add the item to the database. @@ -281,8 +281,8 @@ func multiWithDeleteAndSet(t *testing.T, ods state.Store) { } // Create the set requests. - var setRequests []state.SetRequest - for i := 0; i < 3; i++ { + var setRequests []state.SetRequest //nolint:prealloc + for range 3 { req := state.SetRequest{ Key: randomKey(), Value: randomJSON(), diff --git a/state/postgresql/v1/postgresql_integration_test.go b/state/postgresql/v1/postgresql_integration_test.go index e69dbef081..31fb148005 100644 --- a/state/postgresql/v1/postgresql_integration_test.go +++ b/state/postgresql/v1/postgresql_integration_test.go @@ -170,9 +170,9 @@ func deleteItemThatDoesNotExist(t *testing.T, pgs *postgresql.PostgreSQL) { } func multiWithSetOnly(t *testing.T, pgs *postgresql.PostgreSQL) { - var operations []state.TransactionalStateOperation - var setRequests []state.SetRequest - for i := 0; i < 3; i++ { + var operations []state.TransactionalStateOperation //nolint:prealloc + var setRequests []state.SetRequest //nolint:prealloc + for range 3 { req := state.SetRequest{ Key: randomKey(), Value: randomJSON(), @@ -193,9 +193,9 @@ func multiWithSetOnly(t *testing.T, pgs *postgresql.PostgreSQL) { } func multiWithDeleteOnly(t *testing.T, pgs *postgresql.PostgreSQL) { - var operations []state.TransactionalStateOperation - var deleteRequests []state.DeleteRequest - for i := 0; i < 3; i++ { + var operations []state.TransactionalStateOperation //nolint:prealloc + var deleteRequests []state.DeleteRequest //nolint:prealloc + for range 3 { req := state.DeleteRequest{Key: randomKey()} // Add the item to the database @@ -219,9 +219,9 @@ func multiWithDeleteOnly(t *testing.T, pgs *postgresql.PostgreSQL) { } func multiWithDeleteAndSet(t *testing.T, pgs *postgresql.PostgreSQL) { - var operations []state.TransactionalStateOperation - var deleteRequests []state.DeleteRequest - for i := 0; i < 3; i++ { + var operations []state.TransactionalStateOperation //nolint:prealloc + var deleteRequests []state.DeleteRequest //nolint:prealloc + for range 3 { req := state.DeleteRequest{Key: randomKey()} // Add the item to the database @@ -235,8 +235,8 @@ func multiWithDeleteAndSet(t *testing.T, pgs *postgresql.PostgreSQL) { } // Create the set requests - var setRequests []state.SetRequest - for i := 0; i < 3; i++ { + var setRequests []state.SetRequest //nolint:prealloc + for range 3 { req := state.SetRequest{ Key: randomKey(), Value: randomJSON(), diff --git a/state/postgresql/v2/postgresql_integration_test.go b/state/postgresql/v2/postgresql_integration_test.go index 1705b61848..23252d88a0 100644 --- a/state/postgresql/v2/postgresql_integration_test.go +++ b/state/postgresql/v2/postgresql_integration_test.go @@ -167,9 +167,9 @@ func deleteItemThatDoesNotExist(t *testing.T, pgs *postgresql.PostgreSQL) { } func multiWithSetOnly(t *testing.T, pgs *postgresql.PostgreSQL) { - var operations []state.TransactionalStateOperation - var setRequests []state.SetRequest - for i := 0; i < 3; i++ { + var operations []state.TransactionalStateOperation //nolint:prealloc + var setRequests []state.SetRequest //nolint:prealloc + for range 3 { req := state.SetRequest{ Key: randomKey(), Value: randomJSON(), @@ -190,9 +190,9 @@ func multiWithSetOnly(t *testing.T, pgs *postgresql.PostgreSQL) { } func multiWithDeleteOnly(t *testing.T, pgs *postgresql.PostgreSQL) { - var operations []state.TransactionalStateOperation - var deleteRequests []state.DeleteRequest - for i := 0; i < 3; i++ { + var operations []state.TransactionalStateOperation //nolint:prealloc + var deleteRequests []state.DeleteRequest //nolint:prealloc + for range 3 { req := state.DeleteRequest{Key: randomKey()} // Add the item to the database @@ -216,9 +216,9 @@ func multiWithDeleteOnly(t *testing.T, pgs *postgresql.PostgreSQL) { } func multiWithDeleteAndSet(t *testing.T, pgs *postgresql.PostgreSQL) { - var operations []state.TransactionalStateOperation - var deleteRequests []state.DeleteRequest - for i := 0; i < 3; i++ { + var operations []state.TransactionalStateOperation //nolint:prealloc + var deleteRequests []state.DeleteRequest //nolint:prealloc + for range 3 { req := state.DeleteRequest{Key: randomKey()} // Add the item to the database @@ -232,8 +232,8 @@ func multiWithDeleteAndSet(t *testing.T, pgs *postgresql.PostgreSQL) { } // Create the set requests - var setRequests []state.SetRequest - for i := 0; i < 3; i++ { + var setRequests []state.SetRequest //nolint:prealloc + for range 3 { req := state.SetRequest{ Key: randomKey(), Value: randomJSON(), diff --git a/state/query/filter.go b/state/query/filter.go index 2b0e64f8cb..9b10b20f9c 100644 --- a/state/query/filter.go +++ b/state/query/filter.go @@ -14,6 +14,7 @@ limitations under the License. package query import ( + "errors" "fmt" ) @@ -25,10 +26,10 @@ type Filter interface { func ParseFilter(obj interface{}) (Filter, error) { m, ok := obj.(map[string]interface{}) if !ok { - return nil, fmt.Errorf("filter unit must be a map") + return nil, errors.New("filter unit must be a map") } if len(m) != 1 { - return nil, fmt.Errorf("filter unit must have a single element") + return nil, errors.New("filter unit must have a single element") } for k, v := range m { switch k { @@ -93,10 +94,10 @@ type EQ struct { func (f *EQ) Parse(obj interface{}) error { m, ok := obj.(map[string]interface{}) if !ok { - return fmt.Errorf("EQ filter must be a map") + return errors.New("EQ filter must be a map") } if len(m) != 1 { - return fmt.Errorf("EQ filter must contain a single key/value pair") + return errors.New("EQ filter must contain a single key/value pair") } for k, v := range m { f.Key = k @@ -114,10 +115,10 @@ type NEQ struct { func (f *NEQ) Parse(obj interface{}) error { m, ok := obj.(map[string]interface{}) if !ok { - return fmt.Errorf("NEQ filter must be a map") + return errors.New("NEQ filter must be a map") } if len(m) != 1 { - return fmt.Errorf("NEQ filter must contain a single key/value pair") + return errors.New("NEQ filter must contain a single key/value pair") } for k, v := range m { f.Key = k @@ -135,10 +136,10 @@ type GT struct { func (f *GT) Parse(obj interface{}) error { m, ok := obj.(map[string]interface{}) if !ok { - return fmt.Errorf("GT filter must be a map") + return errors.New("GT filter must be a map") } if len(m) != 1 { - return fmt.Errorf("GT filter must contain a single key/value pair") + return errors.New("GT filter must contain a single key/value pair") } for k, v := range m { f.Key = k @@ -156,10 +157,10 @@ type GTE struct { func (f *GTE) Parse(obj interface{}) error { m, ok := obj.(map[string]interface{}) if !ok { - return fmt.Errorf("GTE filter must be a map") + return errors.New("GTE filter must be a map") } if len(m) != 1 { - return fmt.Errorf("GTE filter must contain a single key/value pair") + return errors.New("GTE filter must contain a single key/value pair") } for k, v := range m { f.Key = k @@ -177,10 +178,10 @@ type LT struct { func (f *LT) Parse(obj interface{}) error { m, ok := obj.(map[string]interface{}) if !ok { - return fmt.Errorf("LT filter must be a map") + return errors.New("LT filter must be a map") } if len(m) != 1 { - return fmt.Errorf("LT filter must contain a single key/value pair") + return errors.New("LT filter must contain a single key/value pair") } for k, v := range m { f.Key = k @@ -198,10 +199,10 @@ type LTE struct { func (f *LTE) Parse(obj interface{}) error { m, ok := obj.(map[string]interface{}) if !ok { - return fmt.Errorf("LTE filter must be a map") + return errors.New("LTE filter must be a map") } if len(m) != 1 { - return fmt.Errorf("LTE filter must contain a single key/value pair") + return errors.New("LTE filter must contain a single key/value pair") } for k, v := range m { f.Key = k @@ -219,15 +220,15 @@ type IN struct { func (f *IN) Parse(obj interface{}) error { m, ok := obj.(map[string]interface{}) if !ok { - return fmt.Errorf("IN filter must be a map") + return errors.New("IN filter must be a map") } if len(m) != 1 { - return fmt.Errorf("IN filter must contain a single key/value pair") + return errors.New("IN filter must contain a single key/value pair") } for k, v := range m { f.Key = k if f.Vals, ok = v.([]interface{}); !ok { - return fmt.Errorf("IN filter value must be an array") + return errors.New("IN filter value must be an array") } } diff --git a/state/redis/redis.go b/state/redis/redis.go index 318e4ea129..0a87f40c5c 100644 --- a/state/redis/redis.go +++ b/state/redis/redis.go @@ -189,6 +189,7 @@ func (r *StateStore) parseConnectedSlaves(res string) int { if strings.Contains(info, connectedSlavesReplicas) { parsedReplicas, _ := strconv.ParseUint(info[len(connectedSlavesReplicas):], 10, 32) + //nolint:gosec return int(parsedReplicas) } } @@ -281,7 +282,7 @@ func (r *StateStore) getJSON(ctx context.Context, req *state.GetRequest) (*state str, ok := res.(string) if !ok { - return nil, fmt.Errorf("invalid result") + return nil, errors.New("invalid result") } var entry jsonEntry @@ -481,7 +482,7 @@ func (r *StateStore) getKeyVersion(vals []interface{}) (data string, version *st } } if !seenData || !seenVersion { - return "", nil, fmt.Errorf("required hash field 'data' or 'version' was not found") + return "", nil, errors.New("required hash field 'data' or 'version' was not found") } return data, version, nil diff --git a/state/redis/redis_query.go b/state/redis/redis_query.go index 7647cb9ed0..e6cd91dcd5 100644 --- a/state/redis/redis_query.go +++ b/state/redis/redis_query.go @@ -168,7 +168,7 @@ func (q *Query) VisitIN(f *query.IN) (string, error) { return "", err } vals := make([]string, n) - for i := 0; i < n; i++ { + for i := range n { vals[i] = f.Vals[i].(string) } str := fmt.Sprintf("@%s:(%s)", alias, strings.Join(vals, "|")) @@ -179,7 +179,7 @@ func (q *Query) VisitIN(f *query.IN) (string, error) { or := &query.OR{ Filters: make([]query.Filter, n), } - for i := 0; i < n; i++ { + for i := range n { or.Filters[i] = &query.EQ{ Key: f.Key, Val: f.Vals[i], @@ -335,19 +335,19 @@ func parseQueryResponsePost28(ret any) ([]state.QueryItem, bool, error) { return nil, false, nil } - var res []state.QueryItem + var res []state.QueryItem //nolint:prealloc arr := aarr["results"].([]any) if len(arr) == 0 { return nil, false, errors.New("invalid output") } - for i := 0; i < len(arr); i++ { + for i := range arr { inner, ok := arr[i].(map[any]any) if !ok { - return nil, false, fmt.Errorf("invalid output") + return nil, false, errors.New("invalid output") } exattr, ok := inner["extra_attributes"].(map[any]any) if !ok { - return nil, false, fmt.Errorf("invalid output") + return nil, false, errors.New("invalid output") } item := state.QueryItem{ Key: inner["id"].(string), @@ -380,7 +380,7 @@ func parseQueryResponsePre28(ret any) ([]state.QueryItem, error) { // arr[2n+1][2] = "$.version" // arr[2n+1][3] = etag if len(arr)%2 != 1 { - return nil, fmt.Errorf("invalid output") + return nil, errors.New("invalid output") } var res []state.QueryItem diff --git a/state/redis/redis_query_schema.go b/state/redis/redis_query_schema.go index aec60f054b..56075a1cc3 100644 --- a/state/redis/redis_query_schema.go +++ b/state/redis/redis_query_schema.go @@ -15,6 +15,7 @@ package redis import ( "encoding/json" + "errors" "fmt" ) @@ -48,7 +49,7 @@ func parseQuerySchemas(content string) (querySchemas, error) { ret := querySchemas{} for _, schema := range schemas { if len(schema.Name) == 0 { - return nil, fmt.Errorf("empty query schema name") + return nil, errors.New("empty query schema name") } if _, ok := ret[schema.Name]; ok { return nil, fmt.Errorf("duplicate schema name %s", schema.Name) @@ -63,7 +64,7 @@ func parseQuerySchemas(content string) (querySchemas, error) { } alias := fmt.Sprintf("var%d", id) elem.keys[indx.Key] = alias - elem.schema = append(elem.schema, fmt.Sprintf("$.data.%s", indx.Key), "AS", alias, indx.Type, "SORTABLE") + elem.schema = append(elem.schema, "$.data."+indx.Key, "AS", alias, indx.Type, "SORTABLE") } ret[schema.Name] = elem } diff --git a/state/requests.go b/state/requests.go index 22dbe226df..af2c566a6f 100644 --- a/state/requests.go +++ b/state/requests.go @@ -14,7 +14,7 @@ limitations under the License. package state import ( - "fmt" + "errors" "strings" "github.com/dapr/components-contrib/state/query" @@ -77,7 +77,7 @@ type DeleteWithPrefixRequest struct { func (r *DeleteWithPrefixRequest) Validate() error { if r.Prefix == "" || r.Prefix == "||" { - return fmt.Errorf("a prefix is required for deleteWithPrefix request") + return errors.New("a prefix is required for deleteWithPrefix request") } if !strings.HasSuffix(r.Prefix, "||") { r.Prefix += "||" diff --git a/state/rethinkdb/rethinkdb_test.go b/state/rethinkdb/rethinkdb_test.go index 088878d0dc..329b1fbfcf 100644 --- a/state/rethinkdb/rethinkdb_test.go +++ b/state/rethinkdb/rethinkdb_test.go @@ -167,7 +167,7 @@ func TestRethinkDBStateStoreRongRun(t *testing.T) { } defer require.NoError(t, db.Close()) - for i := 0; i < 1000; i++ { + for i := range 1000 { testBulk(t, db, i) } } diff --git a/state/sqlite/sqlite_dbaccess.go b/state/sqlite/sqlite_dbaccess.go index cb40627ac3..9f58d192f0 100644 --- a/state/sqlite/sqlite_dbaccess.go +++ b/state/sqlite/sqlite_dbaccess.go @@ -479,7 +479,7 @@ func (a *sqliteDBAccess) doDelete(parentCtx context.Context, db querier, req *st } if req.Key == "" { - return fmt.Errorf("missing key in delete operation") + return errors.New("missing key in delete operation") } ctx, cancel := context.WithTimeout(parentCtx, a.metadata.Timeout) diff --git a/state/sqlite/sqlite_integration_test.go b/state/sqlite/sqlite_integration_test.go index 837aadcaa2..81e78fcee5 100644 --- a/state/sqlite/sqlite_integration_test.go +++ b/state/sqlite/sqlite_integration_test.go @@ -192,9 +192,9 @@ func deleteItemThatDoesNotExist(t *testing.T, s state.Store) { } func multiWithSetOnly(t *testing.T, s state.Store) { - var operations []state.TransactionalStateOperation - var setRequests []state.SetRequest - for i := 0; i < 3; i++ { + var operations []state.TransactionalStateOperation //nolint:prealloc + var setRequests []state.SetRequest //nolint:prealloc + for range 3 { req := state.SetRequest{ Key: randomKey(), Value: randomJSON(), @@ -215,9 +215,9 @@ func multiWithSetOnly(t *testing.T, s state.Store) { } func multiWithDeleteOnly(t *testing.T, s state.Store) { - var operations []state.TransactionalStateOperation - var deleteRequests []state.DeleteRequest - for i := 0; i < 3; i++ { + var operations []state.TransactionalStateOperation //nolint:prealloc + var deleteRequests []state.DeleteRequest //nolint:prealloc + for range 3 { req := state.DeleteRequest{Key: randomKey()} // Add the item to the database. @@ -241,9 +241,9 @@ func multiWithDeleteOnly(t *testing.T, s state.Store) { } func multiWithDeleteAndSet(t *testing.T, s state.Store) { - var operations []state.TransactionalStateOperation - var deleteRequests []state.DeleteRequest - for i := 0; i < 3; i++ { + var operations []state.TransactionalStateOperation //nolint:prealloc + var deleteRequests []state.DeleteRequest //nolint:prealloc + for range 3 { req := state.DeleteRequest{Key: randomKey()} // Add the item to the database. @@ -257,8 +257,8 @@ func multiWithDeleteAndSet(t *testing.T, s state.Store) { } // Create the set requests. - var setRequests []state.SetRequest - for i := 0; i < 3; i++ { + var setRequests []state.SetRequest //nolint:prealloc + for range 3 { req := state.SetRequest{ Key: randomKey(), Value: randomJSON(), diff --git a/state/sqlserver/metadata.go b/state/sqlserver/metadata.go index 98efdb63fc..eeb2fdda4c 100644 --- a/state/sqlserver/metadata.go +++ b/state/sqlserver/metadata.go @@ -77,10 +77,10 @@ func (m *sqlServerMetadata) Parse(meta map[string]string) error { // Validate and sanitize more values if !sqlserverAuth.IsValidSQLName(m.TableName) { - return fmt.Errorf("invalid table name, accepted characters are (A-Z, a-z, 0-9, _)") + return errors.New("invalid table name, accepted characters are (A-Z, a-z, 0-9, _)") } if !sqlserverAuth.IsValidSQLName(m.MetadataTableName) { - return fmt.Errorf("invalid metadata table name, accepted characters are (A-Z, a-z, 0-9, _)") + return errors.New("invalid metadata table name, accepted characters are (A-Z, a-z, 0-9, _)") } err = m.setKeyType() @@ -174,15 +174,15 @@ func (m *sqlServerMetadata) validateIndexedProperties(indexedProperties []Indexe } if !sqlserverAuth.IsValidSQLName(p.ColumnName) { - return fmt.Errorf("invalid indexed property column name, accepted characters are (A-Z, a-z, 0-9, _)") + return errors.New("invalid indexed property column name, accepted characters are (A-Z, a-z, 0-9, _)") } if !isValidIndexedPropertyName(p.Property) { - return fmt.Errorf("invalid indexed property name, accepted characters are (A-Z, a-z, 0-9, _, ., [, ])") + return errors.New("invalid indexed property name, accepted characters are (A-Z, a-z, 0-9, _, ., [, ])") } if !isValidIndexedPropertyType(p.Type) { - return fmt.Errorf("invalid indexed property type, accepted characters are (A-Z, a-z, 0-9, _, (, ))") + return errors.New("invalid indexed property type, accepted characters are (A-Z, a-z, 0-9, _, (, ))") } } diff --git a/state/sqlserver/migration.go b/state/sqlserver/migration.go index 3f60ca3578..38e14d0e1a 100644 --- a/state/sqlserver/migration.go +++ b/state/sqlserver/migration.go @@ -46,7 +46,7 @@ func newMigration(metadata *sqlServerMetadata) migrator { func (m *migration) newMigrationResult() migrationResult { r := migrationResult{ itemRefTableTypeName: fmt.Sprintf("[%s].%s_Table", m.metadata.SchemaName, m.metadata.TableName), - upsertProcName: fmt.Sprintf("sp_Upsert_v5_%s", m.metadata.TableName), + upsertProcName: "sp_Upsert_v5_" + m.metadata.TableName, getCommand: fmt.Sprintf("SELECT [Data], [RowVersion], [ExpireDate] FROM [%s].[%s] WHERE [Key] = @Key AND ([ExpireDate] IS NULL OR [ExpireDate] > GETDATE())", m.metadata.SchemaName, m.metadata.TableName), deleteWithETagCommand: fmt.Sprintf(`DELETE [%s].[%s] WHERE [Key]=@Key AND [RowVersion]=@RowVersion`, m.metadata.SchemaName, m.metadata.TableName), deleteWithoutETagCommand: fmt.Sprintf(`DELETE [%s].[%s] WHERE [Key]=@Key`, m.metadata.SchemaName, m.metadata.TableName), diff --git a/state/sqlserver/sqlserver_integration_test.go b/state/sqlserver/sqlserver_integration_test.go index 44becc0bf8..a4671ad744 100644 --- a/state/sqlserver/sqlserver_integration_test.go +++ b/state/sqlserver/sqlserver_integration_test.go @@ -81,7 +81,7 @@ func TestIntegrationCases(t *testing.T) { // Run concurrent set tests 10 times const executions = 10 - for i := 0; i < executions; i++ { + for i := range executions { t.Run(fmt.Sprintf("Concurrent sets, try #%d", i+1), testConcurrentSets) } } @@ -90,7 +90,7 @@ func getUniqueDBSchema(t *testing.T) string { b := make([]byte, 4) _, err := io.ReadFull(rand.Reader, b) require.NoError(t, err) - return fmt.Sprintf("v%s", hex.EncodeToString(b)) + return "v" + hex.EncodeToString(b) } func createMetadata(schema string, kt KeyType, indexedProperties string) state.Metadata { @@ -548,7 +548,7 @@ func testConcurrentSets(t *testing.T) { start := make(chan bool, parallelism) totalErrors := int32(0) totalSucceeds := int32(0) - for i := 0; i < parallelism; i++ { + for range parallelism { wc.Add(1) go func(id, etag string, start <-chan bool, wc *sync.WaitGroup, store *SQLServer) { <-start diff --git a/state/zookeeper/zk_test.go b/state/zookeeper/zk_test.go index ee74668929..2598a82724 100644 --- a/state/zookeeper/zk_test.go +++ b/state/zookeeper/zk_test.go @@ -15,7 +15,6 @@ package zookeeper import ( "context" - "fmt" "testing" "time" @@ -38,7 +37,7 @@ func TestNewConfig(t *testing.T) { "sessionTimeout": "5s", } cp, err := newConfig(properties) - require.NoError(t, err, fmt.Sprintf("Unexpected error: %v", err)) + require.NoError(t, err, "Unexpected error: %v", err) assert.NotNil(t, cp, "failed to respond to missing data field") assert.Equal(t, []string{ "127.0.0.1:3000", "127.0.0.1:3001", "127.0.0.1:3002", diff --git a/tests/conformance/pubsub/pubsub.go b/tests/conformance/pubsub/pubsub.go index 55f54ed968..84fb7cdf90 100644 --- a/tests/conformance/pubsub/pubsub.go +++ b/tests/conformance/pubsub/pubsub.go @@ -508,7 +508,7 @@ func ConformanceTests(t *testing.T, props map[string]string, ps pubsub.PubSub, c close(allSentCh) }() - for i := 0; i < 3; i++ { + for i := range 3 { t.Logf("Starting iteration %d", i) switch i { case 1: // On iteration 1, close the first subscriber diff --git a/tests/conformance/state/state.go b/tests/conformance/state/state.go index ef9dd51828..25de650cf9 100644 --- a/tests/conformance/state/state.go +++ b/tests/conformance/state/state.go @@ -101,139 +101,139 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St scenarios := []scenario{ { - key: fmt.Sprintf("%s-int", key), + key: key + "-int", value: 123, }, { - key: fmt.Sprintf("%s-bool", key), + key: key + "-bool", value: true, }, { - key: fmt.Sprintf("%s-bytes", key), + key: key + "-bytes", value: []byte{0x1}, }, { - key: fmt.Sprintf("%s-string-with-json", key), + key: key + "-string-with-json", value: `{"a":"b"}`, }, { - key: fmt.Sprintf("%s-string", key), + key: key + "-string", value: "hello world", }, { - key: fmt.Sprintf("%s-empty-string", key), + key: key + "-empty-string", value: "", }, { - key: fmt.Sprintf("%s-struct", key), - value: ValueType{Message: fmt.Sprintf("test%s", key)}, + key: key + "-struct", + value: ValueType{Message: "test" + key}, contentType: contenttype.JSONContentType, }, { - key: fmt.Sprintf("%s-struct-operations", key), + key: key + "-struct-operations", value: StructType{Product: struct { Value int `json:"value"` - }{Value: 15}, Status: "ACTIVE", Message: fmt.Sprintf("%smessage", key)}, + }{Value: 15}, Status: "ACTIVE", Message: key + "message"}, contentType: contenttype.JSONContentType, }, { - key: fmt.Sprintf("%s-struct-operations-inactive", key), + key: key + "-struct-operations-inactive", value: StructType{Product: struct { Value int `json:"value"` - }{Value: 12}, Status: "INACTIVE", Message: fmt.Sprintf("%smessage", key)}, + }{Value: 12}, Status: "INACTIVE", Message: key + "message"}, contentType: contenttype.JSONContentType, }, { - key: fmt.Sprintf("%s-struct-2", key), - value: ValueType{Message: fmt.Sprintf("%stest", key)}, + key: key + "-struct-2", + value: ValueType{Message: key + "test"}, contentType: contenttype.JSONContentType, }, { - key: fmt.Sprintf("%s-struct-with-int", key), + key: key + "-struct-with-int", value: intValueType{Message: 42}, contentType: contenttype.JSONContentType, }, { - key: fmt.Sprintf("%s-to-be-deleted", key), + key: key + "-to-be-deleted", value: "to be deleted", toBeDeleted: true, }, { - key: fmt.Sprintf("%s-bulk-int", key), + key: key + "-bulk-int", value: 123, bulkOnly: true, }, { - key: fmt.Sprintf("%s-bulk-bool", key), + key: key + "-bulk-bool", value: true, bulkOnly: true, }, { - key: fmt.Sprintf("%s-bulk-bytes", key), + key: key + "-bulk-bytes", value: []byte{0x1}, bulkOnly: true, }, { - key: fmt.Sprintf("%s-bulk-string", key), + key: key + "-bulk-string", value: "hello world", bulkOnly: true, }, { - key: fmt.Sprintf("%s-bulk-struct", key), + key: key + "-bulk-struct", value: ValueType{Message: "test"}, bulkOnly: true, }, { - key: fmt.Sprintf("%s-bulk-to-be-deleted", key), + key: key + "-bulk-to-be-deleted", value: "to be deleted", toBeDeleted: true, bulkOnly: true, }, { - key: fmt.Sprintf("%s-bulk-to-be-deleted-too", key), + key: key + "-bulk-to-be-deleted-too", value: "to be deleted too", toBeDeleted: true, bulkOnly: true, }, { - key: fmt.Sprintf("%s-trx-int", key), + key: key + "-trx-int", value: 123, transactionOnly: true, transactionGroup: 1, }, { - key: fmt.Sprintf("%s-trx-bool", key), + key: key + "-trx-bool", value: true, transactionOnly: true, transactionGroup: 1, }, { - key: fmt.Sprintf("%s-trx-bytes", key), + key: key + "-trx-bytes", value: []byte{0x1}, transactionOnly: true, transactionGroup: 1, }, { - key: fmt.Sprintf("%s-trx-string", key), + key: key + "-trx-string", value: "hello world", transactionOnly: true, transactionGroup: 1, }, { - key: fmt.Sprintf("%s-trx-struct", key), + key: key + "-trx-struct", value: ValueType{Message: "test"}, transactionOnly: true, transactionGroup: 2, }, { - key: fmt.Sprintf("%s-trx-to-be-deleted", key), + key: key + "-trx-to-be-deleted", value: "to be deleted", toBeDeleted: true, transactionOnly: true, transactionGroup: 1, }, { - key: fmt.Sprintf("%s-trx-to-be-deleted-too", key), + key: key + "-trx-to-be-deleted-too", value: "to be deleted too", toBeDeleted: true, transactionOnly: true, @@ -259,7 +259,7 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St `, results: []state.QueryItem{ { - Key: fmt.Sprintf("%s-struct", key), + Key: key + "-struct", Data: []byte(fmt.Sprintf(`{"message":"test%s"}`, key)), }, }, @@ -287,7 +287,7 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St `, results: []state.QueryItem{ { - Key: fmt.Sprintf("%s-struct-operations", key), + Key: key + "-struct-operations", Data: []byte(fmt.Sprintf(`{"product":{"value":15}, "status":"ACTIVE","message":"%smessage"}`, key)), }, }, @@ -329,7 +329,7 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St `, results: []state.QueryItem{ { - Key: fmt.Sprintf("%s-struct-operations-inactive", key), + Key: key + "-struct-operations-inactive", Data: []byte(fmt.Sprintf(`{"product":{"value":12}, "status":"INACTIVE","message":"%smessage"}`, key)), }, }, @@ -354,11 +354,11 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St // Return 2 item from 2 different partitionKey (-struct and -struct-2), for default the partitionKey is equals to key results: []state.QueryItem{ { - Key: fmt.Sprintf("%s-struct", key), + Key: key + "-struct", Data: []byte(fmt.Sprintf(`{"message":"test%s"}`, key)), }, { - Key: fmt.Sprintf("%s-struct-2", key), + Key: key + "-struct-2", Data: []byte(fmt.Sprintf(`{"message":"%stest"}`, key)), }, }, @@ -381,13 +381,13 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St } `, metadata: map[string]string{ - "partitionKey": fmt.Sprintf("%s-struct-2", key), + "partitionKey": key + "-struct-2", }, partitionOnly: true, // The same query from previous test but return only item having the same partitionKey value (%s-struct-2) given in the metadata results: []state.QueryItem{ { - Key: fmt.Sprintf("%s-struct-2", key), + Key: key + "-struct-2", Data: []byte(fmt.Sprintf(`{"message":"%stest"}`, key)), }, }, @@ -841,7 +841,7 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St }, state.BulkGetOpts{}) require.NoError(t, err) require.Len(t, bulkRes, 3) - for i := 0; i < 3; i++ { + for i := range 3 { require.NotNil(t, bulkRes[i].ETag) require.NotEmpty(t, *bulkRes[i].ETag) assertDataEquals(t, firstValue, bulkRes[i].Data) @@ -931,7 +931,7 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St }, state.BulkGetOpts{}) require.NoError(t, err) require.Len(t, bulkRes, 2) - for i := 0; i < 2; i++ { + for i := range 2 { require.NotNil(t, bulkRes[i].ETag) require.NotEmpty(t, *bulkRes[i].ETag) assertDataEquals(t, thirdValue, bulkRes[i].Data) @@ -1015,7 +1015,7 @@ func ConformanceTests(t *testing.T, props map[string]string, statestore state.St require.NoError(t, err) require.Len(t, bulkRes, 2) foundKeys := []string{} - for i := 0; i < 2; i++ { + for i := range 2 { require.Empty(t, bulkRes[i].Data) require.Empty(t, bulkRes[i].ETag) foundKeys = append(foundKeys, bulkRes[i].Key) diff --git a/tests/utils/configupdater/postgres/postgres.go b/tests/utils/configupdater/postgres/postgres.go index ba487a5cf1..ed37a66e0c 100644 --- a/tests/utils/configupdater/postgres/postgres.go +++ b/tests/utils/configupdater/postgres/postgres.go @@ -2,6 +2,7 @@ package postgres import ( "context" + "errors" "fmt" "strconv" "strings" @@ -105,7 +106,7 @@ func (r *ConfigUpdater) Init(props map[string]string) error { if tbl, ok := props["table"]; ok && tbl != "" { r.configTable = tbl } else { - return fmt.Errorf("missing postgreSQL configuration table name") + return errors.New("missing postgreSQL configuration table name") } config, err := md.GetPgxPoolConfig() @@ -134,7 +135,7 @@ func buildAddQuery(items map[string]*configuration.Item, configTable string) (st paramWildcard := make([]string, 0, len(items)) params := make([]interface{}, 0, 4*len(items)) if len(items) == 0 { - return query, params, fmt.Errorf("empty list of items") + return query, params, errors.New("empty list of items") } var queryBuilder strings.Builder queryBuilder.WriteString("INSERT INTO " + configTable + " (KEY, VALUE, VERSION, METADATA) VALUES ") @@ -164,7 +165,7 @@ func (r *ConfigUpdater) AddKey(items map[string]*configuration.Item) error { func (r *ConfigUpdater) UpdateKey(items map[string]*configuration.Item) error { if len(items) == 0 { - return fmt.Errorf("empty list of items") + return errors.New("empty list of items") } for key, item := range items { var params []interface{} @@ -180,7 +181,7 @@ func (r *ConfigUpdater) UpdateKey(items map[string]*configuration.Item) error { func (r *ConfigUpdater) DeleteKey(keys []string) error { if len(keys) == 0 { - return fmt.Errorf("empty list of items") + return errors.New("empty list of items") } for _, key := range keys { var params []interface{}