diff --git a/.golangci.yml b/.golangci.yml index 8486acd355b7e4eac35ef178cb3584dbbffa137e_LmdvbGFuZ2NpLnltbA==..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_LmdvbGFuZ2NpLnltbA== 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,3 +1,5 @@ run: timeout: 2m + sort-results: true + allow-parallel-runners: true linters: @@ -3,2 +5,3 @@ linters: + disable-all: true enable: @@ -4,7 +7,133 @@ enable: - - misspell - - revive - - whitespace - - unconvert - - gosec + # enable by default linters + - errcheck + - gosimple + - govet + - ineffassign + - staticcheck + - typecheck + - unused + + # extra linters + - asasalint #Â âš™ï¸ Check for pass []any as any in variadic func(...any). bugs 1.47.0 + - asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers + - bidichk # Checks for dangerous unicode character sequences + - bodyclose # checks whether HTTP response body is closed successfully + # - canonicalheader # Canonicalheader checks whether net/http.Header uses canonical header. style v1.58.0 + # - containedctx # containedctx is a linter that detects struct contained context.Context field style 1.44.0 + - contextcheck # check the function whether use a non-inherited context bugs v1.43.0 + - copyloopvar # Copyloopvar is a linter detects places where loop variables are copied. style v1.57.0 + # - cyclop # checks function and package cyclomatic complexity complexity v1.37.0 + # - decorder # check declaration order and count of types, constants, variables and functions format, style v1.44.0 + # - depguard # Go linter that checks if package imports are in a list of acceptable packages style, import, module v1.4.0 + - dogsled # Checks assignments with too many blank identifiers (e.g. x, , , _, := f()) style v1.19.0 + - dupl # Tool for code clone detection style v1.0.0 + - dupword # âš™ï¸ Checks for duplicate words in the source code. comment ✔ 1.50.0 + - durationcheck # check for two durations multiplied together bugs v1.37.0 + # - err113 # Go linter to check the errors handling expressions. style, error v1.26.0 + - errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occations, where the check for the returned error can be omitted. bugs 1.44.0 + # - errname # Checks that sentinel errors are prefixed with the Err and error types are suffixed with the Error. style v1.42.0 + - errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13. bugs, error v1.32.0 + - exhaustive # check exhaustiveness of enum switch statements bugs v1.28.0 + # - exhaustruct # Checks if all struct's fields are initialized style, test v1.32.0 + - exportloopref # checks for pointers to enclosing loop variables bugs v1.28.0 + - fatcontext # Detects nested contexts in loops. performance 1.58.0 + # - forbidigo # Forbids identifiers style v1.34.0 + - forcetypeassert # finds forced type assertions style v1.38.0 + # - funlen # Tool for detection of long functions complexity v1.18.0 + - gci # Gci control golang package import order and make it always deterministic. format, import ✔ v1.30.0 + - ginkgolinter # Enforces standards of using ginkgo and gomega. style v1.51.0 + - gocheckcompilerdirectives # Checks that go compiler directive comments (//go:) are valid. bugs v1.51.0 + # - gochecknoglobals # check that no global variables exist. style v1.12.0 + # - gochecknoinits # Checks that no init functions are present in Go code style v1.12.0 + - gochecksumtype # Run exhaustiveness checks on Go "sum types". bugs v1.55.0 + # - gocognit # Computes and checks the cognitive complexity of functions complexity v1.20.0 + - goconst # Finds repeated strings that could be replaced by a constant style v1.0.0 + - gocritic # Provides diagnostics that check for bugs, performance and style issues. style, metalinter v1.12.0 + # - gocyclo # Computes and checks the cyclomatic complexity of functions complexity v1.0.0 + - godot # Check if comments end in a period style, comment ✔ v1.25.0 + # - godox # Tool for detection of FIXME, TODO and other comment keywords style, comment v1.19.0 + - gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification format ✔ v1.0.0 + - gofumpt # Gofumpt checks whether code was gofumpt-ed. format ✔ v1.28.0 + - goheader # Checks is file header matches to pattern style v1.28.0 + - goimports # In addition to fixing imports, goimports also formats your code in the same style as gofmt. format, import ✔ v1.20.0 + # - gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod. style, module v1.39.0 + - gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. style, import, module v1.25.0 + - goprintffuncname # Checks that printf-like functions are named with f at the end style v1.23.0 + - gosec # Inspects source code for security problems bugs v1.0.0 + # - gosmopolitan # Report certain i18n/l10n anti-patterns in your Go codebase. bugs v1.53.0 + - grouper # Analyze expression groups. style v1.44.0 + - importas # Enforces consistent import aliases style v1.38.0 + # - inamedparam # Reports interfaces with unnamed method parameters. style v1.55.0 + - interfacebloat # checks the number of methods inside an interface. style v1.49.0 + - intrange # Intrange is a linter to find places where for loops could make use of an integer range. v1.57.0 + # - ireturn # Accept Interfaces, Return Concrete Types style v1.43.0 + - lll # Reports long lines style v1.8.0 + - loggercheck # Checks key value pairs for common logger libraries (kitlog,klog,logr,zap). style, bugs + # - maintidx # maintidx measures the maintainability index of each function. complexity v1.44.0 + - makezero # Finds slice declarations with non-zero initial length style, bugs v1.34.0 + - mirror # Reports wrong mirror patterns of bytes/strings usage. style v1.53.0 + - misspell # Finds commonly misspelled English words in comments style, comment ✔ v1.8.0 + # - mnd # An analyzer to detect magic numbers. style v1.22.0 + - musttag # âš™ï¸ Enforce field tags in (un)marshaled structs. style, bugs v1.51.0 + - nakedret # Finds naked returns in functions greater than a specified function length style v1.19.0 + # - nestif # Reports deeply nested if statements complexity v1.25.0 + - nilerr # Finds the code that returns nil even if it checks that the error is not nil. bugs v1.38.0 + - nilnil # Checks that there is no simultaneous return of nil error and an invalid value. style v1.43.0 + - nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity style v1.30.0 + - noctx # noctx finds sending http request without context.Context performance, bugs v1.28.0 + - nolintlint # Reports ill-formed or insufficient nolint directives style v1.26.0 + - nonamedreturns # Reports all named returns. style v1.46.0 + - nosprintfhostport # Checks for misuse of Sprintf to construct a host with port in a URL. style v1.46.0 + # - paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test style, test v1.33.0 + - perfsprint # Checks that fmt.Sprintf can be replaced with a faster alternative. performance v1.55.0 + - prealloc # Finds slice declarations that could potentially be preallocated performance v1.19.0 + - predeclared # find code that shadows one of Go's predeclared identifiers style v1.35.0 + - promlinter # Check Prometheus metrics naming via promlint style v1.40.0 + - protogetter # Reports direct reads from proto message fields when getters should be used. bugs ✔ v1.55.0 + - reassign # âš™ï¸ Checks that package variables are not reassigned. bugs 1.49.0 + - revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. style, metalinter v1.37.0 + - rowserrcheck # checks whether Err of rows is checked successfully bugs, sql v1.23.0 + - sloglint # Ensure consistent code style when using log/slog. style, format v1.55.0 + - spancheck # Checks for mistakes with OpenTelemetry/Census spans. bugs v1.56.0 + - sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. bugs, sql v1.28.0 + - stylecheck # Stylecheck is a replacement for golint style v1.20.0 + # - tagalign # âš™ï¸ Check that struct tags are well aligned. style, format ✔ v1.53.0 + # - tagliatelle # Checks the struct tags. style v1.40.0 + - tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 style v1.43.0 + - testableexamples # Linter checks if examples are testable (have an expected output). test v1.50.0 + - testifylint # Checks usage of github.com/stretchr/testify. test, bugs v1.55.0 + - testpackage # linter that makes you use a separate _test package style, test v1.25.0 + - thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers style v1.34.0 + - tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes style, test v1.32.0 + - unconvert # Remove unnecessary type conversions style v1.0.0 + - unparam # Reports unused function parameters unused v1.9.0 + - usestdlibvars # âš™ï¸ A linter that detect the possibility to use variables/constants from the Go standard library. style v1.48.0 + # - varnamelen # checks that the length of a variable's name matches its scope style v1.43.0 + - wastedassign # wastedassign finds wasted assignment statements. style v1.38.0 + - whitespace # Tool for detection of leading and trailing whitespace style ✔ v1.19.0 + # - wrapcheck # Checks that errors returned from external packages are wrapped style, error v1.32.0 + # - wsl # Whitespace Linter - Forces you to use empty lines! style v1.20.0 + - zerologlint # Detects the wrong usage of zerolog that a user forgets to dispatch with Send or Msg. bugs v1.53.0 + +linters-settings: + gci: + sections: + - standard + - default + - prefix(orus.io/orus-io/go-orusapi) + golint: + # minimal confidence for issues, default is 0.8 + min-confidence: 0.5 + varnamelen: + ignore-names: + - db + - msg + ignore-decls: + - t testing.T + - i int + testifylint: + enable-all: true + disable: + - require-error issues: @@ -10,3 +139,7 @@ issues: + # Maximum issues count per one linter. Set to 0 to disable. Default is 50. + max-issues-per-linter: 0 + # Maximum count of issues with the same text. Set to 0 to disable. Default is 3. + max-same-issues: 0 exclude: - SA5008 # duplicate struct tag (staticcheck) @@ -11,2 +144,11 @@ exclude: - SA5008 # duplicate struct tag (staticcheck) + - ST1016 # too many false + on method owner name consistency + - "unused-parameter:" # revive + - "if-return:" # revive + - "empty-block:" # revive + - "var-naming: don't use an underscore in package name" + - "ST1003: should not use underscores in package names" + exclude-rules: + exclude-dirs: + exclude-files: diff --git a/Makefile b/Makefile index 8486acd355b7e4eac35ef178cb3584dbbffa137e_TWFrZWZpbGU=..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_TWFrZWZpbGU= 100644 --- a/Makefile +++ b/Makefile @@ -1,5 +1,5 @@ -GOLANGCI_LINT_VERSION = v1.54.2 +GOLANGCI_LINT_VERSION = v1.59.1 GOLANGCI_LINT_BIN = tools/bin/golangci-lint-$(GOLANGCI_LINT_VERSION) help: ## Display this help @@ -16,4 +16,5 @@ | sh -s -- -b $$(go env GOPATH)/bin $(GOLANGCI_LINT_VERSION) \ && cp $$(go env GOPATH)/bin/golangci-lint $(GOLANGCI_LINT_BIN) +.PHONY: lint lint: $(GOLANGCI_LINT_BIN) ## Lint the files @@ -19,2 +20,6 @@ lint: $(GOLANGCI_LINT_BIN) ## Lint the files - $(GOLANGCI_LINT_BIN) run + $(GOLANGCI_LINT_BIN) run $(GOLANGCI_LINT_ARGS) + +.PHONY: lint-fix +lint-fix: $(GOLANGCI_LINT_BIN) ## Lint & fix the files + $(GOLANGCI_LINT_BIN) run --fix $(GOLANGCI_LINT_ARGS) diff --git a/database/database.go b/database/database.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_ZGF0YWJhc2UvZGF0YWJhc2UuZ28=..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_ZGF0YWJhc2UvZGF0YWJhc2UuZ28= 100644 --- a/database/database.go +++ b/database/database.go @@ -4,7 +4,7 @@ "github.com/jmoiron/sqlx" ) -// Open opens a connection to the database +// Open opens a connection to the database. func Open(dsn string, maxConn int) (*sqlx.DB, error) { db, err := sqlx.Open("postgres", dsn) if err != nil { diff --git a/database/join.go b/database/join.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_ZGF0YWJhc2Uvam9pbi5nbw==..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_ZGF0YWJhc2Uvam9pbi5nbw== 100644 --- a/database/join.go +++ b/database/join.go @@ -2,7 +2,7 @@ import "fmt" -// Join builds a join clause +// Join builds a join clause. func Join(tableFrom, fieldFrom, tableTo, fieldTo string) string { return fmt.Sprintf("%[3]s ON %[3]s.%[4]s = %[1]s.%[2]s", tableFrom, fieldFrom, tableTo, fieldTo) diff --git a/database/migrations.go b/database/migrations.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_ZGF0YWJhc2UvbWlncmF0aW9ucy5nbw==..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_ZGF0YWJhc2UvbWlncmF0aW9ucy5nbw== 100644 --- a/database/migrations.go +++ b/database/migrations.go @@ -16,8 +16,8 @@ //go:generate sed -i "1s;^;// Code generated by go-bindata. DO NOT EDIT.\\n\\n;" bindata.go // ErrDBNotVersioned is returned by IsUptodate if the database is not versionned -// at all +// at all. var ErrDBNotVersioned = errors.New( "the database is not versionned, please run the 'migrate' command") // ErrDBNeedUpgrade is returned if the database is not up-to-date with the @@ -20,10 +20,10 @@ var ErrDBNotVersioned = errors.New( "the database is not versionned, please run the 'migrate' command") // ErrDBNeedUpgrade is returned if the database is not up-to-date with the -// server version +// server version. type ErrDBNeedUpgrade struct { CurrentVersion uint RequiredVersion uint } @@ -25,9 +25,9 @@ type ErrDBNeedUpgrade struct { CurrentVersion uint RequiredVersion uint } -// Error returns the formatted error message +// Error returns the formatted error message. func (e ErrDBNeedUpgrade) Error() string { return fmt.Sprintf("Database version is too old. Please run '%s migrate'."+ " Required version: %d, current version: %d", @@ -36,9 +36,9 @@ } // ErrDBFutureVersion is returned if the database is more recent than the server. -// It generally means the server is not at the right version +// It generally means the server is not at the right version. type ErrDBFutureVersion struct { CurrentVersion uint RequiredVersion uint } @@ -40,9 +40,9 @@ type ErrDBFutureVersion struct { CurrentVersion uint RequiredVersion uint } -// Error returns the formatted error message +// Error returns the formatted error message. func (e ErrDBFutureVersion) Error() string { return fmt.Sprintf("Database version is too new. It probably means your "+ "version of '%s' is too old."+ @@ -52,7 +52,7 @@ } // NewMigrate initializes a github.com/golang-migrate/migrate/v4.Migrate for -// the given database options +// the given database options. func NewMigrate(dsn string, sourceDriver source.Driver) (*migrate.Migrate, error) { db, err := sql.Open("postgres", dsn) if err != nil { @@ -74,7 +74,7 @@ } // AutoMigrate brings the db up-to-date and logs a warning if it needed some -// changes +// changes. func AutoMigrate(dsn string, sourceDriver source.Driver, log zerolog.Logger) error { err := IsUptodate(dsn, sourceDriver) if err == nil { @@ -97,7 +97,7 @@ return nil } -// IsUptodate returns nil if the database version is up to date +// IsUptodate returns nil if the database version is up to date. func IsUptodate(dsn string, sourceDriver source.Driver) error { m, err := NewMigrate(dsn, sourceDriver) if err != nil { diff --git a/database/options.go b/database/options.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_ZGF0YWJhc2Uvb3B0aW9ucy5nbw==..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_ZGF0YWJhc2Uvb3B0aW9ucy5nbw== 100644 --- a/database/options.go +++ b/database/options.go @@ -2,9 +2,9 @@ import "github.com/jmoiron/sqlx" -// Options is a jessevdk/go-flags compatible struct for db-related options +// Options is a jessevdk/go-flags compatible struct for db-related options. type Options struct { DSN string `long:"dsn" env:"DSN" ini-name:"dsn" description:"DSN of the database"` MaxConn int `long:"max-conn" env:"MAX_CONN" ini-name:"max-conn" description:"Database max connection" default:"0"` } @@ -6,9 +6,9 @@ type Options struct { DSN string `long:"dsn" env:"DSN" ini-name:"dsn" description:"DSN of the database"` MaxConn int `long:"max-conn" env:"MAX_CONN" ini-name:"max-conn" description:"Database max connection" default:"0"` } -// Open a connection to the database +// Open a connection to the database. func (o Options) Open() (*sqlx.DB, error) { return Open(o.DSN, o.MaxConn) } diff --git a/database/sql.go b/database/sql.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_ZGF0YWJhc2Uvc3FsLmdv..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_ZGF0YWJhc2Uvc3FsLmdv 100644 --- a/database/sql.go +++ b/database/sql.go @@ -12,7 +12,7 @@ "github.com/rs/zerolog" ) -// Mapped is the common interface of all structs that are mapped in the database +// Mapped is the common interface of all structs that are mapped in the database. type Mapped interface { Table() string PKeyColumn() string @@ -20,6 +20,6 @@ Values(columns ...string) []interface{} } -// SQ is a squirrel StatementBuilder +// SQ is a squirrel StatementBuilder. var SQ = squirrel.StatementBuilder @@ -24,6 +24,6 @@ var SQ = squirrel.StatementBuilder -// SQLTrace logs a sql query and args as TRACE level +// SQLTrace logs a sql query and args as TRACE level. func SQLTrace(log *zerolog.Logger, sql string, args []interface{}) { if log != nil && log.GetLevel() < 0 { arr := zerolog.Arr() @@ -47,7 +47,7 @@ } // SQLExecutor is the common interface of sqlx.DB and sqlx.Tx that we use in -// the functions below +// the functions below. type SQLExecutor interface { ExecContext(context.Context, string, ...interface{}) (sql.Result, error) GetContext(ctx context.Context, dest interface{}, query string, args ...interface{}) error @@ -59,8 +59,8 @@ return builder.Set(query, "PlaceholderFormat", squirrel.Dollar).(squirrel.Sqlizer) } -// Get loads an object +// Get loads an object. func Get(e SQLExecutor, obj interface{}, query squirrel.Sqlizer, log *zerolog.Logger) error { return GetContext(context.Background(), e, obj, query, log) } @@ -63,8 +63,8 @@ func Get(e SQLExecutor, obj interface{}, query squirrel.Sqlizer, log *zerolog.Logger) error { return GetContext(context.Background(), e, obj, query, log) } -// GetContext loads an object +// GetContext loads an object. func GetContext( ctx context.Context, e SQLExecutor, obj interface{}, query squirrel.Sqlizer, log *zerolog.Logger, ) error { @@ -76,8 +76,8 @@ return e.GetContext(ctx, obj, sqlQuery, args...) } -// Select load an object list +// Select load an object list. func Select(e SQLExecutor, obj interface{}, query squirrel.Sqlizer, log *zerolog.Logger) error { return SelectContext(context.Background(), e, obj, query, log) } @@ -80,8 +80,8 @@ func Select(e SQLExecutor, obj interface{}, query squirrel.Sqlizer, log *zerolog.Logger) error { return SelectContext(context.Background(), e, obj, query, log) } -// SelectContext loads an object list +// SelectContext loads an object list. func SelectContext( ctx context.Context, e SQLExecutor, obj interface{}, query squirrel.Sqlizer, log *zerolog.Logger, ) error { @@ -93,8 +93,8 @@ return e.SelectContext(ctx, obj, sqlQuery, args...) } -// Exec runs a squirrel query on the given db or tx +// Exec runs a squirrel query on the given db or tx. func Exec(e SQLExecutor, query squirrel.Sqlizer, log *zerolog.Logger) (sql.Result, error) { return ExecContext(context.Background(), e, query, log) } @@ -97,8 +97,8 @@ func Exec(e SQLExecutor, query squirrel.Sqlizer, log *zerolog.Logger) (sql.Result, error) { return ExecContext(context.Background(), e, query, log) } -// ExecContext runs a squirrel query on the given db or tx +// ExecContext runs a squirrel query on the given db or tx. func ExecContext(ctx context.Context, e SQLExecutor, query squirrel.Sqlizer, log *zerolog.Logger) (sql.Result, error) { query = setPlaceHolderFormat(query) sqlQuery, args, err := query. @@ -110,7 +110,7 @@ return e.ExecContext(ctx, sqlQuery, args...) } -// QueryContext runs a squirrel query on the given db or tx +// QueryContext runs a squirrel query on the given db or tx. func QueryContext(ctx context.Context, e SQLExecutor, query squirrel.Sqlizer, log *zerolog.Logger) (*sqlx.Rows, error) { query = setPlaceHolderFormat(query) sqlQuery, args, err := query. @@ -123,7 +123,7 @@ } // ValuesMap returns the values for a list of columns as a map. If a column does -// not exits, the corresponding value is set to nil +// not exits, the corresponding value is set to nil. func ValuesMap(m Mapped, columns ...string) map[string]interface{} { valuesList := m.Values(columns...) values := make(map[string]interface{}) @@ -134,7 +134,7 @@ } // SQLUpdate generates a squirrel "update" statement -// for the given mapped instance (auto-selecting by its pkey) +// for the given mapped instance (auto-selecting by its pkey). func SQLUpdate(m Mapped, columns ...string) squirrel.UpdateBuilder { if len(columns) == 0 { columns = m.Columns(false) @@ -146,7 +146,7 @@ return q } -// SQLUpsert generates a squirrel "upsert" statement +// SQLUpsert generates a squirrel "upsert" statement. func SQLUpsert(m Mapped) squirrel.InsertBuilder { return SQLUpsertColumns(m, m.Columns(true), m.Columns(false)) } @@ -164,7 +164,7 @@ updateParts := strings.Split(updateSQL, " SET ") if len(updateParts) != 2 { - panic("Could not split the UPDATE query: " + updateSQL) //nolint:gosec + panic("Could not split the UPDATE query: " + updateSQL) } suffix := "ON CONFLICT (" + m.PKeyColumn() + ") DO UPDATE SET " + updateParts[1] @@ -177,7 +177,7 @@ return q } -// SQLUpsertNoPKey generates a squirrel "upsert" statement +// SQLUpsertNoPKey generates a squirrel "upsert" statement. func SQLUpsertNoPKey(keyCols []string, m Mapped) squirrel.InsertBuilder { updateSQL, updateArgs, err := squirrel. Update(m.Table()). @@ -189,7 +189,7 @@ updateParts := strings.Split(updateSQL, " SET ") if len(updateParts) != 2 { - panic("Could not split the UPDATE query: " + updateSQL) //nolint:gosec + panic("Could not split the UPDATE query: " + updateSQL) } suffix := "ON CONFLICT (" + strings.Join(keyCols, ",") + ") DO UPDATE SET " + updateParts[1] @@ -204,7 +204,7 @@ } // SQLInsert build a Insert statement to insert one or several mapped instances -// in the database. All the instances must be of the same actual type +// in the database. All the instances must be of the same actual type. func SQLInsert(instances ...Mapped) squirrel.InsertBuilder { allColumns := instances[0].Columns(true) q := SQ.Insert(instances[0].Table()). @@ -217,7 +217,7 @@ // SQLInsertNoPKey build a Insert statement to insert one or several mapped instances // in the database, but leave the pkey undefined so it gets auto-generated -// by the database. All the instances must be of the same actual type +// by the database. All the instances must be of the same actual type. func SQLInsertNoPKey(instances ...Mapped) squirrel.InsertBuilder { allColumns := instances[0].Columns(false) q := SQ.Insert(instances[0].Table()). @@ -230,7 +230,7 @@ // PrefixColumns ... func PrefixColumns(table string, columns ...string) []string { - var prefixed = make([]string, len(columns)) + prefixed := make([]string, len(columns)) for i, name := range columns { prefixed[i] = PrefixColumn(table, name) } diff --git a/database/sql_helper.go b/database/sql_helper.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_ZGF0YWJhc2Uvc3FsX2hlbHBlci5nbw==..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_ZGF0YWJhc2Uvc3FsX2hlbHBlci5nbw== 100644 --- a/database/sql_helper.go +++ b/database/sql_helper.go @@ -9,8 +9,8 @@ "github.com/rs/zerolog" ) -// NewSQLHelper creates a SQLHelper. It must not outlive the given context and sql executor +// NewSQLHelper creates a SQLHelper. It must not outlive the given context and sql executor. func NewSQLHelper(ctx context.Context, sqle SQLExecutor, log zerolog.Logger) SQLHelper { return SQLHelper{ctx, sqle, log} } @@ -13,11 +13,11 @@ func NewSQLHelper(ctx context.Context, sqle SQLExecutor, log zerolog.Logger) SQLHelper { return SQLHelper{ctx, sqle, log} } -// SQLHelper is a short lived helper to easily get/select Mapped structures +// SQLHelper is a short lived helper to easily get/select Mapped structures. type SQLHelper struct { ctx context.Context sqle SQLExecutor log zerolog.Logger } @@ -18,10 +18,10 @@ type SQLHelper struct { ctx context.Context sqle SQLExecutor log zerolog.Logger } -// Get loads a mapped structure +// Get loads a mapped structure. func (h *SQLHelper) Get(obj interface{}, query sq.Sqlizer) error { return GetContext(h.ctx, h.sqle, obj, query, &h.log) } @@ -31,7 +31,7 @@ return h.sqle.GetContext(h.ctx, obj, sql, args...) } -// GetByPKey loads a mapped structure by primary key +// GetByPKey loads a mapped structure by primary key. func (h *SQLHelper) GetByPKey(obj Mapped, value interface{}) error { return h.GetBy(obj, obj.PKeyColumn(), value) } @@ -42,7 +42,7 @@ return h.GetByForUpdate(obj, obj.PKeyColumn(), value) } -// GetBy loads a mapped structure by a given column +// GetBy loads a mapped structure by a given column. func (h *SQLHelper) GetBy(obj Mapped, column string, value interface{}) error { return h.GetWhere(obj, sq.Eq{column: value}) } @@ -87,7 +87,7 @@ return h.Get(obj, query) } -// Select loads a structure list +// Select loads a structure list. func (h *SQLHelper) Select(obj interface{}, query sq.Sqlizer) error { return SelectContext(h.ctx, h.sqle, obj, query, &h.log) } @@ -97,7 +97,7 @@ return h.sqle.SelectContext(h.ctx, obj, sql, args...) } -// Exec executes a query +// Exec executes a query. func (h *SQLHelper) Exec(query sq.Sqlizer) (sql.Result, error) { return ExecContext(h.ctx, h.sqle, query, &h.log) } @@ -107,8 +107,8 @@ return h.sqle.ExecContext(h.ctx, sql, args...) } -// Query executes a query +// Query executes a query. func (h *SQLHelper) Query(query sq.Sqlizer) (*sqlx.Rows, error) { return QueryContext(h.ctx, h.sqle, query, &h.log) } @@ -111,10 +111,10 @@ func (h *SQLHelper) Query(query sq.Sqlizer) (*sqlx.Rows, error) { return QueryContext(h.ctx, h.sqle, query, &h.log) } -// QueryRaw executes a raw SQL query +// QueryRaw executes a raw SQL query. func (h *SQLHelper) QueryRaw(sql string, args ...interface{}) (*sqlx.Rows, error) { SQLTrace(&h.log, sql, args) return h.sqle.QueryxContext(h.ctx, sql, args...) } @@ -116,11 +116,11 @@ func (h *SQLHelper) QueryRaw(sql string, args ...interface{}) (*sqlx.Rows, error) { SQLTrace(&h.log, sql, args) return h.sqle.QueryxContext(h.ctx, sql, args...) } -// Insert inserts a Mapped into the db +// Insert inserts a Mapped into the db. func (h *SQLHelper) Insert(instances ...Mapped) (sql.Result, error) { query := SQLInsert(instances...) return h.Exec(query) } @@ -122,11 +122,11 @@ func (h *SQLHelper) Insert(instances ...Mapped) (sql.Result, error) { query := SQLInsert(instances...) return h.Exec(query) } -// InsertNoPKey inserts a Mapped into the db +// InsertNoPKey inserts a Mapped into the db. func (h *SQLHelper) InsertNoPKey(instances ...Mapped) (sql.Result, error) { query := SQLInsertNoPKey(instances...) return h.Exec(query) } @@ -128,9 +128,9 @@ func (h *SQLHelper) InsertNoPKey(instances ...Mapped) (sql.Result, error) { query := SQLInsertNoPKey(instances...) return h.Exec(query) } -// Upsert upserts a Mapped into the db +// Upsert upserts a Mapped into the db. func (h *SQLHelper) Upsert(instances ...Mapped) error { for _, instance := range instances { query := SQLUpsert(instance) @@ -141,7 +141,7 @@ return nil } -// UpsertColumns upserts a Mapped into the db using only the given columns as update source +// UpsertColumns upserts a Mapped into the db using only the given columns as update source. func (h *SQLHelper) UpsertColumns(insertColumns, updateColumns []string, instances ...Mapped) error { for _, instance := range instances { query := SQLUpsertColumns(instance, insertColumns, updateColumns) @@ -153,7 +153,7 @@ } // Update updates the given Mapped into the db using their -// pkey as predicate for the where clause +// pkey as predicate for the where clause. func (h *SQLHelper) Update(instances ...Mapped) error { for _, instance := range instances { query := SQLUpdate(instance) @@ -164,7 +164,7 @@ return nil } -// UpdateColumns update a mapped but only for the given columns +// UpdateColumns update a mapped but only for the given columns. func (h *SQLHelper) UpdateColumns(instance Mapped, columns ...string) error { query := SQLUpdate(instance, columns...) if _, err := h.Exec(query); err != nil { @@ -173,7 +173,7 @@ return nil } -// UpsertNoPKey upserts a Mapped into the db +// UpsertNoPKey upserts a Mapped into the db. func (h *SQLHelper) UpsertNoPKey(keyCols []string, instances ...Mapped) error { for _, instance := range instances { query := SQLUpsertNoPKey(keyCols, instance) diff --git a/database/test.go b/database/test.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_ZGF0YWJhc2UvdGVzdC5nbw==..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_ZGF0YWJhc2UvdGVzdC5nbw== 100644 --- a/database/test.go +++ b/database/test.go @@ -24,7 +24,7 @@ return dsn } -//nolint:revive + func clearDB(ctx context.Context, t testing.TB, c *sqlx.Conn, dsn string) { // Drop all tables, and reinit if _, err := c.ExecContext(ctx, "DROP SCHEMA IF EXISTS public CASCADE"); err != nil { @@ -35,7 +35,7 @@ } } -// TestDB is a sqlx.DB wrapper that release a global lock on close +// TestDB is a sqlx.DB wrapper that release a global lock on close. type TestDB struct { *sqlx.DB DSN string @@ -44,7 +44,7 @@ lockConn *sqlx.Conn } -// SetTB changes the current tb and returns a function to restore the original one +// SetTB changes the current tb and returns a function to restore the original one. func (db *TestDB) SetTB(tb testing.TB) func() { save := db.tb db.tb = tb @@ -53,7 +53,7 @@ } } -// ClearDB empty the database +// ClearDB empty the database. func (db *TestDB) ClearDB() { tx, err := db.lockConn.BeginTxx(db.ctx, nil) require.NoError(db.tb, err) @@ -67,7 +67,7 @@ for _, name := range dbtablenames { if _, err := tx.Exec( - "DELETE FROM " + name, //nolint:gosec + "DELETE FROM " + name, ); err != nil { db.tb.Fatal(err) } @@ -130,7 +130,7 @@ } // GetTestDB creates a db and returns it. It must be closed within the test. -// If it fails, t.Fatal() is called +// If it fails, t.Fatal() is called. func GetTestDB(ctx context.Context, t testing.TB, sourceDriver source.Driver) *TestDB { db := GetTestDBNoClear(ctx, t, sourceDriver) db.ClearDB() @@ -228,7 +228,7 @@ } } -// Close the lock connection, then the database +// Close the lock connection, then the database. func (db *TestDB) Close() { if db.lockConn != nil { if err := db.lockConn.Close(); err != nil { diff --git a/database/tx.go b/database/tx.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_ZGF0YWJhc2UvdHguZ28=..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_ZGF0YWJhc2UvdHguZ28= 100644 --- a/database/tx.go +++ b/database/tx.go @@ -8,7 +8,7 @@ "github.com/rs/zerolog" ) -// TxState is a enum that describes the states of a transaction +// TxState is a enum that describes the states of a transaction. type TxState int const ( @@ -12,5 +12,5 @@ type TxState int const ( - // TxOpened means the transaction begun and is not yet closed + // TxOpened means the transaction begun and is not yet closed. TxOpened TxState = iota @@ -16,3 +16,3 @@ TxOpened TxState = iota - // TxCommitted means the transaction was committed (maybe with an error) + // TxCommitted means the transaction was committed (maybe with an error). TxCommitted @@ -18,5 +18,5 @@ TxCommitted - // TxRolledback means the transaction was rolled back (maybe with an error) + // TxRolledback means the transaction was rolled back (maybe with an error). TxRolledback ) @@ -20,7 +20,7 @@ TxRolledback ) -// Begin begins a transaction and returns a *database.Tx +// Begin begins a transaction and returns a *database.Tx. func Begin(ctx context.Context, db *sqlx.DB) (*Tx, error) { tx, err := db.BeginTxx(ctx, nil) if err != nil { @@ -29,10 +29,10 @@ return &Tx{tx, TxOpened}, nil } -// Tx wraps a sqlx.Tx +// Tx wraps a sqlx.Tx. type Tx struct { *sqlx.Tx state TxState } @@ -33,10 +33,10 @@ type Tx struct { *sqlx.Tx state TxState } -// Commit commits the transaction +// Commit commits the transaction. func (tx *Tx) Commit() error { if tx.state != TxOpened { return fmt.Errorf("transaction is not open") @@ -45,7 +45,7 @@ return tx.Tx.Commit() } -// Rollback rollbacks the transaction +// Rollback rollbacks the transaction. func (tx *Tx) Rollback() error { if tx.state != TxOpened { return fmt.Errorf("transaction is not open") @@ -54,10 +54,10 @@ return tx.Tx.Rollback() } -// LoggedRollback rollbacks the transaction and log the error if it fails +// LoggedRollback rollbacks the transaction and log the error if it fails. func (tx *Tx) LoggedRollback(log zerolog.Logger) { if err := tx.Rollback(); err != nil { log.Err(err).Msg("rollback failed") } } @@ -58,10 +58,10 @@ func (tx *Tx) LoggedRollback(log zerolog.Logger) { if err := tx.Rollback(); err != nil { log.Err(err).Msg("rollback failed") } } -// RollbackIfOpened rollbacks the transaction if it is still opened +// RollbackIfOpened rollbacks the transaction if it is still opened. func (tx *Tx) RollbackIfOpened(log zerolog.Logger) { if tx.state == TxOpened { tx.LoggedRollback(log) diff --git a/generate-config.go b/generate-config.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_Z2VuZXJhdGUtY29uZmlnLmdv..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_Z2VuZXJhdGUtY29uZmlnLmdv 100644 --- a/generate-config.go +++ b/generate-config.go @@ -7,10 +7,10 @@ flags "github.com/orus-io/go-flags" ) -// GenerateConfigCmd is a command that generates a configuration file +// GenerateConfigCmd is a command that generates a configuration file. type GenerateConfigCmd struct { Output string `short:"o" long:"output" default:"-" no-ini:"t" description:"output file"` parser *flags.Parser } @@ -11,11 +11,11 @@ type GenerateConfigCmd struct { Output string `short:"o" long:"output" default:"-" no-ini:"t" description:"output file"` parser *flags.Parser } -// NewGenerateConfigCmd creates a GenerateConfigCmd +// NewGenerateConfigCmd creates a GenerateConfigCmd. func NewGenerateConfigCmd(parser *flags.Parser) *GenerateConfigCmd { return &GenerateConfigCmd{parser: parser} } @@ -18,10 +18,10 @@ func NewGenerateConfigCmd(parser *flags.Parser) *GenerateConfigCmd { return &GenerateConfigCmd{parser: parser} } -// Execute write out a configuration file +// Execute write out a configuration file. func (c *GenerateConfigCmd) Execute([]string) (errResult error) { var out io.Writer if c.Output == "-" { out = os.Stdout } else { @@ -23,9 +23,9 @@ func (c *GenerateConfigCmd) Execute([]string) (errResult error) { var out io.Writer if c.Output == "-" { out = os.Stdout } else { - f, err := os.OpenFile(c.Output, os.O_RDWR|os.O_CREATE, 0755) + f, err := os.OpenFile(c.Output, os.O_RDWR|os.O_CREATE, 0o755) if err != nil { return err } diff --git a/log-console-writer.go b/log-console-writer.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_bG9nLWNvbnNvbGUtd3JpdGVyLmdv..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_bG9nLWNvbnNvbGUtd3JpdGVyLmdv 100644 --- a/log-console-writer.go +++ b/log-console-writer.go @@ -24,7 +24,7 @@ ) // ExceptionFieldName is the field name used for exception fields. -// In our case, it should be a sentry-formatted exception built from a panic +// In our case, it should be a sentry-formatted exception built from a panic. const ExceptionFieldName = "exception" const ( @@ -41,13 +41,11 @@ colorDarkGray = 90 ) -var ( - consoleBufPool = sync.Pool{ - New: func() interface{} { - return bytes.NewBuffer(make([]byte, 0, 100)) - }, - } -) +var consoleBufPool = sync.Pool{ + New: func() interface{} { + return bytes.NewBuffer(make([]byte, 0, 100)) + }, +} const ( consoleDefaultTimeFormat = time.Kitchen @@ -104,7 +102,7 @@ w.PartsOrder = consoleDefaultPartsOrder() } - var buf = consoleBufPool.Get().(*bytes.Buffer) + buf := consoleBufPool.Get().(*bytes.Buffer) defer func() { buf.Reset() consoleBufPool.Put(buf) @@ -135,7 +133,7 @@ // writeFields appends formatted key-value pairs to buf. func (w ConsoleWriter) writeFields(evt map[string]interface{}, buf *bytes.Buffer) { - var fields = make([]string, 0, len(evt)) + fields := make([]string, 0, len(evt)) for field := range evt { switch field { case zerolog.LevelFieldName, zerolog.TimestampFieldName, zerolog.MessageFieldName, zerolog.CallerFieldName: @@ -155,7 +153,7 @@ hasErr := erri < len(fields) && fields[erri] == zerolog.ErrorFieldName hasExc := exci < len(fields) && fields[exci] == ExceptionFieldName - var xfields = make([]string, 0, len(fields)) + xfields := make([]string, 0, len(fields)) if hasErr { xfields = append(xfields, zerolog.ErrorFieldName) } @@ -278,7 +276,7 @@ } } - var s = f(evt[p]) + s := f(evt[p]) if len(s) > 0 { buf.WriteString(s) @@ -468,7 +466,7 @@ return in } -// PrintFrame prints a sentry frame in a go stack-like manner +// PrintFrame prints a sentry frame in a go stack-like manner. func PrintFrame(frame sentry.Frame) string { return fmt.Sprintf("%s.%s\n %s:%d\n", frame.Module, frame.Function, frame.AbsPath, frame.Lineno) } diff --git a/log-console-writer_test.go b/log-console-writer_test.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_bG9nLWNvbnNvbGUtd3JpdGVyX3Rlc3QuZ28=..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_bG9nLWNvbnNvbGUtd3JpdGVyX3Rlc3QuZ28= 100644 --- a/log-console-writer_test.go +++ b/log-console-writer_test.go @@ -381,7 +381,7 @@ b.ResetTimer() b.ReportAllocs() - var msg = []byte(`{"level": "info", "foo": "bar", "message": "HELLO", "time": "1990-01-01"}`) + msg := []byte(`{"level": "info", "foo": "bar", "message": "HELLO", "time": "1990-01-01"}`) w := ConsoleWriter{Out: io.Discard, NoColor: false} diff --git a/logging.go b/logging.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_bG9nZ2luZy5nbw==..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_bG9nZ2luZy5nbw== 100644 --- a/logging.go +++ b/logging.go @@ -9,7 +9,7 @@ "golang.org/x/term" ) -// NewLoggingOptions creates a LoggingOptions +// NewLoggingOptions creates a LoggingOptions. func NewLoggingOptions(log *zerolog.Logger, output io.Writer) (*LoggingOptions, error) { var o LoggingOptions if err := o.Setup(log, output); err != nil { @@ -18,7 +18,7 @@ return &o, nil } -// MustLoggingOptions panic if err is not nil +// MustLoggingOptions panic if err is not nil. func MustLoggingOptions(o *LoggingOptions, err error) *LoggingOptions { if err != nil { panic(err) @@ -36,7 +36,7 @@ Level(zerolog.WarnLevel) } -// LoggingOptions holds the logging options +// LoggingOptions holds the logging options. type LoggingOptions struct { Level func(string) error `long:"level" env:"LEVEL" ini-name:"log-level" choice:"trace" choice:"debug" choice:"info" choice:"warn" choice:"error" choice:"fatal" choice:"panic" choice:"auto" default:"auto" description:"log level. 'auto' selects 'info' when stdout is a tty, 'error' otherwise."` Format func(string) error `long:"format" env:"FORMAT" ini-name:"log-format" choice:"json" choice:"pretty" choice:"auto" default:"auto" description:"Logs format. 'auto' selects 'pretty' if stdout is a tty."` @@ -49,7 +49,7 @@ log *zerolog.Logger `no-flag:"t"` } -// Logger returns the latest configured logger +// Logger returns the latest configured logger. func (o *LoggingOptions) Logger() zerolog.Logger { return *o.log } @@ -67,9 +67,9 @@ *o.log = o.log.Output(out) } -// AddLogWrapper adds a log wrapper to the stack +// AddLogWrapper adds a log wrapper to the stack. func (o *LoggingOptions) AddLogWrapper(wrapper func(io.Writer) io.Writer) { o.logWrappers = append(o.logWrappers, wrapper) o.resetOutput() } @@ -71,9 +71,9 @@ func (o *LoggingOptions) AddLogWrapper(wrapper func(io.Writer) io.Writer) { o.logWrappers = append(o.logWrappers, wrapper) o.resetOutput() } -// SetMinLoggingLevel makes sure the logging level is not under a given value +// SetMinLoggingLevel makes sure the logging level is not under a given value. func (o *LoggingOptions) SetMinLoggingLevel(level zerolog.Level) { if level < o.log.GetLevel() { *o.log = log.Level(level) @@ -82,7 +82,7 @@ // Setup ... func (o *LoggingOptions) Setup(log *zerolog.Logger, output io.Writer) error { - var logLevelAutoLocked = false + logLevelAutoLocked := false o.logFinalOutput = output diff --git a/panic_middleware.go b/panic_middleware.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_cGFuaWNfbWlkZGxld2FyZS5nbw==..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_cGFuaWNfbWlkZGxld2FyZS5nbw== 100644 --- a/panic_middleware.go +++ b/panic_middleware.go @@ -10,7 +10,7 @@ "github.com/rs/zerolog" ) -// CatchPanics catches the panics and log them as errors +// CatchPanics catches the panics and log them as errors. func CatchPanics(next http.Handler) http.Handler { return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) { defer func() { diff --git a/prometheus_middleware.go b/prometheus_middleware.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_cHJvbWV0aGV1c19taWRkbGV3YXJlLmdv..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_cHJvbWV0aGV1c19taWRkbGV3YXJlLmdv 100644 --- a/prometheus_middleware.go +++ b/prometheus_middleware.go @@ -8,7 +8,7 @@ "github.com/prometheus/client_golang/prometheus/promhttp" ) -// Prometheus serves the '/metrics' endpoint +// Prometheus serves the '/metrics' endpoint. func Prometheus(path string) func(next http.Handler) http.Handler { handler := promhttp.Handler() diff --git a/redoc.go b/redoc.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_cmVkb2MuZ28=..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_cmVkb2MuZ28= 100644 --- a/redoc.go +++ b/redoc.go @@ -8,7 +8,7 @@ "path" ) -// RedocOpts configures the Redoc middleware +// RedocOpts configures the Redoc middleware. type RedocOpts struct { // BasePath for the UI path, defaults to: / BasePath string @@ -22,7 +22,7 @@ Title string } -// EnsureDefaults in case some options are missing +// EnsureDefaults in case some options are missing. func (r *RedocOpts) EnsureDefaults() { if r.BasePath == "" { r.BasePath = "/" @@ -43,7 +43,6 @@ // Redoc creates a middleware to serve a documentation site for a swagger spec. // This allows for altering the spec before starting the http listener. -// func Redoc(opts RedocOpts) func(http.Handler) http.Handler { opts.EnsureDefaults() diff --git a/scripts/generate_db_helpers.go b/scripts/generate_db_helpers.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_c2NyaXB0cy9nZW5lcmF0ZV9kYl9oZWxwZXJzLmdv..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_c2NyaXB0cy9nZW5lcmF0ZV9kYl9oZWxwZXJzLmdv 100644 --- a/scripts/generate_db_helpers.go +++ b/scripts/generate_db_helpers.go @@ -14,7 +14,7 @@ "github.com/fatih/structtag" ) -// Package is the top-level package +// Package is the top-level package. type Package struct { Name string @@ -39,7 +39,7 @@ return fields } -// DBStruct is a struct mapped to a table +// DBStruct is a struct mapped to a table. type DBStruct struct { Name string Tablename string @@ -48,8 +48,8 @@ } // HasTable returns true if this structure is only a top level db struct that -// has is associated to a table +// has is associated to a table. func (s DBStruct) HasTable() bool { return s.Tablename != "" } @@ -52,9 +52,9 @@ func (s DBStruct) HasTable() bool { return s.Tablename != "" } -// IsEmbedded returns true if this structure is only embedded in other db structs +// IsEmbedded returns true if this structure is only embedded in other db structs. func (s DBStruct) IsEmbedded() bool { return s.Tablename == "" } @@ -57,8 +57,8 @@ func (s DBStruct) IsEmbedded() bool { return s.Tablename == "" } -// DBField is a field of a DBStruct +// DBField is a field of a DBStruct. type DBField struct { Name string Column string @@ -66,9 +66,7 @@ } func main() { - var ( - outputname = "db_helpers.go" - ) + outputname := "db_helpers.go" if len(os.Args) > 2 && os.Args[1] == "-o" { outputname = os.Args[2] @@ -128,7 +126,7 @@ return strings.Compare(topLevel.DBStructs[i].Name, topLevel.DBStructs[j].Name) < 0 }) - out, err := os.OpenFile(outputname, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0666) + out, err := os.OpenFile(outputname, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0o666) if err != nil { panic(err) } @@ -259,8 +257,7 @@ return dbfields, nil } -var ( - headTmpl = template.Must(template.New("head").Parse(`// This file is generated by 'gendbfiles' - DO NOT EDIT +var headTmpl = template.Must(template.New("head").Parse(`// This file is generated by 'gendbfiles' - DO NOT EDIT package {{.Name}} @@ -603,4 +600,3 @@ var Schema = NewDBSchema() `)) -) diff --git a/sentry.go b/sentry.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_c2VudHJ5Lmdv..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_c2VudHJ5Lmdv 100644 --- a/sentry.go +++ b/sentry.go @@ -33,7 +33,7 @@ func(next io.Writer) io.Writer { return SentryLogger{hub, next, &sentryOptions} }) - //OnShutdown(func() { + // OnShutdown(func() { //hub.Flush(time.Second) //}) } diff --git a/server.go b/server.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_c2VydmVyLmdv..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_c2VydmVyLmdv 100644 --- a/server.go +++ b/server.go @@ -25,7 +25,7 @@ "golang.org/x/net/netutil" ) -// API is a configured api +// API is a configured api. type API interface { Name() string Handler() http.Handler @@ -48,7 +48,7 @@ } } -// NewServer creates a new api server but does not configure it +// NewServer creates a new api server but does not configure it. func NewServer(api API) *Server { s := new(Server) @@ -58,7 +58,7 @@ return s } -// Server for the API +// Server for the API. type Server struct { EnabledListeners []string `long:"scheme" description:"the listeners to enable, this can be repeated and defaults to the schemes in the swagger spec"` CleanupTimeout time.Duration `long:"cleanup-timeout" description:"grace period for which to wait before killing idle connections" default:"10s"` @@ -101,7 +101,7 @@ interrupt chan os.Signal } -// SetLog sets the server logger +// SetLog sets the server logger. func (s *Server) SetLog(log zerolog.Logger) { s.log = log } @@ -112,8 +112,8 @@ } // Fatalf logs message either via defined user logger or via system one if no user logger is defined. -// Exits with non-zero status after printing +// Exits with non-zero status after printing. func (s *Server) Fatalf(f string, args ...interface{}) { s.log.Fatal().Msgf(f, args...) } @@ -116,8 +116,8 @@ func (s *Server) Fatalf(f string, args ...interface{}) { s.log.Fatal().Msgf(f, args...) } -// SetAPI configures the server with the specified API. Needs to be called before Serve +// SetAPI configures the server with the specified API. Needs to be called before Serve. func (s *Server) SetAPI(api API) { if api == nil { s.api = nil @@ -142,7 +142,7 @@ return false } -// Serve the api +// Serve the api. func (s *Server) Serve() (err error) { if !s.hasListeners { if err = s.Listen(); err != nil { @@ -174,7 +174,7 @@ domainSocket.IdleTimeout = s.CleanupTimeout } - //configureServer(domainSocket, "unix", string(s.SocketPath)) + // configureServer(domainSocket, "unix", string(s.SocketPath)) servers = append(servers, domainSocket) wg.Add(1) @@ -204,7 +204,7 @@ httpServer.Handler = s.handler - //configureServer(httpServer, "http", s.httpServerL.Addr().String()) + // configureServer(httpServer, "http", s.httpServerL.Addr().String()) servers = append(servers, httpServer) wg.Add(1) @@ -280,7 +280,7 @@ } // call custom TLS configurator - //configureTLS(httpsServer.TLSConfig) + // configureTLS(httpsServer.TLSConfig) if len(httpsServer.TLSConfig.Certificates) == 0 && httpsServer.TLSConfig.GetCertificate == nil { // after standard and custom config are passed, this ends up with no certificate @@ -300,7 +300,7 @@ // must have at least one certificate or panics // httpsServer.TLSConfig.BuildNameToCertificate() - //configureServer(httpsServer, "https", s.httpsServerL.Addr().String()) + // configureServer(httpsServer, "https", s.httpsServerL.Addr().String()) servers = append(servers, httpsServer) wg.Add(1) @@ -321,7 +321,7 @@ return nil } -// Listen creates the listeners for the server +// Listen creates the listeners for the server. func (s *Server) Listen() error { if s.hasListeners { // already done this return nil @@ -392,7 +392,7 @@ return nil } -// Shutdown server and clean up resources +// Shutdown server and clean up resources. func (s *Server) Shutdown() error { if atomic.CompareAndSwapInt32(&s.shuttingDown, 0, 1) { close(s.shutdown) @@ -442,8 +442,8 @@ } } -// GetHandler returns a handler useful for testing +// GetHandler returns a handler useful for testing. func (s *Server) GetHandler() http.Handler { return s.handler } @@ -446,8 +446,8 @@ func (s *Server) GetHandler() http.Handler { return s.handler } -// SetHandler allows for setting a http handler on this server +// SetHandler allows for setting a http handler on this server. func (s *Server) SetHandler(handler http.Handler) { s.handler = handler if s.Prometheus { @@ -455,7 +455,7 @@ } } -// UnixListener returns the domain socket listener +// UnixListener returns the domain socket listener. func (s *Server) UnixListener() (net.Listener, error) { if !s.hasListeners { if err := s.Listen(); err != nil { @@ -465,7 +465,7 @@ return s.domainSocketL, nil } -// HTTPListener returns the http listener +// HTTPListener returns the http listener. func (s *Server) HTTPListener() (net.Listener, error) { if !s.hasListeners { if err := s.Listen(); err != nil { @@ -475,7 +475,7 @@ return s.httpServerL, nil } -// TLSListener returns the https listener +// TLSListener returns the https listener. func (s *Server) TLSListener() (net.Listener, error) { if !s.hasListeners { if err := s.Listen(); err != nil { diff --git a/testutils/logger.go b/testutils/logger.go index 8486acd355b7e4eac35ef178cb3584dbbffa137e_dGVzdHV0aWxzL2xvZ2dlci5nbw==..6b5f31e47bbc0d52f36dc45ef5a9e673878e7ab4_dGVzdHV0aWxzL2xvZ2dlci5nbw== 100644 --- a/testutils/logger.go +++ b/testutils/logger.go @@ -7,8 +7,8 @@ "github.com/rs/zerolog" ) -// NewTestLogger creates a TestLogger +// NewTestLogger creates a TestLogger. func NewTestLogger(tb testing.TB) *TestLogger { return &TestLogger{tb} } @@ -11,9 +11,9 @@ func NewTestLogger(tb testing.TB) *TestLogger { return &TestLogger{tb} } -// TestLogger logs to a t.Log function +// TestLogger logs to a t.Log function. type TestLogger struct { tb testing.TB } @@ -16,8 +16,8 @@ type TestLogger struct { tb testing.TB } -// Logger returns a zerolog Logger +// Logger returns a zerolog Logger. func (tl *TestLogger) Logger() zerolog.Logger { level := zerolog.DebugLevel if os.Getenv("TEST_TRACE") != "" { @@ -31,10 +31,10 @@ Level(level) } -// Write writes the given string to t.Logf +// Write writes the given string to t.Logf. func (tl *TestLogger) Write(m []byte) (int, error) { tl.tb.Logf(string(m)) return len(m), nil } // SetTB changes the current TB, and returns a function to get back to the @@ -35,10 +35,10 @@ func (tl *TestLogger) Write(m []byte) (int, error) { tl.tb.Logf(string(m)) return len(m), nil } // SetTB changes the current TB, and returns a function to get back to the -// previous one +// previous one. func (tl *TestLogger) SetTB(tb testing.TB) func() { otb := tl.tb tl.tb = tb @@ -47,7 +47,7 @@ } } -// GetLogger returns a test Logger +// GetLogger returns a test Logger. func GetLogger(tb testing.TB) zerolog.Logger { return NewTestLogger(tb).Logger() }