chore: upgrade golangci-lint configuration and optimize codebase (#4236)

This PR includes the following changes:

- **Upgrade `.golangci.yml`**: Updated the configuration file to align
with the latest golangci-lint version, ensuring compatibility and
leveraging new features.
- **Refactor GitHub Action workflow**: Modified `golangci-lint.yml` in
the GitHub Actions workflow to reflect the updated configuration and
improve CI performance.
- **Codebase optimization**: Refactored code to address issues and
warnings raised by the updated golangci-lint rules, including:
  - Improved function length and complexity.
  - Enhanced error handling and variable naming conventions.
- Fixed minor issues such as unused imports and formatting
inconsistencies.

These changes aim to maintain code quality, ensure compatibility with
the latest tools, and improve overall maintainability.
This commit is contained in:
houseme
2025-08-22 13:29:09 +08:00
committed by GitHub
parent 24083b865d
commit 7ffdff37e4
33 changed files with 290 additions and 425 deletions

View File

@ -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.1.1
only-new-issues: true
skip-cache: true
github-token: ${{ secrets.GITHUB_TOKEN }}
args: --timeout 3m0s --config=.golangci.yml -v
args: --config=.golangci.yml -v

View File

@ -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: |

3
.gitignore vendored
View File

@ -23,4 +23,5 @@ go.work.sum
node_modules
.docusaurus
output
.example/
.example/
.golangci.bck.yml

View File

@ -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
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
go: "1.22"
modules-download-mode: readonly
issues-exit-code: 2
tests: false
allow-parallel-runners: true
allow-serial-runners: true
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$

View File

@ -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 {

View File

@ -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 {

View File

@ -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)

View File

@ -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)
})
}

View File

@ -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()

View File

@ -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

View File

@ -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)
}

View File

@ -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 {

View File

@ -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 ""
}

View File

@ -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--

View File

@ -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()
}

View File

@ -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,
})
}

View File

@ -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)
}

View File

@ -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))
}
}
}

View File

@ -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)
}

View File

@ -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 {

View File

@ -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.

View File

@ -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.

View File

@ -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 {

View File

@ -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)
}

View File

@ -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
}

View File

@ -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)
}

View File

@ -411,7 +411,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
}
@ -419,7 +419,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
}
@ -435,7 +435,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
}

View File

@ -246,7 +246,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
}
@ -355,7 +355,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.
//
@ -366,7 +366,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) {
@ -403,7 +403,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

View File

@ -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
}

View File

@ -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):

View File

@ -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.

View File

@ -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

View File

@ -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
}