use embedded structs where they were used before

Signed-off-by: Mohammed Al Sahaf <msaa1990@gmail.com>
This commit is contained in:
Mohammed Al Sahaf 2025-05-02 20:56:05 +03:00
parent 111fcddd56
commit 3cece4b644
No known key found for this signature in database
16 changed files with 33 additions and 33 deletions

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 // make path relative to the file of the _token_ being processed rather
// than current working directory (issue #867) and then use glob to get // than current working directory (issue #867) and then use glob to get
// list of matching filenames // list of matching filenames
absFile, err := caddy.FastAbs(p.File()) absFile, err := caddy.FastAbs(p.Dispenser.File())
if err != nil { if err != nil {
return p.Errf("Failed to get absolute path of file: %s: %v", p.File(), err) return p.Errf("Failed to get absolute path of file: %s: %v", p.Dispenser.File(), err)
} }
var matches []string 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) cl.WriterRaw = caddyconfig.JSONModuleObject(wo, "output", moduleName, h.warnings)
case "sampling": case "sampling":
d := h.NewFromNextSegment() d := h.Dispenser.NewFromNextSegment()
for d.NextArg() { for d.NextArg() {
// consume any tokens on the same line, if any. // consume any tokens on the same line, if any.
} }

View File

@ -247,7 +247,7 @@ func (h Helper) MatcherToken() (caddy.ModuleMap, bool, error) {
if !h.NextArg() { if !h.NextArg() {
return nil, false, nil return nil, false, nil
} }
return matcherSetFromMatcherToken(h.Token(), h.matcherDefs, h.warnings) return matcherSetFromMatcherToken(h.Dispenser.Token(), h.matcherDefs, h.warnings)
} }
// ExtractMatcherSet is like MatcherToken, except this is a higher-level // ExtractMatcherSet is like MatcherToken, except this is a higher-level
@ -266,9 +266,9 @@ func (h Helper) ExtractMatcherSet() (caddy.ModuleMap, error) {
// new dispenser should have been made // new dispenser should have been made
// solely for this directive's tokens, // solely for this directive's tokens,
// with no other uses of same slice // with no other uses of same slice
h.Delete() h.Dispenser.Delete()
} }
h.Reset() // pretend this lookahead never happened h.Dispenser.Reset() // pretend this lookahead never happened
return matcherSet, nil return matcherSet, nil
} }

View File

@ -302,7 +302,7 @@ type Flags struct {
// flag given by name. It panics if the flag is not // flag given by name. It panics if the flag is not
// in the flag set. // in the flag set.
func (f Flags) String(name string) string { func (f Flags) String(name string) string {
return f.Lookup(name).Value.String() return f.FlagSet.Lookup(name).Value.String()
} }
// Bool returns the boolean representation of the // Bool returns the boolean representation of the

View File

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

View File

@ -226,7 +226,7 @@ func (app *App) Emit(ctx caddy.Context, eventName string, data map[string]any) c
zap.String("origin", originModuleName)) zap.String("origin", originModuleName))
// add event info to replacer, make sure it's in the context // add event info to replacer, make sure it's in the context
repl, ok := ctx.Value(caddy.ReplacerCtxKey).(*caddy.Replacer) repl, ok := ctx.Context.Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
if !ok { if !ok {
repl = caddy.NewReplacer() repl = caddy.NewReplacer()
ctx.Context = context.WithValue(ctx.Context, caddy.ReplacerCtxKey, repl) ctx.Context = context.WithValue(ctx.Context, caddy.ReplacerCtxKey, repl)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -768,7 +768,7 @@ type tcpRWTimeoutConn struct {
func (c *tcpRWTimeoutConn) Read(b []byte) (int, error) { func (c *tcpRWTimeoutConn) Read(b []byte) (int, error) {
if c.readTimeout > 0 { if c.readTimeout > 0 {
err := c.SetReadDeadline(time.Now().Add(c.readTimeout)) err := c.TCPConn.SetReadDeadline(time.Now().Add(c.readTimeout))
if err != nil { if err != nil {
if ce := c.logger.Check(zapcore.ErrorLevel, "failed to set read deadline"); ce != nil { if ce := c.logger.Check(zapcore.ErrorLevel, "failed to set read deadline"); ce != nil {
ce.Write(zap.Error(err)) ce.Write(zap.Error(err))
@ -780,7 +780,7 @@ func (c *tcpRWTimeoutConn) Read(b []byte) (int, error) {
func (c *tcpRWTimeoutConn) Write(b []byte) (int, error) { func (c *tcpRWTimeoutConn) Write(b []byte) (int, error) {
if c.writeTimeout > 0 { if c.writeTimeout > 0 {
err := c.SetWriteDeadline(time.Now().Add(c.writeTimeout)) err := c.TCPConn.SetWriteDeadline(time.Now().Add(c.writeTimeout))
if err != nil { if err != nil {
if ce := c.logger.Check(zapcore.ErrorLevel, "failed to set write deadline"); ce != nil { if ce := c.logger.Check(zapcore.ErrorLevel, "failed to set write deadline"); ce != nil {
ce.Write(zap.Error(err)) 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.hostport", dialInfo.Address)
repl.Set("http.reverse_proxy.upstream.host", dialInfo.Host) repl.Set("http.reverse_proxy.upstream.host", dialInfo.Host)
repl.Set("http.reverse_proxy.upstream.port", dialInfo.Port) repl.Set("http.reverse_proxy.upstream.port", dialInfo.Port)
repl.Set("http.reverse_proxy.upstream.requests", upstream.NumRequests()) repl.Set("http.reverse_proxy.upstream.requests", upstream.Host.NumRequests())
repl.Set("http.reverse_proxy.upstream.max_requests", upstream.MaxRequests) repl.Set("http.reverse_proxy.upstream.max_requests", upstream.MaxRequests)
repl.Set("http.reverse_proxy.upstream.fails", upstream.Fails()) repl.Set("http.reverse_proxy.upstream.fails", upstream.Host.Fails())
// mutate request headers according to this upstream; // mutate request headers according to this upstream;
// because we're in a retry loop, we have to copy // 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 // (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.) // 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 { func (h *Handler) reverseProxy(rw http.ResponseWriter, req *http.Request, origReq *http.Request, repl *caddy.Replacer, di DialInfo, next caddyhttp.Handler) error {
_ = di.Upstream.countRequest(1) _ = di.Upstream.Host.countRequest(1)
//nolint:errcheck //nolint:errcheck
defer di.Upstream.countRequest(-1) defer di.Upstream.Host.countRequest(-1)
// point the request to this upstream // point the request to this upstream
h.directRequest(req, di) h.directRequest(req, di)

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 n, err = conn2.Write(b); err == nil {
if reconn.Conn != nil { if reconn.Conn != nil {
reconn.Close() reconn.Conn.Close()
} }
reconn.Conn = conn2 reconn.Conn = conn2
} }