diff --git a/cmd/transport-core-tool/main.go b/cmd/transport-core-tool/main.go index 2fdcfd1..7787f72 100644 --- a/cmd/transport-core-tool/main.go +++ b/cmd/transport-core-tool/main.go @@ -32,8 +32,7 @@ func main() { if _, err := parser.Parse(); err != nil { if flagsErr, ok := err.(*flags.Error); ok && flagsErr.Type == flags.ErrHelp { // nolint:errorlint os.Exit(0) - } else { - os.Exit(1) } + os.Exit(1) } } diff --git a/core/config/config.go b/core/config/config.go index ea3ee72..d236003 100644 --- a/core/config/config.go +++ b/core/config/config.go @@ -1,7 +1,7 @@ package config import ( - "io/ioutil" + "os" "path/filepath" "time" @@ -132,7 +132,7 @@ func (c *Config) GetConfigData(path string) []byte { panic(err) } - source, err := ioutil.ReadFile(path) + source, err := os.ReadFile(path) if err != nil { panic(err) } diff --git a/core/config/config_test.go b/core/config/config_test.go index 2fa569c..8498ae0 100644 --- a/core/config/config_test.go +++ b/core/config/config_test.go @@ -1,7 +1,6 @@ package config import ( - "io/ioutil" "os" "path" "testing" @@ -54,7 +53,7 @@ config_aws: bucket: bucket folder_name: folder content_type: image/jpeg`) - err := ioutil.WriteFile(testConfigFile, c.data, os.ModePerm) + err := os.WriteFile(testConfigFile, c.data, os.ModePerm) require.Nil(c.T(), err) c.config = NewConfig(testConfigFile) diff --git a/core/db/migration_generator.go b/core/db/migration_generator.go index b078ad0..79b9967 100644 --- a/core/db/migration_generator.go +++ b/core/db/migration_generator.go @@ -51,7 +51,7 @@ func (x *NewMigrationCommand) FileExists(filename string) bool { } // Execute migration generator command. -func (x *NewMigrationCommand) Execute(args []string) error { +func (x *NewMigrationCommand) Execute(_ []string) error { tpl, err := template.New("migration").Parse(migrationTemplate) if err != nil { return fmt.Errorf("fatal: cannot parse base migration template: %w", err) diff --git a/core/db/migration_generator_test.go b/core/db/migration_generator_test.go index 1d86ac5..03723ac 100644 --- a/core/db/migration_generator_test.go +++ b/core/db/migration_generator_test.go @@ -2,7 +2,6 @@ package db import ( "fmt" - "io/ioutil" "log" "math/rand" "os" @@ -36,7 +35,7 @@ func (s *MigrationGeneratorSuite) Test_FileExists() { func (s *MigrationGeneratorSuite) Test_Execute() { found := false assert.NoError(s.T(), s.command.Execute([]string{})) - files, err := ioutil.ReadDir(s.command.Directory) + files, err := os.ReadDir(s.command.Directory) if err != nil { log.Fatal(err) } diff --git a/core/db/models/user.go b/core/db/models/user.go index 5a7b4b0..be82382 100644 --- a/core/db/models/user.go +++ b/core/db/models/user.go @@ -14,11 +14,14 @@ type User struct { // TableName will return table name for User // It will not work if User is not embedded, but mapped as another type -// type MyUser User // will not work +// +// type MyUser User // will not work +// // but -// type MyUser struct { // will work -// User -// } +// +// type MyUser struct { // will work +// User +// } func (User) TableName() string { return "mg_user" } diff --git a/core/doc.go b/core/doc.go index b1916a4..4bbe25e 100644 --- a/core/doc.go +++ b/core/doc.go @@ -2,6 +2,7 @@ Package core provides different functions like error-reporting, logging, localization, etc. to make it easier to create transports. Usage: + package main import ( @@ -36,14 +37,19 @@ Usage: } } -Resource embedding +# Resource embedding packr can be used to provide resource embedding, see: + https://github.com/gobuffalo/packr/tree/master/v2 + In order to use packr you must follow instruction, and provide boxes with templates, translations and assets to library. You can find instruction here: + https://github.com/gobuffalo/packr/tree/master/v2#library-installation + Example of usage: + package main import ( @@ -104,10 +110,12 @@ Example of usage: } } -Migration generator +# Migration generator This library contains helper tool for transports. You can install it via go: + $ go get -u github.com/retailcrm/mg-transport-core/cmd/transport-core-tool + Currently, it only can generate new migrations for your transport. Copyright (c) 2019 RetailDriver LLC. Usage of this source code is governed by a MIT license. diff --git a/core/domains.go b/core/domains.go index 2b14d63..46e1529 100644 --- a/core/domains.go +++ b/core/domains.go @@ -2,7 +2,7 @@ package core import ( "encoding/json" - "io/ioutil" + "io" "net/http" ) @@ -40,7 +40,7 @@ func getDomainsByStore(store string) []Domain { return nil } - respBody, readErr := ioutil.ReadAll(resp.Body) + respBody, readErr := io.ReadAll(resp.Body) if readErr != nil { return nil diff --git a/core/engine.go b/core/engine.go index 6887ad4..72dfd48 100644 --- a/core/engine.go +++ b/core/engine.go @@ -7,6 +7,7 @@ import ( "io/fs" "net/http" "sync" + "time" "github.com/blacked/go-zabbix" "github.com/getsentry/sentry-go" @@ -26,12 +27,14 @@ import ( "github.com/retailcrm/mg-transport-core/v2/core/logger" ) +const DefaultHTTPClientTimeout time.Duration = 30 + var boolTrue = true // DefaultHTTPClientConfig is a default config for HTTP client. It will be used by Engine for building HTTP client // if HTTP client config is not present in the configuration. var DefaultHTTPClientConfig = &config.HTTPClientConfig{ - Timeout: 30, + Timeout: DefaultHTTPClientTimeout, SSLVerification: &boolTrue, } @@ -279,10 +282,9 @@ func (e *Engine) BuildHTTPClient(certs *x509.CertPool, replaceDefault ...bool) * if err != nil { panic(err) - } else { - e.httpClient = client } + e.httpClient = client return e } diff --git a/core/engine_test.go b/core/engine_test.go index 2d89d76..ab9bbd2 100644 --- a/core/engine_test.go +++ b/core/engine_test.go @@ -6,7 +6,7 @@ import ( "database/sql" "fmt" "html/template" - "io/ioutil" + "io" "net/http" "net/url" "os" @@ -365,7 +365,7 @@ func (e *EngineTest) Test_GetCSRFToken() { URL: &url.URL{ RawQuery: "", }, - Body: ioutil.NopCloser(bytes.NewReader([]byte{})), + Body: io.NopCloser(bytes.NewReader([]byte{})), Header: http.Header{"X-CSRF-Token": []string{"token"}}, }} c.Set("csrf_token", "token") diff --git a/core/healthcheck/counter.go b/core/healthcheck/counter.go index e8e1ede..86ee3a7 100644 --- a/core/healthcheck/counter.go +++ b/core/healthcheck/counter.go @@ -10,7 +10,7 @@ import ( const DefaultResetPeriod = time.Minute * 15 // AtomicCounter is a default Counter implementation. -// It uses atomics under the hood (hence the name) and can be configured with custom reset timeout and +// It uses atomics under the hood (hence the name) and can be configured with custom reset timeout and. type AtomicCounter struct { name atomic.String msg atomic.String diff --git a/core/healthcheck/iface.go b/core/healthcheck/iface.go index cf88d2d..c9c2486 100644 --- a/core/healthcheck/iface.go +++ b/core/healthcheck/iface.go @@ -1,7 +1,7 @@ package healthcheck var ( - // compile-time checks to ensure that implementations are compatible with the interface + // compile-time checks to ensure that implementations are compatible with the interface. _ = Storage(&SyncMapStorage{}) _ = Counter(&AtomicCounter{}) _ = Processor(CounterProcessor{}) diff --git a/core/job_manager_test.go b/core/job_manager_test.go index 40ed2a6..ac3ce2a 100644 --- a/core/job_manager_test.go +++ b/core/job_manager_test.go @@ -44,7 +44,7 @@ type callbackLogger struct { fn callbackLoggerFunc } -func (n *callbackLogger) Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry { +func (n *callbackLogger) Check(_ zapcore.Level, _ string) *zapcore.CheckedEntry { return &zapcore.CheckedEntry{} } @@ -75,7 +75,7 @@ func (n *callbackLogger) cloneWithFields(fields []zap.Field) *callbackLogger { cl.fields = fields return cl } - cl.fields = append(existing, fields...) + cl.fields = append(existing, fields...) // nolint:gocritic return cl } @@ -91,19 +91,19 @@ func (n *callbackLogger) WithLazy(args ...zap.Field) logger.Logger { return n.cloneWithFields(args) } -func (n *callbackLogger) WithGroup(name string) logger.Logger { +func (n *callbackLogger) WithGroup(_ string) logger.Logger { return n } -func (n *callbackLogger) ForHandler(handler any) logger.Logger { +func (n *callbackLogger) ForHandler(_ any) logger.Logger { return n } -func (n *callbackLogger) ForConnection(conn any) logger.Logger { +func (n *callbackLogger) ForConnection(_ any) logger.Logger { return n } -func (n *callbackLogger) ForAccount(acc any) logger.Logger { +func (n *callbackLogger) ForAccount(_ any) logger.Logger { return n } @@ -288,11 +288,11 @@ func (t *JobTest) oncePanicJob() { } func (t *JobTest) regularJob() { - rand.Seed(time.Now().UnixNano()) + r := rand.New(rand.NewSource(time.Now().UnixNano())) // nolint:gosec t.job = &Job{ Command: func(log logger.Logger) error { t.executedChan <- true - t.randomNumber <- rand.Int() // nolint:gosec + t.randomNumber <- r.Int() // nolint:gosec return nil }, ErrorHandler: t.testErrorHandler(), @@ -303,7 +303,6 @@ func (t *JobTest) regularJob() { } func (t *JobTest) regularSyncJob() { - rand.Seed(time.Now().UnixNano()) t.job = &Job{ Command: func(log logger.Logger) error { t.syncBool = true diff --git a/core/localizer.go b/core/localizer.go index 5dbfcf7..355d86d 100644 --- a/core/localizer.go +++ b/core/localizer.go @@ -3,7 +3,7 @@ package core import ( "html/template" "io/fs" - "io/ioutil" + "os" "path" "sync" @@ -90,7 +90,8 @@ type CloneableLocalizer interface { // NewLocalizer returns localizer instance with specified parameters. // Usage: -// NewLocalizer(language.English, DefaultLocalizerMatcher(), "translations") +// +// NewLocalizer(language.English, DefaultLocalizerMatcher(), "translations") func NewLocalizer(locale language.Tag, matcher language.Matcher, translationsPath string) LocalizerInterface { localizer := &Localizer{ i18nStorage: &sync.Map{}, @@ -106,7 +107,9 @@ func NewLocalizer(locale language.Tag, matcher language.Matcher, translationsPat // NewLocalizerFS returns localizer instance with specified parameters. // Usage: -// NewLocalizerFS(language.English, DefaultLocalizerMatcher(), translationsFS) +// +// NewLocalizerFS(language.English, DefaultLocalizerMatcher(), translationsFS) +// // TODO This code should be covered with tests. func NewLocalizerFS( locale language.Tag, matcher language.Matcher, translationsFS fs.FS, @@ -161,9 +164,10 @@ func (l *Localizer) Clone() CloneableLocalizer { // Because of that all Localizer instances from this middleware will share *same* mutex. This mutex is used to wrap // i18n.Bundle methods (those aren't goroutine-safe to use). // Usage: -// engine := gin.New() -// localizer := NewLocalizer("en", DefaultLocalizerMatcher(), "translations") -// engine.Use(localizer.LocalizationMiddleware()) +// +// engine := gin.New() +// localizer := NewLocalizer("en", DefaultLocalizerMatcher(), "translations") +// engine.Use(localizer.LocalizationMiddleware()) func (l *Localizer) LocalizationMiddleware() gin.HandlerFunc { return func(c *gin.Context) { clone := l.Clone().(LocaleControls) @@ -174,15 +178,21 @@ func (l *Localizer) LocalizationMiddleware() gin.HandlerFunc { // LocalizationFuncMap returns template.FuncMap (html template is used) with one method - trans // Usage in code: -// engine := gin.New() -// engine.FuncMap = localizer.LocalizationFuncMap() +// +// engine := gin.New() +// engine.FuncMap = localizer.LocalizationFuncMap() +// // or (with multitemplate) -// renderer := multitemplate.NewRenderer() -// funcMap := localizer.LocalizationFuncMap() -// renderer.AddFromFilesFuncs("index", funcMap, "template/index.html") +// +// renderer := multitemplate.NewRenderer() +// funcMap := localizer.LocalizationFuncMap() +// renderer.AddFromFilesFuncs("index", funcMap, "template/index.html") +// // funcMap must be passed for every .AddFromFilesFuncs call // Usage in templates: -//
{{"need_login_msg" | trans}} +// +//
{{"need_login_msg" | trans}}
+//
// You can borrow FuncMap from this method and add your functions to it.
func (l *Localizer) LocalizationFuncMap() template.FuncMap {
return template.FuncMap{
@@ -196,7 +206,7 @@ func (l *Localizer) LocalizationFuncMap() template.FuncMap {
parts = append(parts, "")
}
- partsMap := make(map[string]interface{}, len(parts)/2)
+ partsMap := make(map[string]interface{}, len(parts)/2) // nolint:gomnd
for i := 0; i < len(parts)-1; i += 2 {
partsMap[parts[i]] = parts[i+1]
@@ -239,7 +249,7 @@ func (l *Localizer) loadTranslationsToBundle(i18nBundle *i18n.Bundle) {
// LoadTranslations will load all translation files from translations directory.
func (l *Localizer) loadFromDirectory(i18nBundle *i18n.Bundle) error {
- files, err := ioutil.ReadDir(l.TranslationsPath)
+ files, err := os.ReadDir(l.TranslationsPath)
if err != nil {
return err
}
diff --git a/core/localizer_test.go b/core/localizer_test.go
index 57c5cc8..35050fa 100644
--- a/core/localizer_test.go
+++ b/core/localizer_test.go
@@ -1,7 +1,6 @@
package core
import (
- "io/ioutil"
"math/rand"
"net/http"
"net/http/httptest"
@@ -40,7 +39,7 @@ func createTestLangFiles(t *testing.T) {
}
if _, err := os.Stat(fileName); err != nil && os.IsNotExist(err) {
- err = ioutil.WriteFile(fileName, data, os.ModePerm)
+ err = os.WriteFile(fileName, data, os.ModePerm)
require.Nil(t, err)
}
}
@@ -103,7 +102,7 @@ func (l *LocalizerTest) Test_LocalizationMiddleware_Context() {
func (l *LocalizerTest) Test_LocalizationMiddleware_Httptest() {
var wg sync.WaitGroup
- rand.Seed(time.Now().UnixNano())
+ r := rand.New(rand.NewSource(time.Now().UnixNano())) // nolint:gosec
l.localizer.Preload(DefaultLanguages)
langMsgMap := map[language.Tag]string{
language.English: "Test message",
@@ -122,7 +121,7 @@ func (l *LocalizerTest) Test_LocalizationMiddleware_Httptest() {
wg.Add(1)
go func(m map[language.Tag]string, wg *sync.WaitGroup) {
var tag language.Tag
- switch rand.Intn(3-1) + 1 { // nolint:gosec
+ switch r.Intn(3-1) + 1 { // nolint:gosec
case 1:
tag = language.English
case 2:
diff --git a/core/logger/api_client_adapter.go b/core/logger/api_client_adapter.go
index 1cb7d4c..8d88117 100644
--- a/core/logger/api_client_adapter.go
+++ b/core/logger/api_client_adapter.go
@@ -2,6 +2,7 @@ package logger
import (
"fmt"
+
"go.uber.org/zap"
retailcrm "github.com/retailcrm/api-client-go/v2"
diff --git a/core/logger/api_client_adapter_test.go b/core/logger/api_client_adapter_test.go
index eb2e6ca..4a4d6bc 100644
--- a/core/logger/api_client_adapter_test.go
+++ b/core/logger/api_client_adapter_test.go
@@ -1,12 +1,13 @@
package logger
import (
+ "net/http"
+ "testing"
+
"github.com/h2non/gock"
retailcrm "github.com/retailcrm/api-client-go/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "net/http"
- "testing"
)
func TestAPIClientAdapter(t *testing.T) {
diff --git a/core/logger/attrs.go b/core/logger/attrs.go
index 73de78d..06ec6e0 100644
--- a/core/logger/attrs.go
+++ b/core/logger/attrs.go
@@ -2,10 +2,11 @@ package logger
import (
"fmt"
- json "github.com/goccy/go-json"
"io"
"net/http"
+ json "github.com/goccy/go-json"
+
"go.uber.org/zap"
)
diff --git a/core/logger/attrs_test.go b/core/logger/attrs_test.go
index c3fdcf5..2bb519d 100644
--- a/core/logger/attrs_test.go
+++ b/core/logger/attrs_test.go
@@ -4,11 +4,12 @@ import (
"bytes"
"errors"
"fmt"
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/mock"
"io"
"net/http"
"testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/mock"
)
func TestErr(t *testing.T) {
diff --git a/core/logger/buffer_logger_test.go b/core/logger/buffer_logger_test.go
index a36e5db..0c6115e 100644
--- a/core/logger/buffer_logger_test.go
+++ b/core/logger/buffer_logger_test.go
@@ -4,11 +4,12 @@ import (
"bufio"
"bytes"
"encoding/json"
- "github.com/guregu/null/v5"
"io"
"os"
"sync"
+ "github.com/guregu/null/v5"
+
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
diff --git a/core/logger/default.go b/core/logger/default.go
index 8ec6fc7..017b4b5 100644
--- a/core/logger/default.go
+++ b/core/logger/default.go
@@ -27,7 +27,8 @@ type Logger interface {
Warn(msg string, fields ...zap.Field)
// Error logs an error-level message with the given fields.
Error(msg string, fields ...zap.Field)
- // DPanic logs a debug-panic-level message with the given fields and panics if the logger's panic level is set to a non-zero value.
+ // DPanic logs a debug-panic-level message with the given fields and panics
+ // if the logger's panic level is set to a non-zero value.
DPanic(msg string, fields ...zap.Field)
// Panic logs a panic-level message with the given fields and panics immediately.
Panic(msg string, fields ...zap.Field)
diff --git a/core/logger/default_test.go b/core/logger/default_test.go
index acd4f47..7301568 100644
--- a/core/logger/default_test.go
+++ b/core/logger/default_test.go
@@ -1,11 +1,12 @@
package logger
import (
+ "testing"
+
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"go.uber.org/zap"
- "testing"
)
type TestDefaultSuite struct {
diff --git a/core/logger/gin_test.go b/core/logger/gin_test.go
index 3c04067..3cf6cf7 100644
--- a/core/logger/gin_test.go
+++ b/core/logger/gin_test.go
@@ -1,12 +1,13 @@
package logger
import (
- "github.com/gin-gonic/gin"
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
"net/http"
"net/http/httptest"
"testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
)
func TestGinMiddleware(t *testing.T) {
diff --git a/core/logger/json_with_context_encoder.go b/core/logger/json_with_context_encoder.go
index cb377e7..cc3a8a1 100644
--- a/core/logger/json_with_context_encoder.go
+++ b/core/logger/json_with_context_encoder.go
@@ -18,19 +18,21 @@
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
+// nolint
package logger
import (
"encoding/base64"
"encoding/json"
"fmt"
- "go.uber.org/zap"
- "go.uber.org/zap/zapcore"
"io"
"math"
"time"
"unicode/utf8"
+ "go.uber.org/zap"
+ "go.uber.org/zap/zapcore"
+
"go.uber.org/zap/buffer"
)
diff --git a/core/logger/mg_transport_client_adapter.go b/core/logger/mg_transport_client_adapter.go
index 345b5b3..0b8569b 100644
--- a/core/logger/mg_transport_client_adapter.go
+++ b/core/logger/mg_transport_client_adapter.go
@@ -2,8 +2,10 @@ package logger
import (
"fmt"
- v1 "github.com/retailcrm/mg-transport-api-client-go/v1"
+
"go.uber.org/zap"
+
+ v1 "github.com/retailcrm/mg-transport-api-client-go/v1"
)
const (
@@ -36,10 +38,10 @@ func (m *mgTransportClientAdapter) Debugf(msg string, args ...interface{}) {
if len(args) > 1 {
uri = fmt.Sprint(args[1])
}
- if len(args) > 2 {
+ if len(args) > 2 { // nolint:gomnd
token = fmt.Sprint(args[2])
}
- if len(args) > 3 {
+ if len(args) > 3 { // nolint:gomnd
body = args[3]
}
m.log.Debug("MG TRANSPORT API Request",
diff --git a/core/logger/mg_transport_client_adapter_test.go b/core/logger/mg_transport_client_adapter_test.go
index e88aec0..f3ece35 100644
--- a/core/logger/mg_transport_client_adapter_test.go
+++ b/core/logger/mg_transport_client_adapter_test.go
@@ -1,12 +1,14 @@
package logger
import (
- "github.com/h2non/gock"
- v1 "github.com/retailcrm/mg-transport-api-client-go/v1"
- "github.com/stretchr/testify/assert"
- "github.com/stretchr/testify/require"
"net/http"
"testing"
+
+ "github.com/h2non/gock"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ v1 "github.com/retailcrm/mg-transport-api-client-go/v1"
)
func TestMGTransportClientAdapter(t *testing.T) {
diff --git a/core/logger/nil.go b/core/logger/nil.go
index f6d0f95..bd348ed 100644
--- a/core/logger/nil.go
+++ b/core/logger/nil.go
@@ -13,11 +13,11 @@ func NewNil() Logger {
return &Nil{}
}
-func (l *Nil) With(fields ...zap.Field) Logger {
+func (l *Nil) With(_ ...zap.Field) Logger {
return l
}
-func (l *Nil) WithLazy(fields ...zap.Field) Logger {
+func (l *Nil) WithLazy(_ ...zap.Field) Logger {
return l
}
@@ -25,35 +25,35 @@ func (l *Nil) Level() zapcore.Level {
return zapcore.DebugLevel
}
-func (l *Nil) Check(lvl zapcore.Level, msg string) *zapcore.CheckedEntry {
+func (l *Nil) Check(_ zapcore.Level, _ string) *zapcore.CheckedEntry {
return &zapcore.CheckedEntry{}
}
-func (l *Nil) Log(lvl zapcore.Level, msg string, fields ...zap.Field) {}
+func (l *Nil) Log(_ zapcore.Level, _ string, _ ...zap.Field) {}
-func (l *Nil) Debug(msg string, fields ...zap.Field) {}
+func (l *Nil) Debug(_ string, _ ...zap.Field) {}
-func (l *Nil) Info(msg string, fields ...zap.Field) {}
+func (l *Nil) Info(_ string, _ ...zap.Field) {}
-func (l *Nil) Warn(msg string, fields ...zap.Field) {}
+func (l *Nil) Warn(_ string, _ ...zap.Field) {}
-func (l *Nil) Error(msg string, fields ...zap.Field) {}
+func (l *Nil) Error(_ string, _ ...zap.Field) {}
-func (l *Nil) DPanic(msg string, fields ...zap.Field) {}
+func (l *Nil) DPanic(_ string, _ ...zap.Field) {}
-func (l *Nil) Panic(msg string, fields ...zap.Field) {}
+func (l *Nil) Panic(_ string, _ ...zap.Field) {}
-func (l *Nil) Fatal(msg string, fields ...zap.Field) {}
+func (l *Nil) Fatal(_ string, _ ...zap.Field) {}
-func (l *Nil) ForHandler(handler any) Logger {
+func (l *Nil) ForHandler(_ any) Logger {
return l
}
-func (l *Nil) ForConnection(conn any) Logger {
+func (l *Nil) ForConnection(_ any) Logger {
return l
}
-func (l *Nil) ForAccount(acc any) Logger {
+func (l *Nil) ForAccount(_ any) Logger {
return l
}
diff --git a/core/logger/pool_test.go b/core/logger/pool_test.go
index 5509847..a73da78 100644
--- a/core/logger/pool_test.go
+++ b/core/logger/pool_test.go
@@ -1,8 +1,9 @@
package logger
import (
- "github.com/stretchr/testify/assert"
"testing"
+
+ "github.com/stretchr/testify/assert"
)
func TestPool(t *testing.T) {
diff --git a/core/logger/writer_adapter_test.go b/core/logger/writer_adapter_test.go
index 8007e02..68e34d2 100644
--- a/core/logger/writer_adapter_test.go
+++ b/core/logger/writer_adapter_test.go
@@ -1,10 +1,11 @@
package logger
import (
+ "testing"
+
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.uber.org/zap"
- "testing"
)
func TestWriterAdapter(t *testing.T) {
diff --git a/core/logger/zabbix_collector_adapter_test.go b/core/logger/zabbix_collector_adapter_test.go
index bd3633d..08f9dfb 100644
--- a/core/logger/zabbix_collector_adapter_test.go
+++ b/core/logger/zabbix_collector_adapter_test.go
@@ -2,9 +2,10 @@ package logger
import (
"errors"
+ "testing"
+
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "testing"
)
func TestZabbixCollectorAdapter(t *testing.T) {
diff --git a/core/middleware/csrf.go b/core/middleware/csrf.go
index 3fe4716..f8b59b0 100644
--- a/core/middleware/csrf.go
+++ b/core/middleware/csrf.go
@@ -6,7 +6,6 @@ import (
"crypto/sha1"
"encoding/base64"
"io"
- "io/ioutil"
"math/rand"
"time"
@@ -57,10 +56,10 @@ var DefaultCSRFTokenGetter = func(c *gin.Context) string {
} else if t := r.Header.Get("X-XSRF-Token"); len(t) > 0 {
return t
} else if c.Request.Body != nil {
- data, _ := ioutil.ReadAll(c.Request.Body)
- c.Request.Body = ioutil.NopCloser(bytes.NewReader(data))
+ data, _ := io.ReadAll(c.Request.Body)
+ c.Request.Body = io.NopCloser(bytes.NewReader(data))
t := r.FormValue("csrf_token")
- c.Request.Body = ioutil.NopCloser(bytes.NewReader(data))
+ c.Request.Body = io.NopCloser(bytes.NewReader(data))
if len(t) > 0 {
return t
@@ -91,17 +90,20 @@ type CSRF struct {
// csrfTokenGetter will be used to obtain token.
//
// Usage (with random salt):
-// core.NewCSRF("", "super secret", "csrf_session", store, func (c *gin.Context, reason core.CSRFErrorReason) {
-// c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid CSRF token"})
-// }, core.DefaultCSRFTokenGetter)
+//
+// core.NewCSRF("", "super secret", "csrf_session", store, func (c *gin.Context, reason core.CSRFErrorReason) {
+// c.AbortWithStatusJSON(http.StatusBadRequest, gin.H{"error": "Invalid CSRF token"})
+// }, core.DefaultCSRFTokenGetter)
//
// Note for csrfTokenGetter: if you want to read token from request body (for example, from form field)
// - don't forget to restore Body data!
//
// Body in http.Request is io.ReadCloser instance. Reading CSRF token from form like that:
-// if t := r.FormValue("csrf_token"); len(t) > 0 {
-// return t
-// }
+//
+// if t := r.FormValue("csrf_token"); len(t) > 0 {
+// return t
+// }
+//
// will close body - and all next middlewares won't be able to read body at all!
//
// Use DefaultCSRFTokenGetter as example to implement your own token getter.
@@ -185,11 +187,11 @@ func (x *CSRF) generateSalt() string {
// pseudoRandomString generates pseudo-random string with specified length.
func (x *CSRF) pseudoRandomString(length int) string {
- rand.Seed(time.Now().UnixNano())
+ r := rand.New(rand.NewSource(time.Now().UnixNano())) // nolint:gosec
data := make([]byte, length)
for i := 0; i < length; i++ { // it is supposed to use pseudo-random data.
- data[i] = byte(65 + rand.Intn(90-65)) // nolint:gosec,gomnd
+ data[i] = byte(65 + r.Intn(90-65)) // nolint:gosec,gomnd
}
return string(data)
@@ -209,15 +211,16 @@ func (x *CSRF) CSRFFromContext(c *gin.Context) string {
// GenerateCSRFMiddleware returns gin.HandlerFunc which will generate CSRF token
// Usage:
-// engine := gin.New()
-// csrf := NewCSRF("salt", "secret", "not_found", "incorrect", localizer)
-// engine.Use(csrf.GenerateCSRFMiddleware())
+//
+// engine := gin.New()
+// csrf := NewCSRF("salt", "secret", "not_found", "incorrect", localizer)
+// engine.Use(csrf.GenerateCSRFMiddleware())
func (x *CSRF) GenerateCSRFMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
session, _ := x.store.Get(c.Request, x.sessionName)
- if i, ok := session.Values["csrf_token"]; ok {
- if i, ok := i.(string); !ok || i == "" {
+ if i, ok := session.Values["csrf_token"]; ok { // nolint:nestif
+ if i, ok := i.(string); !ok || i == "" { // nolint:nestif
if x.fillToken(session, c) != nil {
x.abortFunc(c, CSRFErrorCannotStoreTokenInSession)
c.Abort()
@@ -243,8 +246,9 @@ func (x *CSRF) fillToken(s *sessions.Session, c *gin.Context) error {
// VerifyCSRFMiddleware verifies CSRF token
// Usage:
-// engine := gin.New()
-// engine.Use(csrf.VerifyCSRFMiddleware())
+//
+// engine := gin.New()
+// engine.Use(csrf.VerifyCSRFMiddleware())
func (x *CSRF) VerifyCSRFMiddleware(ignoredMethods []string) gin.HandlerFunc {
return func(c *gin.Context) {
if x.strInSlice(ignoredMethods, c.Request.Method) {
@@ -254,9 +258,9 @@ func (x *CSRF) VerifyCSRFMiddleware(ignoredMethods []string) gin.HandlerFunc {
var token string
session, _ := x.store.Get(c.Request, x.sessionName)
- if i, ok := session.Values["csrf_token"]; ok {
+ if i, ok := session.Values["csrf_token"]; ok { // nolint:nestif
var v string
- if v, ok = i.(string); !ok || v == "" {
+ if v, ok = i.(string); !ok || v == "" { // nolint:nestif
if !ok {
x.abortFunc(c, CSRFErrorIncorrectTokenType)
} else if v == "" {
diff --git a/core/middleware/csrf_test.go b/core/middleware/csrf_test.go
index 5f7b831..6d501a7 100644
--- a/core/middleware/csrf_test.go
+++ b/core/middleware/csrf_test.go
@@ -3,7 +3,6 @@ package middleware
import (
"bytes"
"io"
- "io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
@@ -32,7 +31,7 @@ func TestCSRF_DefaultCSRFTokenGetter_Empty(t *testing.T) {
URL: &url.URL{
RawQuery: "",
},
- Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
+ Body: io.NopCloser(bytes.NewReader([]byte(""))),
}}
assert.Empty(t, DefaultCSRFTokenGetter(c))
@@ -85,14 +84,14 @@ func TestCSRF_DefaultCSRFTokenGetter_Form(t *testing.T) {
RawQuery: "",
},
Header: headers,
- Body: ioutil.NopCloser(bytes.NewReader([]byte(""))),
+ Body: io.NopCloser(bytes.NewReader([]byte(""))),
}}
c.Request.PostForm = url.Values{"csrf_token": {"token"}}
assert.NotEmpty(t, DefaultCSRFTokenGetter(c))
assert.Equal(t, "token", DefaultCSRFTokenGetter(c))
- _, err := ioutil.ReadAll(c.Request.Body)
+ _, err := io.ReadAll(c.Request.Body)
assert.NoError(t, err)
}
diff --git a/core/sentry.go b/core/sentry.go
index 2e3330c..9f6763f 100644
--- a/core/sentry.go
+++ b/core/sentry.go
@@ -23,6 +23,8 @@ import (
"github.com/gin-gonic/gin"
)
+const recoveryMiddlewareSkipFrames = 3
+
// ErrorHandlerFunc will handle errors.
type ErrorHandlerFunc func(recovery interface{}, c *gin.Context)
@@ -249,7 +251,7 @@ func (s *Sentry) recoveryMiddleware() gin.HandlerFunc { // nolint
}
if l != nil {
// TODO: Check if we can output stacktraces with prefix data like before if we really need it.
- stack := stacktrace.FormattedStack(3, "trace: ")
+ stack := stacktrace.FormattedStack(recoveryMiddlewareSkipFrames, "trace: ")
formattedErr := logger.Err(err)
httpRequest, _ := httputil.DumpRequest(c.Request, false)
headers := strings.Split(string(httpRequest), "\r\n")
diff --git a/core/sentry_test.go b/core/sentry_test.go
index b919d86..2857725 100644
--- a/core/sentry_test.go
+++ b/core/sentry_test.go
@@ -31,12 +31,12 @@ type sentryMockTransport struct {
sending sync.RWMutex
}
-func (s *sentryMockTransport) Flush(timeout time.Duration) bool {
+func (s *sentryMockTransport) Flush(_ time.Duration) bool {
// noop
return true
}
-func (s *sentryMockTransport) Configure(options sentry.ClientOptions) {
+func (s *sentryMockTransport) Configure(_ sentry.ClientOptions) {
// noop
}
diff --git a/core/stacktrace/error_test.go b/core/stacktrace/error_test.go
index fdc205e..0ff8a51 100644
--- a/core/stacktrace/error_test.go
+++ b/core/stacktrace/error_test.go
@@ -18,7 +18,7 @@ func TestError(t *testing.T) {
func (t *ErrorTest) TestAppendToError() {
err := errors.New("test error")
- _, ok := err.(StackTraced)
+ _, ok := err.(StackTraced) // nolint:errorlint
t.Assert().False(ok)
@@ -28,16 +28,16 @@ func (t *ErrorTest) TestAppendToError() {
t.Assert().Nil(AppendToError(nil))
t.Assert().Implements((*StackTraced)(nil), withTrace)
t.Assert().Implements((*StackTraced)(nil), twiceTrace)
- t.Assert().Equal(withTrace.(StackTraced).StackTrace(), twiceTrace.(StackTraced).StackTrace())
+ t.Assert().Equal(withTrace.(StackTraced).StackTrace(), twiceTrace.(StackTraced).StackTrace()) // nolint:errorlint
}
func (t *ErrorTest) TestCauseUnwrap() {
err := errors.New("test error")
wrapped := AppendToError(err)
- t.Assert().Equal(err, wrapped.(*withStack).Cause())
+ t.Assert().Equal(err, wrapped.(*withStack).Cause()) // nolint:errorlint
t.Assert().Equal(err, errors.Unwrap(wrapped))
- t.Assert().Equal(wrapped.(*withStack).Cause(), errors.Unwrap(wrapped))
+ t.Assert().Equal(wrapped.(*withStack).Cause(), errors.Unwrap(wrapped)) // nolint:errorlint
}
func (t *ErrorTest) TestFormat() {
diff --git a/core/stacktrace/stack.go b/core/stacktrace/stack.go
index b6262a2..d66d6e9 100644
--- a/core/stacktrace/stack.go
+++ b/core/stacktrace/stack.go
@@ -5,7 +5,7 @@ import (
"bytes"
"fmt"
"io"
- "io/ioutil"
+ "os"
"path"
"runtime"
"strconv"
@@ -63,34 +63,34 @@ func (f Frame) name() string {
// Format formats the frame according to the fmt.Formatter interface.
//
-// %s source file
-// %d source line
-// %n function name
-// %v equivalent to %s:%d
+// %s source file
+// %d source line
+// %n function name
+// %v equivalent to %s:%d
//
// Format accepts flags that alter the printing of some verbs, as follows:
//
-// %+s function name and path of source file relative to the compile time
-// GOPATH separated by \n\t (