From 7d3ec3ab1f61119652896e22fe11ce4b8857703e Mon Sep 17 00:00:00 2001 From: houseme Date: Tue, 8 Apr 2025 18:01:37 +0800 Subject: [PATCH 1/2] chore: upgrade golangci-lint configuration and optimize codebase - Update `.golangci.yml` to align with the latest golangci-lint version - Refactor GitHub Action workflow `golangci-lint.yml` for improved compatibility - Apply code improvements based on updated golangci-lint rules --- .github/workflows/golangci-lint.yml | 8 +- .github/workflows/release.yml | 2 +- .gitignore | 3 +- .golangci.yml | 516 +++++++----------- container/gmap/gmap_list_map.go | 6 +- database/gdb/gdb_model_with.go | 4 +- debug/gdebug/gdebug_grid.go | 4 +- debug/gdebug/gdebug_z_unit_test.go | 2 +- encoding/gjson/gjson.go | 6 +- encoding/gjson/gjson_api_new_load.go | 2 +- encoding/gjson/gjson_api_new_load_content.go | 20 +- encoding/gjson/gjson_implements.go | 2 +- internal/intlog/intlog.go | 10 +- net/gclient/gclient_request.go | 2 +- net/gclient/gclient_response.go | 4 +- net/ghttp/ghttp_request_param.go | 2 +- net/ghttp/ghttp_request_param_ctx.go | 4 +- net/ghttp/ghttp_response_write.go | 4 +- net/ghttp/ghttp_server_handler.go | 2 +- .../response/response_buffer_writer.go | 6 +- net/gipv4/gipv4_convert.go | 6 +- os/gcfg/gcfg_adapter_content.go | 5 +- os/gcron/gcron_schedule_check.go | 30 +- os/gfile/gfile_size.go | 9 +- os/gfsnotify/gfsnotify.go | 8 +- os/gfsnotify/gfsnotify_watcher.go | 6 +- os/gtime/gtime_time.go | 6 +- .../internal/converter/converter_scan.go | 8 +- .../internal/converter/converter_struct.go | 4 +- .../gconv/internal/structcache/structcache.go | 4 +- util/gtag/gtag_enums.go | 4 +- util/gutil/gutil_dump.go | 8 +- util/gvalid/internal/builtin/builtin_size.go | 2 +- 33 files changed, 287 insertions(+), 422 deletions(-) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 4e646ce4cbf..0febea161da 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -29,7 +29,7 @@ jobs: golang-ci: strategy: matrix: - go-version: [ 'stable' ] + go-version: [ "1.22", "1.23", "1.24" ] name: golang-ci-lint runs-on: ubuntu-latest @@ -41,11 +41,11 @@ jobs: with: go-version: ${{ matrix.go-version }} - name: golang-ci-lint - uses: golangci/golangci-lint-action@v6 + uses: golangci/golangci-lint-action@v7 with: # Required: specify the golangci-lint version without the patch version to always use the latest patch. - version: v1.64.5 + version: v2.0 only-new-issues: true skip-cache: true github-token: ${{ secrets.GITHUB_TOKEN }} - args: --timeout 3m0s --config=.golangci.yml -v + args: --config=.golangci.yml -v diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index b9729849cd6..f9d5a2824e8 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -21,7 +21,7 @@ jobs: - name: Set Up Golang Environment uses: actions/setup-go@v5 with: - go-version: 1.23.4 + go-version: 1.24.2 - name: Build CLI Binary run: | diff --git a/.gitignore b/.gitignore index bc6df0d61c2..964d5fdd0dd 100644 --- a/.gitignore +++ b/.gitignore @@ -23,4 +23,5 @@ go.work.sum node_modules .docusaurus output -.example/ \ No newline at end of file +.example/ +.golangci.bck.yml \ No newline at end of file diff --git a/.golangci.yml b/.golangci.yml index f1512b2b310..1747390ed25 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -1,325 +1,207 @@ -## This file contains all available configuration options -## with their default values. - -# See https://github.com/golangci/golangci-lint#config-file -# See https://golangci-lint.run/usage/configuration/ - -# Options for analysis running. +version: "2" run: - # Timeout for analysis, e.g. 30s, 5m. - # Default: 1m - timeout: 5m - # Exit code when at least one issue was found. - # Default: 1 + concurrency: 4 + go: "1.22" + modules-download-mode: readonly issues-exit-code: 2 - # Include test files or not. - # Default: true tests: false - # List of build tags, all linters use it. - # Default: [] - build-tags: [] - # If set, we pass it to "go list -mod={option}". From "go help modules": - # If invoked with -mod=readonly, the go command is disallowed from the implicit - # automatic updating of go.mod described above. Instead, it fails when any changes - # to go.mod are needed. This setting is most useful to check that go.mod does - # not need updates, such as in a continuous integration and testing system. - # If invoked with -mod=vendor, the go command assumes that the vendor - # directory holds the correct copies of dependencies and ignores - # the dependency descriptions in go.mod. - # - # Allowed values: readonly|vendor|mod - # Default: "" - modules-download-mode: readonly - # Allow multiple parallel golangci-lint instances running. - # If false, golangci-lint acquires file lock on start. - # Default: false allow-parallel-runners: true - # Allow multiple golangci-lint instances running, but serialize them around a lock. - # If false, golangci-lint exits with an error if it fails to acquire file lock on start. - # Default: false allow-serial-runners: true - # Define the Go version limit. - # Mainly related to generics support since go1.18. - # Default: use Go version from the go.mod file, fallback on the env var `GOVERSION`, fallback on 1.17 - go: '1.20' - # Number of operating system threads (`GOMAXPROCS`) that can execute golangci-lint simultaneously. - # If it is explicitly set to 0 (i.e. not the default) then golangci-lint will automatically set the value to match Linux container CPU quota. - # Default: the number of logical CPUs in the machine - concurrency: 4 - - -# Main linters configurations. -# See https://golangci-lint.run/usage/linters linters: - # Disable all default enabled linters. - disable-all: true - # Custom enable linters we want to use. + default: none enable: - - errcheck # Errcheck is a program for checking for unchecked errors in go programs. - - errchkjson # Checks types passed to the JSON encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted. - - funlen # Tool for detection of long functions - - gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification - - goimports # Check import statements are formatted according to the 'goimport' command. Reformat imports in autofix mode. - - gci # Gci controls Go package import order and makes it always deterministic. - - goconst # Finds repeated strings that could be replaced by a constant - - gocritic # Provides diagnostics that check for bugs, performance and style issues. - - gosimple # Linter for Go source code that specializes in simplifying code - - govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string - - misspell # Finds commonly misspelled English words in comments - - nolintlint # Reports ill-formed or insufficient nolint directives - - revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. - - staticcheck # It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary. - - typecheck # Like the front-end of a Go compiler, parses and type-checks Go code - - usestdlibvars # A linter that detect the possibility to use variables/constants from the Go standard library. - - whitespace # Tool for detection of leading and trailing whitespace - - -issues: - exclude-rules: - # helpers in tests often (rightfully) pass a *testing.T as their first argument - - path: _test\.go - text: "context.Context should be the first parameter of a function" - linters: - - revive - # Yes, they are, but it's okay in a test - - path: _test\.go - text: "exported func.*returns unexported type.*which can be annoying to use" - linters: - - revive - # https://github.com/go-critic/go-critic/issues/926 - - linters: - - gocritic - text: "unnecessaryDefer:" - - -# https://golangci-lint.run/usage/linters -linters-settings: - # https://golangci-lint.run/usage/linters/#misspell - misspell: - locale: US - ignore-words: - - cancelled - # https://golangci-lint.run/usage/linters/#gofmt - gofmt: - # Simplify code: gofmt with `-s` option. - # Default: true - simplify: true - # Apply the rewrite rules to the source before reformatting. - # https://pkg.go.dev/cmd/gofmt - # Default: [] - rewrite-rules: [ ] - # - pattern: 'interface{}' - # replacement: 'any' - # - pattern: 'a[b:len(a)]' - # replacement: 'a[b:]' - goimports: - # A comma-separated list of prefixes, which, if set, checks import paths - # with the given prefixes are grouped after 3rd-party packages. - # Default: "" - local-prefixes: github.com/gogf/gf/v2 - gci: - # Section configuration to compare against. - # Section names are case-insensitive and may contain parameters in (). - # The default order of sections is `standard > default > custom > blank > dot > alias > localmodule`, - # If `custom-order` is `true`, it follows the order of `sections` option. - # Default: ["standard", "default"] - sections: - - standard # Standard section: captures all standard packages. - - blank # Blank section: contains all blank imports. This section is not present unless explicitly enabled. - - default # Default section: contains all imports that could not be matched to another section type. - - dot # Dot section: contains all dot imports. This section is not present unless explicitly enabled. - # - alias # Alias section: contains all alias imports. This section is not present unless explicitly enabled. - # - localmodule # Local module section: contains all local packages. This section is not present unless explicitly enabled. - - prefix(github.com/gogf/gf) # Custom section: groups all imports with the specified Prefix. - - prefix(github.com/gogf/gf/cmd) # Custom section: groups all imports with the specified Prefix. - - prefix(github.com/gogf/gfcontrib) # Custom section: groups all imports with the specified Prefix. - - prefix(github.com/gogf/gf/example) # Custom section: groups all imports with the specified Prefix. - # Skip generated files. - # Default: true - skip-generated: true - # Enable custom order of sections. - # If `true`, make the section order the same as the order of `sections`. - # Default: false - custom-order: true - # Drops lexical ordering for custom sections. - # Default: false - no-lex-order: false - # https://golangci-lint.run/usage/linters/#revive - # https://github.com/mgechev/revive/blob/master/RULES_DESCRIPTIONS.md - revive: - ignore-generated-header: true - severity: error + - errcheck + - errchkjson + - funlen + - goconst + - gocritic + - govet + - misspell + - nolintlint + - revive + - staticcheck + - usestdlibvars + - whitespace + settings: + funlen: + lines: 340 + statements: -1 + goconst: + match-constant: false + min-len: 4 + min-occurrences: 30 + numbers: true + min: 5 + max: 20 + ignore-calls: false + gocritic: + disabled-checks: + - ifElseChain + - assignOp + - appendAssign + - singleCaseSwitch + - regexpMust + - typeSwitchVar + - elseif + govet: + disable: + - asmdecl + - assign + - atomic + - atomicalign + - bools + - buildtag + - cgocall + - composites + - copylocks + - deepequalerrors + - errorsas + - fieldalignment + - findcall + - framepointer + - httpresponse + - ifaceassert + - loopclosure + - lostcancel + - nilfunc + - nilness + - reflectvaluecompare + - shift + - shadow + - sigchanyzer + - sortslice + - stdmethods + - stringintconv + - structtag + - testinggoroutine + - tests + - unmarshal + - unreachable + - unsafeptr + - unusedwrite + enable-all: true + settings: + printf: + funcs: + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf + - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf + unusedresult: + funcs: + - pkg.MyFunc + - context.WithCancel + stringmethods: + - MyMethod + misspell: + locale: US + ignore-rules: + - cancelled + revive: + severity: error + rules: + - name: atomic + - name: line-length-limit + arguments: + - 380 + severity: error + - name: unhandled-error + severity: warning + disabled: true + - name: var-naming + arguments: + - - ID + - URL + - IP + - HTTP + - JSON + - API + - UID + - Id + - Api + - Uid + - Http + - Json + - Ip + - Url + - - VM + severity: warning + disabled: true + - name: string-format + arguments: + - - core.WriteError[1].Message + - /^([^A-Z]|$)/ + - must not start with a capital letter + - - fmt.Errorf[0] + - /(^|[^\.!?])$/ + - must not end in punctuation + - - panic + - /^[^\n]*$/ + - must not contain line breaks + severity: warning + disabled: false + - name: function-result-limit + arguments: + - 4 + severity: warning + disabled: false + staticcheck: + checks: [ "all","-S1000","-S1009","-S1016","-S1023","-S1025","-S1029","-S1034","-S1040","-SA1016","-SA1019","-SA1029","-SA4006","-SA4015","-SA6003","-SA9003","-ST1003","-QF1001","-QF1002","-QF1003","-QF1006","-QF1007","-QF1008","-QF1011","-QF1012","-ST1011" ] + initialisms: [ "ACL", "API", "ASCII", "CPU", "CSS", "DNS", "EOF", "GUID", "HTML", "HTTP", "HTTPS", "ID", "IP", "JSON", "QPS", "RAM", "RPC", "SLA", "SMTP", "SQL", "SSH", "TCP", "TLS", "TTL", "UDP", "UI", "GID", "UID", "UUID", "URI", "URL", "UTF8", "VM", "XML", "XMPP", "XSRF", "XSS", "SIP", "RTP", "AMQP", "DB", "TS" ] + dot-import-whitelist: [ "fmt" ] + http-status-code-whitelist: [ "200", "400", "404", "500" ] + exclusions: + generated: lax + presets: + - comments + - common-false-positives + - legacy + - std-error-handling rules: - - name: atomic - - name: line-length-limit - severity: error - arguments: [ 380 ] - - name: unhandled-error - severity: warning - disabled: true - arguments: [] - - name: var-naming - severity: warning - disabled: true - arguments: - # AllowList - - [ "ID","URL","IP","HTTP","JSON","API","UID","Id","Api","Uid","Http","Json","Ip","Url" ] - # DenyList - - [ "VM" ] - - name: string-format - severity: warning - disabled: false - arguments: - - - 'core.WriteError[1].Message' - - '/^([^A-Z]|$)/' - - must not start with a capital letter - - - 'fmt.Errorf[0]' - - '/(^|[^\.!?])$/' - - must not end in punctuation - - - panic - - '/^[^\n]*$/' - - must not contain line breaks - - name: function-result-limit - severity: warning - disabled: false - arguments: [ 4 ] - - # https://golangci-lint.run/usage/linters/#funlen - funlen: - # Checks the number of lines in a function. - # If lower than 0, disable the check. - # Default: 60 - lines: 340 - # Checks the number of statements in a function. - # If lower than 0, disable the check. - # Default: 40 - statements: -1 - - # https://golangci-lint.run/usage/linters/#goconst - goconst: - # Minimal length of string constant. - # Default: 3 - min-len: 4 - # Minimum occurrences of constant string count to trigger issue. - # Default: 3 - # For subsequent optimization, the value is reduced. - min-occurrences: 30 - # Ignore test files. - # Default: false - ignore-tests: true - # Look for existing constants matching the values. - # Default: true - match-constant: false - # Search also for duplicated numbers. - # Default: false - numbers: true - # Minimum value, only works with goconst.numbers - # Default: 3 - min: 5 - # Maximum value, only works with goconst.numbers - # Default: 3 - max: 20 - # Ignore when constant is not used as function argument. - # Default: true - ignore-calls: false - - # https://golangci-lint.run/usage/linters/#gocritic - gocritic: - disabled-checks: - - ifElseChain - - assignOp - - appendAssign - - singleCaseSwitch - - regexpMust - - typeSwitchVar - - elseif - - # https://golangci-lint.run/usage/linters/#gosimple - gosimple: - # Sxxxx checks in https://staticcheck.io/docs/configuration/options/#checks - # Default: ["*"] - checks: [ - "all", "-S1000", "-S1001", "-S1002", "-S1008", "-S1009", "-S1016", "-S1023", "-S1025", "-S1029", "-S1034", "-S1040" - ] - - # https://golangci-lint.run/usage/linters/#govet - govet: - # Report about shadowed variables. - # Default: false - # check-shadowing: true - # Settings per analyzer. - settings: - # Analyzer name, run `go tool vet help` to see all analyzers. - printf: - # Comma-separated list of print function names to check (in addition to default, see `go tool vet help printf`). - # Default: [] - funcs: - - (github.com/golangci/golangci-lint/pkg/logutils.Log).Infof - - (github.com/golangci/golangci-lint/pkg/logutils.Log).Warnf - - (github.com/golangci/golangci-lint/pkg/logutils.Log).Errorf - - (github.com/golangci/golangci-lint/pkg/logutils.Log).Fatalf - # shadow: - # Whether to be strict about shadowing; can be noisy. - # Default: false - # strict: false - unusedresult: - # Comma-separated list of functions whose results must be used - # (in addition to defaults context.WithCancel,context.WithDeadline,context.WithTimeout,context.WithValue, - # errors.New,fmt.Errorf,fmt.Sprint,fmt.Sprintf,sort.Reverse) - # Default [] - funcs: - - pkg.MyFunc - - context.WithCancel - # Comma-separated list of names of methods of type func() string whose results must be used - # (in addition to default Error,String) - # Default [] - stringmethods: - - MyMethod - # Enable all analyzers. - # Default: false - enable-all: true - # Disable analyzers by name. - # Run `go tool vet help` to see all analyzers. - # Default: [] - disable: - - asmdecl - - assign - - atomic - - atomicalign - - bools - - buildtag - - cgocall - - composites - - copylocks - - deepequalerrors - - errorsas - - fieldalignment - - findcall - - framepointer - - httpresponse - - ifaceassert - - loopclosure - - lostcancel - - nilfunc - - nilness - - reflectvaluecompare - - shift - - shadow - - sigchanyzer - - sortslice - - stdmethods - - stringintconv - - structtag - - testinggoroutine - - tests - - unmarshal - - unreachable - - unsafeptr - - unusedwrite - - # https://golangci-lint.run/usage/linters/#staticcheck - staticcheck: - # SAxxxx checks in https://staticcheck.io/docs/configuration/options/#checks - # Default: ["*"] - checks: [ "all","-SA1019","-SA4015","-SA1029","-SA1016","-SA9003","-SA4006","-SA6003" ] - + - linters: + - revive + path: _test\.go + text: context.Context should be the first parameter of a function + - linters: + - revive + path: _test\.go + text: exported func.*returns unexported type.*which can be annoying to use + - linters: + - gocritic + text: 'unnecessaryDefer:' + - linters: + - goconst + path: (.+)_test\.go + paths: + - third_party$ + - builtin$ + - examples$ +formatters: + enable: + - gci + - gofmt + - goimports + settings: + gci: + sections: + - standard + - blank + - default + - dot + - prefix(github.com/gogf/gf) + - prefix(github.com/gogf/gf/cmd) + - prefix(github.com/gogf/gfcontrib) + - prefix(github.com/gogf/gf/example) + custom-order: true + no-lex-order: false + gofmt: + simplify: true + goimports: + local-prefixes: + - github.com/gogf/gf/v2 + exclusions: + generated: lax + paths: + - third_party$ + - builtin$ + - examples$ diff --git a/container/gmap/gmap_list_map.go b/container/gmap/gmap_list_map.go index 3197a5cadb9..af2d66ec120 100644 --- a/container/gmap/gmap_list_map.go +++ b/container/gmap/gmap_list_map.go @@ -537,9 +537,9 @@ func (m ListMap) MarshalJSON() (jsonBytes []byte, err error) { buffer := bytes.NewBuffer(nil) buffer.WriteByte('{') m.Iterator(func(key, value interface{}) bool { - valueBytes, valueJsonErr := json.Marshal(value) - if valueJsonErr != nil { - err = valueJsonErr + valueBytes, valueJSONErr := json.Marshal(value) + if valueJSONErr != nil { + err = valueJSONErr return false } if buffer.Len() > 1 { diff --git a/database/gdb/gdb_model_with.go b/database/gdb/gdb_model_with.go index fcd36aeec9b..3f34167ee59 100644 --- a/database/gdb/gdb_model_with.go +++ b/database/gdb/gdb_model_with.go @@ -67,7 +67,7 @@ func (m *Model) WithAll() *Model { // doWithScanStruct handles model association operations feature for single struct. func (m *Model) doWithScanStruct(pointer interface{}) error { - if len(m.withArray) == 0 && m.withAll == false { + if len(m.withArray) == 0 && !m.withAll { return nil } var ( @@ -190,7 +190,7 @@ func (m *Model) doWithScanStruct(pointer interface{}) error { // doWithScanStructs handles model association operations feature for struct slice. // Also see doWithScanStruct. func (m *Model) doWithScanStructs(pointer interface{}) error { - if len(m.withArray) == 0 && m.withAll == false { + if len(m.withArray) == 0 && !m.withAll { return nil } if v, ok := pointer.(reflect.Value); ok { diff --git a/debug/gdebug/gdebug_grid.go b/debug/gdebug/gdebug_grid.go index 4d1aa8faad7..4b4fce0a720 100644 --- a/debug/gdebug/gdebug_grid.go +++ b/debug/gdebug/gdebug_grid.go @@ -15,10 +15,10 @@ import ( // gridRegex is the regular expression object for parsing goroutine id from stack information. var gridRegex = regexp.MustCompile(`^\w+\s+(\d+)\s+`) -// GoroutineId retrieves and returns the current goroutine id from stack information. +// GoroutineID retrieves and returns the current goroutine id from stack information. // Be very aware that, it is with low performance as it uses runtime.Stack function. // It is commonly used for debugging purpose. -func GoroutineId() int { +func GoroutineID() int { buf := make([]byte, 26) runtime.Stack(buf, false) match := gridRegex.FindSubmatch(buf) diff --git a/debug/gdebug/gdebug_z_unit_test.go b/debug/gdebug/gdebug_z_unit_test.go index 0a8b0f84ff9..80affc1b4e1 100644 --- a/debug/gdebug/gdebug_z_unit_test.go +++ b/debug/gdebug/gdebug_z_unit_test.go @@ -72,7 +72,7 @@ func Test_PrintStack(t *testing.T) { func Test_GoroutineId(t *testing.T) { gtest.C(t, func(t *gtest.T) { - t.AssertGT(gdebug.GoroutineId(), 0) + t.AssertGT(gdebug.GoroutineID(), 0) }) } diff --git a/encoding/gjson/gjson.go b/encoding/gjson/gjson.go index e1f512067af..df11061306c 100644 --- a/encoding/gjson/gjson.go +++ b/encoding/gjson/gjson.go @@ -24,9 +24,9 @@ import ( type ContentType string const ( - ContentTypeJson ContentType = `json` + ContentTypeJSON ContentType = `json` ContentTypeJs ContentType = `js` - ContentTypeXml ContentType = `xml` + ContentTypeXML ContentType = `xml` ContentTypeIni ContentType = `ini` ContentTypeYaml ContentType = `yaml` ContentTypeYml ContentType = `yml` @@ -92,7 +92,7 @@ func (j *Json) setValue(pattern string, value interface{}, removed bool) error { } var ( pparent *interface{} = nil // Parent pointer. - pointer *interface{} = j.p // Current pointer. + pointer = j.p // Current pointer. ) j.mu.Lock() defer j.mu.Unlock() diff --git a/encoding/gjson/gjson_api_new_load.go b/encoding/gjson/gjson_api_new_load.go index 113e0dc9650..48b9538c3df 100644 --- a/encoding/gjson/gjson_api_new_load.go +++ b/encoding/gjson/gjson_api_new_load.go @@ -20,7 +20,7 @@ import ( // The parameter `safe` specifies whether using this Json object in concurrent-safe context, // which is false in default. func New(data interface{}, safe ...bool) *Json { - return NewWithTag(data, string(ContentTypeJson), safe...) + return NewWithTag(data, string(ContentTypeJSON), safe...) } // NewWithTag creates a Json object with any variable type of `data`, but `data` should be a map diff --git a/encoding/gjson/gjson_api_new_load_content.go b/encoding/gjson/gjson_api_new_load_content.go index 7ddda24c11d..a2329ad87ed 100644 --- a/encoding/gjson/gjson_api_new_load_content.go +++ b/encoding/gjson/gjson_api_new_load_content.go @@ -29,7 +29,7 @@ func LoadWithOptions(data []byte, options Options) (*Json, error) { // LoadJson creates a Json object from given JSON format content. func LoadJson(data []byte, safe ...bool) (*Json, error) { var option = Options{ - Type: ContentTypeJson, + Type: ContentTypeJSON, } if len(safe) > 0 && safe[0] { option.Safe = true @@ -40,7 +40,7 @@ func LoadJson(data []byte, safe ...bool) (*Json, error) { // LoadXml creates a Json object from given XML format content. func LoadXml(data []byte, safe ...bool) (*Json, error) { var option = Options{ - Type: ContentTypeXml, + Type: ContentTypeXML, } if len(safe) > 0 && safe[0] { option.Safe = true @@ -126,9 +126,9 @@ func IsValidDataType(dataType ContentType) bool { } switch dataType { case - ContentTypeJson, + ContentTypeJSON, ContentTypeJs, - ContentTypeXml, + ContentTypeXML, ContentTypeYaml, ContentTypeYml, ContentTypeToml, @@ -171,9 +171,9 @@ func loadContentWithOptions(data []byte, options Options) (*Json, error) { string(options.Type), "."), ) switch options.Type { - case ContentTypeJson, ContentTypeJs: + case ContentTypeJSON, ContentTypeJs: - case ContentTypeXml: + case ContentTypeXML: data, err = gxml.ToJson(data) case ContentTypeYaml, ContentTypeYml: @@ -221,10 +221,10 @@ func loadContentWithOptions(data []byte, options Options) (*Json, error) { func checkDataType(data []byte) (ContentType, error) { switch { case json.Valid(data): - return ContentTypeJson, nil + return ContentTypeJSON, nil - case isXmlContent(data): - return ContentTypeXml, nil + case isXMLContent(data): + return ContentTypeXML, nil case isYamlContent(data): return ContentTypeYaml, nil @@ -247,7 +247,7 @@ func checkDataType(data []byte) (ContentType, error) { } } -func isXmlContent(data []byte) bool { +func isXMLContent(data []byte) bool { return gregex.IsMatch(`^\s*<.+>[\S\s]+<.+>\s*$`, data) } diff --git a/encoding/gjson/gjson_implements.go b/encoding/gjson/gjson_implements.go index 06ce213da0b..377b4f2cace 100644 --- a/encoding/gjson/gjson_implements.go +++ b/encoding/gjson/gjson_implements.go @@ -14,7 +14,7 @@ func (j Json) MarshalJSON() ([]byte, error) { // UnmarshalJSON implements the interface UnmarshalJSON for json.Unmarshal. func (j *Json) UnmarshalJSON(b []byte) error { r, err := loadContentWithOptions(b, Options{ - Type: ContentTypeJson, + Type: ContentTypeJSON, StrNumber: true, }) if r != nil { diff --git a/internal/intlog/intlog.go b/internal/intlog/intlog.go index e86380dc401..57541f06542 100644 --- a/internal/intlog/intlog.go +++ b/internal/intlog/intlog.go @@ -94,7 +94,7 @@ func doPrint(ctx context.Context, content string, stack bool) { buffer.WriteString(" [INTE] ") buffer.WriteString(file()) buffer.WriteString(" ") - if s := traceIdStr(ctx); s != "" { + if s := traceIDStr(ctx); s != "" { buffer.WriteString(s + " ") } buffer.WriteString(content) @@ -106,14 +106,14 @@ func doPrint(ctx context.Context, content string, stack bool) { fmt.Print(buffer.String()) } -// traceIdStr retrieves and returns the trace id string for logging output. -func traceIdStr(ctx context.Context) string { +// traceIDStr retrieves and returns the trace id string for logging output. +func traceIDStr(ctx context.Context) string { if ctx == nil { return "" } spanCtx := trace.SpanContextFromContext(ctx) - if traceId := spanCtx.TraceID(); traceId.IsValid() { - return "{" + traceId.String() + "}" + if traceID := spanCtx.TraceID(); traceID.IsValid() { + return "{" + traceID.String() + "}" } return "" } diff --git a/net/gclient/gclient_request.go b/net/gclient/gclient_request.go index be1c2ad0ffb..a4619f23ff2 100644 --- a/net/gclient/gclient_request.go +++ b/net/gclient/gclient_request.go @@ -371,7 +371,7 @@ func (c *Client) callRequest(req *http.Request) (resp *Response, err error) { err = gerror.Wrapf(err, `request failed`) // The response might not be nil when err != nil. if resp.Response != nil { - _ = resp.Response.Body.Close() + _ = resp.Body.Close() } if c.retryCount > 0 { c.retryCount-- diff --git a/net/gclient/gclient_response.go b/net/gclient/gclient_response.go index 0b599d077af..4dbeeab25e4 100644 --- a/net/gclient/gclient_response.go +++ b/net/gclient/gclient_response.go @@ -57,7 +57,7 @@ func (r *Response) ReadAll() []byte { if r == nil || r.Response == nil { return []byte{} } - body, err := io.ReadAll(r.Response.Body) + body, err := io.ReadAll(r.Body) if err != nil { intlog.Errorf(r.request.Context(), `%+v`, err) return nil @@ -82,5 +82,5 @@ func (r *Response) Close() error { if r == nil || r.Response == nil { return nil } - return r.Response.Body.Close() + return r.Body.Close() } diff --git a/net/ghttp/ghttp_request_param.go b/net/ghttp/ghttp_request_param.go index 6e44814c049..e22113ee8a0 100644 --- a/net/ghttp/ghttp_request_param.go +++ b/net/ghttp/ghttp_request_param.go @@ -184,7 +184,7 @@ func (r *Request) GetBodyString() string { // Note that the request content is read from request BODY, not from any field of FORM. func (r *Request) GetJson() (*gjson.Json, error) { return gjson.LoadWithOptions(r.GetBody(), gjson.Options{ - Type: gjson.ContentTypeJson, + Type: gjson.ContentTypeJSON, StrNumber: true, }) } diff --git a/net/ghttp/ghttp_request_param_ctx.go b/net/ghttp/ghttp_request_param_ctx.go index 4d42205c7c2..ab127e954da 100644 --- a/net/ghttp/ghttp_request_param_ctx.go +++ b/net/ghttp/ghttp_request_param_ctx.go @@ -31,7 +31,7 @@ func (r *Request) Context() context.Context { // Inject Request object into context. ctx = context.WithValue(ctx, ctxKeyForRequest, r) // Update the values of the original HTTP request. - *r.Request = *r.Request.WithContext(ctx) + *r.Request = *r.WithContext(ctx) } return ctx } @@ -72,5 +72,5 @@ func (r *Request) GetCtxVar(key interface{}, def ...interface{}) *gvar.Var { func (r *Request) SetCtxVar(key interface{}, value interface{}) { var ctx = r.Context() ctx = context.WithValue(ctx, key, value) - *r.Request = *r.Request.WithContext(ctx) + *r.Request = *r.WithContext(ctx) } diff --git a/net/ghttp/ghttp_response_write.go b/net/ghttp/ghttp_response_write.go index 1772c61a125..b5c41db62fd 100644 --- a/net/ghttp/ghttp_response_write.go +++ b/net/ghttp/ghttp_response_write.go @@ -30,9 +30,9 @@ func (r *Response) Write(content ...interface{}) { case []byte: _, _ = r.BufferWriter.Write(value) case string: - _, _ = r.BufferWriter.WriteString(value) + _, _ = r.WriteString(value) default: - _, _ = r.BufferWriter.WriteString(gconv.String(v)) + _, _ = r.WriteString(gconv.String(v)) } } } diff --git a/net/ghttp/ghttp_server_handler.go b/net/ghttp/ghttp_server_handler.go index 27ca64e14f9..7fb19d34bda 100644 --- a/net/ghttp/ghttp_server_handler.go +++ b/net/ghttp/ghttp_server_handler.go @@ -204,7 +204,7 @@ func (s *Server) handleAfterRequestDone(request *Request) { // Close the request and response body // to release the file descriptor in time. - err := request.Request.Body.Close() + err := request.Body.Close() if err != nil { intlog.Errorf(request.Context(), `%+v`, err) } diff --git a/net/ghttp/internal/response/response_buffer_writer.go b/net/ghttp/internal/response/response_buffer_writer.go index 8b334d79049..1bf13920c96 100644 --- a/net/ghttp/internal/response/response_buffer_writer.go +++ b/net/ghttp/internal/response/response_buffer_writer.go @@ -74,15 +74,15 @@ func (w *BufferWriter) WriteHeader(status int) { // Flush outputs the buffer to clients and clears the buffer. func (w *BufferWriter) Flush() { - if w.Writer.IsHijacked() { + if w.IsHijacked() { return } - if w.Status != 0 && !w.Writer.IsHeaderWrote() { + if w.Status != 0 && !w.IsHeaderWrote() { w.Writer.WriteHeader(w.Status) } // Default status text output. - if w.Status != http.StatusOK && w.buffer.Len() == 0 && w.Writer.BytesWritten() == 0 { + if w.Status != http.StatusOK && w.buffer.Len() == 0 && w.BytesWritten() == 0 { w.buffer.WriteString(http.StatusText(w.Status)) } if w.buffer.Len() > 0 { diff --git a/net/gipv4/gipv4_convert.go b/net/gipv4/gipv4_convert.go index 47d82555c4f..30d2e939298 100644 --- a/net/gipv4/gipv4_convert.go +++ b/net/gipv4/gipv4_convert.go @@ -16,11 +16,11 @@ import ( // IpToLongBigEndian converts ip address to an uint32 integer with big endian. func IpToLongBigEndian(ip string) uint32 { - netIp := net.ParseIP(ip) - if netIp == nil { + netIP := net.ParseIP(ip) + if netIP == nil { return 0 } - return binary.BigEndian.Uint32(netIp.To4()) + return binary.BigEndian.Uint32(netIP.To4()) } // LongToIpBigEndian converts an uint32 integer ip address to its string type address with big endian. diff --git a/os/gcfg/gcfg_adapter_content.go b/os/gcfg/gcfg_adapter_content.go index 9a0b12a2882..587d2a2f00d 100644 --- a/os/gcfg/gcfg_adapter_content.go +++ b/os/gcfg/gcfg_adapter_content.go @@ -51,10 +51,7 @@ func (a *AdapterContent) SetContent(content string) error { // Note that this function does not return error as it just does simply check for // backend configuration service. func (a *AdapterContent) Available(ctx context.Context, resource ...string) (ok bool) { - if a.jsonVar.IsNil() { - return false - } - return true + return !a.jsonVar.IsNil() } // Get retrieves and returns value by specified `pattern` in current resource. diff --git a/os/gcron/gcron_schedule_check.go b/os/gcron/gcron_schedule_check.go index 7c0069015cf..818cead36c6 100644 --- a/os/gcron/gcron_schedule_check.go +++ b/os/gcron/gcron_schedule_check.go @@ -26,10 +26,7 @@ func (s *cronSchedule) checkMeetAndUpdateLastSeconds(ctx context.Context, curren s.lastMeetTimestamp.Set(currentTime.Unix()) } }() - if !s.checkMinIntervalAndItemMapMeet(lastMeetTime.Time, lastCheckTime.Time, currentTime) { - return false - } - return true + return s.checkMinIntervalAndItemMapMeet(lastMeetTime.Time, lastCheckTime.Time, currentTime) } func (s *cronSchedule) checkMinIntervalAndItemMapMeet( @@ -83,38 +80,23 @@ func (s *cronSchedule) checkMeetSecond(lastMeetTime, currentTime time.Time) (ok } func (s *cronSchedule) checkMeetMinute(currentTime time.Time) (ok bool) { - if !s.keyMatch(s.minuteMap, currentTime.Minute()) { - return false - } - return true + return s.keyMatch(s.minuteMap, currentTime.Minute()) } func (s *cronSchedule) checkMeetHour(currentTime time.Time) (ok bool) { - if !s.keyMatch(s.hourMap, currentTime.Hour()) { - return false - } - return true + return s.keyMatch(s.hourMap, currentTime.Hour()) } func (s *cronSchedule) checkMeetDay(currentTime time.Time) (ok bool) { - if !s.keyMatch(s.dayMap, currentTime.Day()) { - return false - } - return true + return s.keyMatch(s.dayMap, currentTime.Day()) } func (s *cronSchedule) checkMeetMonth(currentTime time.Time) (ok bool) { - if !s.keyMatch(s.monthMap, int(currentTime.Month())) { - return false - } - return true + return s.keyMatch(s.monthMap, int(currentTime.Month())) } func (s *cronSchedule) checkMeetWeek(currentTime time.Time) (ok bool) { - if !s.keyMatch(s.weekMap, int(currentTime.Weekday())) { - return false - } - return true + return s.keyMatch(s.weekMap, int(currentTime.Weekday())) } func (s *cronSchedule) keyMatch(m map[int]struct{}, key int) bool { diff --git a/os/gfile/gfile_size.go b/os/gfile/gfile_size.go index fb8fca764b5..b2f549e01cb 100644 --- a/os/gfile/gfile_size.go +++ b/os/gfile/gfile_size.go @@ -76,9 +76,12 @@ func StrToSize(sizeStr string) int64 { // FormatSize formats size `raw` for more manually readable. func FormatSize(raw int64) string { - var r float64 = float64(raw) - var t float64 = 1024 - var d float64 = 1 + var ( + r = float64(raw) + t float64 = 1024 + d float64 = 1 + ) + if r < t { return fmt.Sprintf("%.2fB", r/d) } diff --git a/os/gfsnotify/gfsnotify.go b/os/gfsnotify/gfsnotify.go index 51f7c93ea07..2ff8f7eb0c4 100644 --- a/os/gfsnotify/gfsnotify.go +++ b/os/gfsnotify/gfsnotify.go @@ -149,19 +149,19 @@ func Remove(path string) error { } // RemoveCallback removes specified callback with given id from watcher. -func RemoveCallback(callbackId int) error { +func RemoveCallback(callbackID int) error { w, err := getDefaultWatcher() if err != nil { return err } callback := (*Callback)(nil) - if r := callbackIdMap.Get(callbackId); r != nil { + if r := callbackIdMap.Get(callbackID); r != nil { callback = r.(*Callback) } if callback == nil { - return gerror.NewCodef(gcode.CodeInvalidParameter, `callback for id %d not found`, callbackId) + return gerror.NewCodef(gcode.CodeInvalidParameter, `callback for id %d not found`, callbackID) } - w.RemoveCallback(callbackId) + w.RemoveCallback(callbackID) return nil } diff --git a/os/gfsnotify/gfsnotify_watcher.go b/os/gfsnotify/gfsnotify_watcher.go index 915e588c239..bb24e7465f0 100644 --- a/os/gfsnotify/gfsnotify_watcher.go +++ b/os/gfsnotify/gfsnotify_watcher.go @@ -182,16 +182,16 @@ func (w *Watcher) Remove(path string) error { // RemoveCallback removes callback with given callback id from watcher. // // Note that, it auto removes the path watching if there's no callback bound on it. -func (w *Watcher) RemoveCallback(callbackId int) { +func (w *Watcher) RemoveCallback(callbackID int) { callback := (*Callback)(nil) - if r := callbackIdMap.Get(callbackId); r != nil { + if r := callbackIdMap.Get(callbackID); r != nil { callback = r.(*Callback) } if callback != nil { if r := w.callbacks.Get(callback.Path); r != nil { r.(*glist.List).Remove(callback.elem) } - callbackIdMap.Remove(callbackId) + callbackIdMap.Remove(callbackID) if callback.name != "" { w.nameSet.Remove(callback.name) } diff --git a/os/gtime/gtime_time.go b/os/gtime/gtime_time.go index 388c4248f42..249efadd969 100644 --- a/os/gtime/gtime_time.go +++ b/os/gtime/gtime_time.go @@ -408,7 +408,7 @@ func (t *Time) StartOfMinute() *Time { func (t *Time) StartOfHour() *Time { y, m, d := t.Date() newTime := t.Clone() - newTime.Time = time.Date(y, m, d, newTime.Time.Hour(), 0, 0, 0, newTime.Time.Location()) + newTime.Time = time.Date(y, m, d, newTime.Hour(), 0, 0, 0, newTime.Location()) return newTime } @@ -416,7 +416,7 @@ func (t *Time) StartOfHour() *Time { func (t *Time) StartOfDay() *Time { y, m, d := t.Date() newTime := t.Clone() - newTime.Time = time.Date(y, m, d, 0, 0, 0, 0, newTime.Time.Location()) + newTime.Time = time.Date(y, m, d, 0, 0, 0, 0, newTime.Location()) return newTime } @@ -432,7 +432,7 @@ func (t *Time) StartOfWeek() *Time { func (t *Time) StartOfMonth() *Time { y, m, _ := t.Date() newTime := t.Clone() - newTime.Time = time.Date(y, m, 1, 0, 0, 0, 0, newTime.Time.Location()) + newTime.Time = time.Date(y, m, 1, 0, 0, 0, 0, newTime.Location()) return newTime } diff --git a/util/gconv/internal/converter/converter_scan.go b/util/gconv/internal/converter/converter_scan.go index 9630ffb2ab1..45ceadb6bc9 100644 --- a/util/gconv/internal/converter/converter_scan.go +++ b/util/gconv/internal/converter/converter_scan.go @@ -242,7 +242,7 @@ func (c *Converter) doScanForComplicatedTypes( option ScanOption, ) error { // Try JSON conversion first - ok, err := c.doConvertWithJsonCheck(srcValue, dstPointer) + ok, err := c.doConvertWithJSONCheck(srcValue, dstPointer) if err != nil { return err } @@ -351,7 +351,7 @@ func (c *Converter) doConvertWithTypeCheck(srcValueReflectValue, dstPointerRefle } } -// doConvertWithJsonCheck attempts to convert the source value to the destination +// doConvertWithJSONCheck attempts to convert the source value to the destination // using JSON marshaling and unmarshaling. This is particularly useful for complex // types that can be represented as JSON. // @@ -362,7 +362,7 @@ func (c *Converter) doConvertWithTypeCheck(srcValueReflectValue, dstPointerRefle // Returns: // - bool: true if JSON conversion was successful // - error: any error that occurred during conversion -func (c *Converter) doConvertWithJsonCheck(srcValue any, dstPointer any) (ok bool, err error) { +func (c *Converter) doConvertWithJSONCheck(srcValue any, dstPointer any) (ok bool, err error) { switch valueResult := srcValue.(type) { case []byte: if json.Valid(valueResult) { @@ -399,7 +399,7 @@ func (c *Converter) doConvertWithJsonCheck(srcValue any, dstPointer any) (ok boo default: // The `params` might be struct that implements interface function Interface, eg: gvar.Var. if v, ok := srcValue.(localinterface.IInterface); ok { - return c.doConvertWithJsonCheck(v.Interface(), dstPointer) + return c.doConvertWithJSONCheck(v.Interface(), dstPointer) } } return false, nil diff --git a/util/gconv/internal/converter/converter_struct.go b/util/gconv/internal/converter/converter_struct.go index 1a84e41b688..0c533fe7582 100644 --- a/util/gconv/internal/converter/converter_struct.go +++ b/util/gconv/internal/converter/converter_struct.go @@ -50,7 +50,7 @@ func (c *Converter) Struct(params, pointer any, option ...StructOption) (err err } // JSON content converting. - ok, err := c.doConvertWithJsonCheck(params, pointer) + ok, err := c.doConvertWithJSONCheck(params, pointer) if err != nil { return err } @@ -474,7 +474,7 @@ func bindVarToReflectValueWithInterfaceCheck(reflectValue reflect.Value, value a // bindVarToReflectValue sets `value` to reflect value object `structFieldValue`. func (c *Converter) bindVarToReflectValue(structFieldValue reflect.Value, value any, option StructOption) (err error) { // JSON content converting. - ok, err := c.doConvertWithJsonCheck(value, structFieldValue) + ok, err := c.doConvertWithJSONCheck(value, structFieldValue) if err != nil { return err } diff --git a/util/gconv/internal/structcache/structcache.go b/util/gconv/internal/structcache/structcache.go index 99f6d236287..ce3819a414c 100644 --- a/util/gconv/internal/structcache/structcache.go +++ b/util/gconv/internal/structcache/structcache.go @@ -109,7 +109,7 @@ func (cf *Converter) checkTypeImplInterface(t reflect.Type) AnyConvertFunc { var ( implUnmarshalText = reflect.TypeOf((*localinterface.IUnmarshalText)(nil)).Elem() - implUnmarshalJson = reflect.TypeOf((*localinterface.IUnmarshalJSON)(nil)).Elem() + implUnmarshalJSON = reflect.TypeOf((*localinterface.IUnmarshalJSON)(nil)).Elem() implUnmarshalValue = reflect.TypeOf((*localinterface.IUnmarshalValue)(nil)).Elem() ) @@ -131,7 +131,7 @@ func checkTypeIsCommonInterface(field reflect.StructField) bool { case field.Type.Implements(implUnmarshalText): isCommonInterface = true - case field.Type.Implements(implUnmarshalJson): + case field.Type.Implements(implUnmarshalJSON): isCommonInterface = true case field.Type.Implements(implUnmarshalValue): diff --git a/util/gtag/gtag_enums.go b/util/gtag/gtag_enums.go index 10a4dbe973c..b628c4731b0 100644 --- a/util/gtag/gtag_enums.go +++ b/util/gtag/gtag_enums.go @@ -15,8 +15,8 @@ var enumsMap = make(map[string]json.RawMessage) // SetGlobalEnums sets the global enums into package. // Note that this operation is not concurrent safety. -func SetGlobalEnums(enumsJson string) error { - return json.Unmarshal([]byte(enumsJson), &enumsMap) +func SetGlobalEnums(enumsJSON string) error { + return json.Unmarshal([]byte(enumsJSON), &enumsMap) } // GetGlobalEnums retrieves and returns the global enums. diff --git a/util/gutil/gutil_dump.go b/util/gutil/gutil_dump.go index 69282cf993f..9f3e7893002 100644 --- a/util/gutil/gutil_dump.go +++ b/util/gutil/gutil_dump.go @@ -476,20 +476,20 @@ func addSlashesForString(s string) string { func DumpJson(value any) { switch result := value.(type) { case []byte: - doDumpJson(result) + doDumpJSON(result) case string: - doDumpJson([]byte(result)) + doDumpJSON([]byte(result)) default: jsonContent, err := json.Marshal(value) if err != nil { fmt.Println(err.Error()) return } - doDumpJson(jsonContent) + doDumpJSON(jsonContent) } } -func doDumpJson(jsonContent []byte) { +func doDumpJSON(jsonContent []byte) { var ( buffer = bytes.NewBuffer(nil) jsonBytes = jsonContent diff --git a/util/gvalid/internal/builtin/builtin_size.go b/util/gvalid/internal/builtin/builtin_size.go index becf32b79a7..33281d4e551 100644 --- a/util/gvalid/internal/builtin/builtin_size.go +++ b/util/gvalid/internal/builtin/builtin_size.go @@ -40,7 +40,7 @@ func (r RuleSize) Run(in RunInput) error { ) size, err := strconv.Atoi(in.RulePattern) if valueLen != size || err != nil { - return errors.New(strings.Replace(in.Message, "{size}", strconv.Itoa(size), -1)) + return errors.New(strings.ReplaceAll(in.Message, "{size}", strconv.Itoa(size))) } return nil } From b827e6028bf7892b3e3ba381ebc1dd36e71f952e Mon Sep 17 00:00:00 2001 From: houseme Date: Sun, 13 Apr 2025 14:03:06 +0800 Subject: [PATCH 2/2] upgrade golangci-lint version 2.1.1 --- .github/workflows/golangci-lint.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/golangci-lint.yml b/.github/workflows/golangci-lint.yml index 0febea161da..0a3d63d1bea 100644 --- a/.github/workflows/golangci-lint.yml +++ b/.github/workflows/golangci-lint.yml @@ -44,7 +44,7 @@ jobs: uses: golangci/golangci-lint-action@v7 with: # Required: specify the golangci-lint version without the patch version to always use the latest patch. - version: v2.0 + version: v2.1.1 only-new-issues: true skip-cache: true github-token: ${{ secrets.GITHUB_TOKEN }}