run golangci-lint run --fix

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
This commit is contained in:
Mohammed Al Sahaf 2025-03-25 22:55:56 +03:00
parent fb467eb9a5
commit 9e284a5b0b
No known key found for this signature in database
31 changed files with 67 additions and 74 deletions

View File

@ -68,7 +68,7 @@ func (a Adapter) Adapt(body []byte, options map[string]any) ([]byte, []caddyconf
// TODO: also perform this check on imported files
func FormattingDifference(filename string, body []byte) (caddyconfig.Warning, bool) {
// replace windows-style newlines to normalize comparison
normalizedBody := bytes.Replace(body, []byte("\r\n"), []byte("\n"), -1)
normalizedBody := bytes.ReplaceAll(body, []byte("\r\n"), []byte("\n"))
formatted := Format(normalizedBody)
if bytes.Equal(formatted, normalizedBody) {

View File

@ -94,7 +94,7 @@ func Format(input []byte) []byte {
}
// detect whether we have the start of a heredoc
if !quoted && !(heredoc != heredocClosed || heredocEscaped) &&
if !quoted && (heredoc == heredocClosed && !heredocEscaped) &&
space && last == '<' && ch == '<' {
write(ch)
heredoc = heredocOpening

View File

@ -137,7 +137,7 @@ func (l *lexer) next() (bool, error) {
}
// detect whether we have the start of a heredoc
if !(quoted || btQuoted) && !(inHeredoc || heredocEscaped) &&
if (!quoted && !btQuoted) && (!inHeredoc && !heredocEscaped) &&
len(val) > 1 && string(val[:2]) == "<<" {
// a space means it's just a regular token and not a heredoc
if ch == ' ' {

View File

@ -423,9 +423,9 @@ func (p *parser) doImport(nesting int) error {
// make path relative to the file of the _token_ being processed rather
// than current working directory (issue #867) and then use glob to get
// list of matching filenames
absFile, err := caddy.FastAbs(p.Dispenser.File())
absFile, err := caddy.FastAbs(p.File())
if err != nil {
return p.Errf("Failed to get absolute path of file: %s: %v", p.Dispenser.File(), err)
return p.Errf("Failed to get absolute path of file: %s: %v", p.File(), err)
}
var matches []string

View File

@ -998,7 +998,7 @@ func parseLogHelper(h Helper, globalLogNames map[string]struct{}) ([]ConfigValue
cl.WriterRaw = caddyconfig.JSONModuleObject(wo, "output", moduleName, h.warnings)
case "sampling":
d := h.Dispenser.NewFromNextSegment()
d := h.NewFromNextSegment()
for d.NextArg() {
// consume any tokens on the same line, if any.
}

View File

@ -173,9 +173,10 @@ func RegisterDirectiveOrder(dir string, position Positional, standardDir string)
if d != standardDir {
continue
}
if position == Before {
switch position {
case Before:
newOrder = append(newOrder[:i], append([]string{dir}, newOrder[i:]...)...)
} else if position == After {
case After:
newOrder = append(newOrder[:i+1], append([]string{dir}, newOrder[i+1:]...)...)
}
break
@ -245,7 +246,7 @@ func (h Helper) MatcherToken() (caddy.ModuleMap, bool, error) {
if !h.NextArg() {
return nil, false, nil
}
return matcherSetFromMatcherToken(h.Dispenser.Token(), h.matcherDefs, h.warnings)
return matcherSetFromMatcherToken(h.Token(), h.matcherDefs, h.warnings)
}
// ExtractMatcherSet is like MatcherToken, except this is a higher-level
@ -264,9 +265,9 @@ func (h Helper) ExtractMatcherSet() (caddy.ModuleMap, error) {
// new dispenser should have been made
// solely for this directive's tokens,
// with no other uses of same slice
h.Dispenser.Delete()
h.Delete()
}
h.Dispenser.Reset() // pretend this lookahead never happened
h.Reset() // pretend this lookahead never happened
return matcherSet, nil
}

View File

@ -281,7 +281,7 @@ func validateTestPrerequisites(tc *Tester) error {
tc.t.Cleanup(func() {
os.Remove(f.Name())
})
if _, err := f.WriteString(fmt.Sprintf(initConfig, tc.config.AdminPort)); err != nil {
if _, err := fmt.Fprintf(f, initConfig, tc.config.AdminPort); err != nil {
return err
}

View File

@ -302,7 +302,7 @@ type Flags struct {
// flag given by name. It panics if the flag is not
// in the flag set.
func (f Flags) String(name string) string {
return f.FlagSet.Lookup(name).Value.String()
return f.Lookup(name).Value.String()
}
// Bool returns the boolean representation of the
@ -418,7 +418,7 @@ func parseEnvFile(envInput io.Reader) (map[string]string, error) {
// quoted value: support newlines
if strings.HasPrefix(val, `"`) || strings.HasPrefix(val, "'") {
quote := string(val[0])
for !(strings.HasSuffix(line, quote) && !strings.HasSuffix(line, `\`+quote)) {
for !strings.HasSuffix(line, quote) || strings.HasSuffix(line, `\`+quote) {
val = strings.ReplaceAll(val, `\`+quote, quote)
if !scanner.Scan() {
break

View File

@ -84,7 +84,7 @@ func cmdAddPackage(fl Flags) (int, error) {
return caddy.ExitCodeFailedStartup, fmt.Errorf("invalid module name: %v", err)
}
// only allow a version to be specified if it's different from the existing version
if _, ok := pluginPkgs[module]; ok && !(version != "" && pluginPkgs[module].Version != version) {
if _, ok := pluginPkgs[module]; ok && (version == "" || pluginPkgs[module].Version == version) {
return caddy.ExitCodeFailedStartup, fmt.Errorf("package is already added")
}
pluginPkgs[module] = pluginPackage{Version: version, Path: module}

View File

@ -574,7 +574,7 @@ type sharedQuicListener struct {
// Destruct closes the underlying QUIC listener and its associated net.PacketConn.
func (sql *sharedQuicListener) Destruct() error {
// close EarlyListener first to stop any operations being done to the net.PacketConn
_ = sql.EarlyListener.Close()
_ = sql.Close()
// then close the net.PacketConn
return sql.packetConn.Close()
}
@ -626,7 +626,7 @@ func (fcql *fakeCloseQuicListener) Accept(_ context.Context) (quic.EarlyConnecti
func (fcql *fakeCloseQuicListener) Close() error {
if atomic.CompareAndSwapInt32(&fcql.closed, 0, 1) {
fcql.contextCancel()
_, _ = listenerPool.Delete(fcql.sharedQuicListener.key)
_, _ = listenerPool.Delete(fcql.key)
}
return nil
}

View File

@ -151,17 +151,17 @@ func (logging *Logging) setupNewDefault(ctx Context) error {
}
// options for the default logger
options, err := newDefault.CustomLog.buildOptions()
options, err := newDefault.buildOptions()
if err != nil {
return fmt.Errorf("setting up default log: %v", err)
}
// set up this new log
err = newDefault.CustomLog.provision(ctx, logging)
err = newDefault.provision(ctx, logging)
if err != nil {
return fmt.Errorf("setting up default log: %v", err)
}
newDefault.logger = zap.New(newDefault.CustomLog.core, options...)
newDefault.logger = zap.New(newDefault.core, options...)
// redirect the default caddy logs
defaultLoggerMu.Lock()

View File

@ -229,7 +229,7 @@ func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) E
zap.String("origin", e.origin.CaddyModule().String()))
// add event info to replacer, make sure it's in the context
repl, ok := ctx.Context.Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
repl, ok := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
if !ok {
repl = caddy.NewReplacer()
ctx.Context = context.WithValue(ctx.Context, caddy.ReplacerCtxKey, repl)
@ -272,10 +272,7 @@ func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) E
moduleID := e.origin.CaddyModule().ID
// implement propagation up the module tree (i.e. start with "a.b.c" then "a.b" then "a" then "")
for {
if app.subscriptions[eventName] == nil {
break // shortcut if event not bound at all
}
for app.subscriptions[eventName] != nil {
for _, handler := range app.subscriptions[eventName][moduleID] {
select {

View File

@ -381,7 +381,7 @@ uniqueDomainsLoop:
// match on known domain names, unless it's our special case of a
// catch-all which is an empty string (common among catch-all sites
// that enable on-demand TLS for yet-unknown domain names)
if !(len(domains) == 1 && domains[0] == "") {
if len(domains) != 1 || domains[0] != "" {
matcherSet = append(matcherSet, MatchHost(domains))
}

View File

@ -329,14 +329,14 @@ func (pn celPkixName) ConvertToNative(typeDesc reflect.Type) (any, error) {
func (pn celPkixName) ConvertToType(typeVal ref.Type) ref.Val {
if typeVal.TypeName() == "string" {
return types.String(pn.Name.String())
return types.String(pn.String())
}
panic("not implemented")
}
func (pn celPkixName) Equal(other ref.Val) ref.Val {
if o, ok := other.Value().(string); ok {
return types.Bool(pn.Name.String() == o)
return types.Bool(pn.String() == o)
}
return types.ValOrErr(other, "%v is not comparable type", other)
}

View File

@ -252,7 +252,7 @@ func celFileMatcherMacroExpander() parser.MacroExpander {
}
for _, arg := range args {
if !(isCELStringLiteral(arg) || isCELCaddyPlaceholderCall(arg)) {
if !isCELStringLiteral(arg) && !isCELCaddyPlaceholderCall(arg) {
return nil, &common.Error{
Location: eh.OffsetLocation(arg.ID()),
Message: "matcher only supports repeated string literal arguments",
@ -616,15 +616,16 @@ func isCELTryFilesLiteral(e ast.Expr) bool {
return false
}
mapKeyStr := mapKey.AsLiteral().ConvertToType(types.StringType).Value()
if mapKeyStr == "try_files" || mapKeyStr == "split_path" {
switch mapKeyStr {
case "try_files", "split_path":
if !isCELStringListLiteral(mapVal) {
return false
}
} else if mapKeyStr == "try_policy" || mapKeyStr == "root" {
case "try_policy", "root":
if !(isCELStringExpr(mapVal)) {
return false
}
} else {
default:
return false
}
}

View File

@ -87,7 +87,7 @@ func parseCaddyfile(h httpcaddyfile.Helper) ([]httpcaddyfile.ConfigValue, error)
if err != nil {
return nil, h.Err(err.Error())
}
if len(handler.Response.HeaderOps.Delete) > 0 {
if len(handler.Response.Delete) > 0 {
handler.Response.Deferred = true
}
}

View File

@ -354,9 +354,9 @@ func (rww *responseWriterWrapper) WriteHeader(status int) {
if status < 100 || status > 199 {
rww.wroteHeader = true
}
if rww.require == nil || rww.require.Match(status, rww.ResponseWriterWrapper.Header()) {
if rww.require == nil || rww.require.Match(status, rww.Header()) {
if rww.headerOps != nil {
rww.headerOps.ApplyTo(rww.ResponseWriterWrapper.Header(), rww.replacer)
rww.headerOps.ApplyTo(rww.Header(), rww.replacer)
}
}
rww.ResponseWriterWrapper.WriteHeader(status)

View File

@ -548,10 +548,7 @@ func (MatchPath) matchPatternWithEscapeSequence(escapedPath, matchPath string) b
// increment iPath every time we consume a char from the path;
// iPattern and iPath are our cursors/iterator positions for each string
var iPattern, iPath int
for {
if iPattern >= len(matchPath) || iPath >= len(escapedPath) {
break
}
for iPattern < len(matchPath) && iPath < len(escapedPath) {
// get the next character from the request path

View File

@ -210,7 +210,7 @@ type linkPusher struct {
}
func (lp linkPusher) WriteHeader(statusCode int) {
if links, ok := lp.ResponseWriter.Header()["Link"]; ok {
if links, ok := lp.Header()["Link"]; ok {
// only initiate these pushes if it hasn't been done yet
if val := caddyhttp.GetVar(lp.request.Context(), pushedLink); val == nil {
if c := lp.handler.logger.Check(zapcore.DebugLevel, "pushing Link resources"); c != nil {

View File

@ -363,13 +363,13 @@ func addHTTPVarsToReplacer(repl *caddy.Replacer, req *http.Request, w http.Respo
}
}
switch {
case key == "http.shutting_down":
switch key {
case "http.shutting_down":
server := req.Context().Value(ServerCtxKey).(*Server)
server.shutdownAtMu.RLock()
defer server.shutdownAtMu.RUnlock()
return !server.shutdownAt.IsZero(), true
case key == "http.time_until_shutdown":
case "http.time_until_shutdown":
server := req.Context().Value(ServerCtxKey).(*Server)
server.shutdownAtMu.RLock()
defer server.shutdownAtMu.RUnlock()

View File

@ -158,7 +158,7 @@ func (rr *responseRecorder) WriteHeader(statusCode int) {
if rr.shouldBuffer == nil {
rr.stream = true
} else {
rr.stream = !rr.shouldBuffer(rr.statusCode, rr.ResponseWriterWrapper.Header())
rr.stream = !rr.shouldBuffer(rr.statusCode, rr.Header())
}
// 1xx responses aren't final; just informational

View File

@ -665,9 +665,10 @@ func (h *Handler) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
if d.NextArg() {
return d.ArgErr()
}
if subdir == "request_buffers" {
switch subdir {
case "request_buffers":
h.RequestBuffers = size
} else if subdir == "response_buffers" {
case "response_buffers":
h.ResponseBuffers = size
}

View File

@ -122,9 +122,10 @@ func cmdReverseProxy(fs caddycmd.Flags) (int, error) {
}
}
if fromAddr.Port == "" {
if fromAddr.Scheme == "http" {
switch fromAddr.Scheme {
case "http":
fromAddr.Port = httpPort
} else if fromAddr.Scheme == "https" {
case "https":
fromAddr.Port = httpsPort
}
}

View File

@ -451,7 +451,7 @@ func (h *Handler) doActiveHealthCheck(dialInfo DialInfo, hostAddr string, networ
markUnhealthy := func() {
// increment failures and then check if it has reached the threshold to mark unhealthy
err := upstream.Host.countHealthFail(1)
err := upstream.countHealthFail(1)
if err != nil {
if c := h.HealthChecks.Active.logger.Check(zapcore.ErrorLevel, "could not count active health failure"); c != nil {
c.Write(
@ -461,18 +461,18 @@ func (h *Handler) doActiveHealthCheck(dialInfo DialInfo, hostAddr string, networ
}
return
}
if upstream.Host.activeHealthFails() >= h.HealthChecks.Active.Fails {
if upstream.activeHealthFails() >= h.HealthChecks.Active.Fails {
// dispatch an event that the host newly became unhealthy
if upstream.setHealthy(false) {
h.events.Emit(h.ctx, "unhealthy", map[string]any{"host": hostAddr})
upstream.Host.resetHealth()
upstream.resetHealth()
}
}
}
markHealthy := func() {
// increment passes and then check if it has reached the threshold to be healthy
err := upstream.Host.countHealthPass(1)
err := upstream.countHealthPass(1)
if err != nil {
if c := h.HealthChecks.Active.logger.Check(zapcore.ErrorLevel, "could not count active health pass"); c != nil {
c.Write(
@ -482,13 +482,13 @@ func (h *Handler) doActiveHealthCheck(dialInfo DialInfo, hostAddr string, networ
}
return
}
if upstream.Host.activeHealthPasses() >= h.HealthChecks.Active.Passes {
if upstream.activeHealthPasses() >= h.HealthChecks.Active.Passes {
if upstream.setHealthy(true) {
if c := h.HealthChecks.Active.logger.Check(zapcore.InfoLevel, "host is up"); c != nil {
c.Write(zap.String("host", hostAddr))
}
h.events.Emit(h.ctx, "healthy", map[string]any{"host": hostAddr})
upstream.Host.resetHealth()
upstream.resetHealth()
}
}
}
@ -584,7 +584,7 @@ func (h *Handler) countFailure(upstream *Upstream) {
}
// count failure immediately
err := upstream.Host.countFail(1)
err := upstream.countFail(1)
if err != nil {
if c := h.HealthChecks.Active.logger.Check(zapcore.ErrorLevel, "could not count failure"); c != nil {
c.Write(

View File

@ -84,7 +84,7 @@ func (u *Upstream) Available() bool {
func (u *Upstream) Healthy() bool {
healthy := u.healthy()
if healthy && u.healthCheckPolicy != nil {
healthy = u.Host.Fails() < u.healthCheckPolicy.MaxFails
healthy = u.Fails() < u.healthCheckPolicy.MaxFails
}
if healthy && u.cb != nil {
healthy = u.cb.OK()
@ -95,7 +95,7 @@ func (u *Upstream) Healthy() bool {
// Full returns true if the remote host
// cannot receive more requests at this time.
func (u *Upstream) Full() bool {
return u.MaxRequests > 0 && u.Host.NumRequests() >= u.MaxRequests
return u.MaxRequests > 0 && u.NumRequests() >= u.MaxRequests
}
// fillDialInfo returns a filled DialInfo for upstream u, using the request

View File

@ -774,7 +774,7 @@ type tcpRWTimeoutConn struct {
func (c *tcpRWTimeoutConn) Read(b []byte) (int, error) {
if c.readTimeout > 0 {
err := c.TCPConn.SetReadDeadline(time.Now().Add(c.readTimeout))
err := c.SetReadDeadline(time.Now().Add(c.readTimeout))
if err != nil {
if ce := c.logger.Check(zapcore.ErrorLevel, "failed to set read deadline"); ce != nil {
ce.Write(zap.Error(err))
@ -786,7 +786,7 @@ func (c *tcpRWTimeoutConn) Read(b []byte) (int, error) {
func (c *tcpRWTimeoutConn) Write(b []byte) (int, error) {
if c.writeTimeout > 0 {
err := c.TCPConn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
err := c.SetWriteDeadline(time.Now().Add(c.writeTimeout))
if err != nil {
if ce := c.logger.Check(zapcore.ErrorLevel, "failed to set write deadline"); ce != nil {
ce.Write(zap.Error(err))

View File

@ -554,9 +554,9 @@ func (h *Handler) proxyLoopIteration(r *http.Request, origReq *http.Request, w h
repl.Set("http.reverse_proxy.upstream.hostport", dialInfo.Address)
repl.Set("http.reverse_proxy.upstream.host", dialInfo.Host)
repl.Set("http.reverse_proxy.upstream.port", dialInfo.Port)
repl.Set("http.reverse_proxy.upstream.requests", upstream.Host.NumRequests())
repl.Set("http.reverse_proxy.upstream.requests", upstream.NumRequests())
repl.Set("http.reverse_proxy.upstream.max_requests", upstream.MaxRequests)
repl.Set("http.reverse_proxy.upstream.fails", upstream.Host.Fails())
repl.Set("http.reverse_proxy.upstream.fails", upstream.Fails())
// mutate request headers according to this upstream;
// because we're in a retry loop, we have to copy
@ -827,9 +827,9 @@ func (h Handler) addForwardedHeaders(req *http.Request) error {
// (This method is mostly the beginning of what was borrowed from the net/http/httputil package in the
// Go standard library which was used as the foundation.)
func (h *Handler) reverseProxy(rw http.ResponseWriter, req *http.Request, origReq *http.Request, repl *caddy.Replacer, di DialInfo, next caddyhttp.Handler) error {
_ = di.Upstream.Host.countRequest(1)
_ = di.Upstream.countRequest(1)
//nolint:errcheck
defer di.Upstream.Host.countRequest(-1)
defer di.Upstream.countRequest(-1)
// point the request to this upstream
h.directRequest(req, di)
@ -1150,7 +1150,7 @@ func (lb LoadBalancing) tryAgain(ctx caddy.Context, start time.Time, retries int
// we have to assume the upstream received the request, and
// retries need to be carefully decided, because some requests
// are not idempotent
if !isDialError && !(isHandlerError && errors.Is(herr, errNoUpstream)) {
if !isDialError && (!isHandlerError || !errors.Is(herr, errNoUpstream)) {
if lb.RetryMatch == nil && req.Method != "GET" {
// by default, don't retry requests if they aren't GET
return false

View File

@ -808,7 +808,7 @@ func leastRequests(upstreams []*Upstream) *Upstream {
return nil
}
var best []*Upstream
var bestReqs int = -1
bestReqs := -1
for _, upstream := range upstreams {
if upstream == nil {
continue

View File

@ -377,10 +377,7 @@ func buildQueryString(qs string, repl *caddy.Replacer) string {
// performed in normalized/unescaped space.
func trimPathPrefix(escapedPath, prefix string) string {
var iPath, iPrefix int
for {
if iPath >= len(escapedPath) || iPrefix >= len(prefix) {
break
}
for iPath < len(escapedPath) && iPrefix < len(prefix) {
prefixCh := prefix[iPrefix]
ch := string(escapedPath[iPath])

View File

@ -388,10 +388,8 @@ func (ap *AutomationPolicy) onlyInternalIssuer() bool {
// isWildcardOrDefault determines if the subjects include any wildcard domains,
// or is the "default" policy (i.e. no subjects) which is unbounded.
func (ap *AutomationPolicy) isWildcardOrDefault() bool {
isWildcardOrDefault := false
if len(ap.subjects) == 0 {
isWildcardOrDefault = true
}
isWildcardOrDefault := len(ap.subjects) == 0
for _, sub := range ap.subjects {
if strings.HasPrefix(sub, "*") {
isWildcardOrDefault = true

View File

@ -202,7 +202,7 @@ func (reconn *redialerConn) Write(b []byte) (n int, err error) {
}
if n, err = conn2.Write(b); err == nil {
if reconn.Conn != nil {
reconn.Conn.Close()
reconn.Close()
}
reconn.Conn = conn2
}