diff options
author | Francis Lavoie <[email protected]> | 2024-09-25 16:30:56 -0400 |
---|---|---|
committer | GitHub <[email protected]> | 2024-09-25 14:30:56 -0600 |
commit | 2faeac0a104c72e9396717406ecb7c353bf9aa64 (patch) | |
tree | 5ae5bc9c450f5fb72ad618cac083f4cf8d71d139 /modules | |
parent | 9dda8fbf846db052243e6ce5ab707650da8c030e (diff) | |
download | caddy-2faeac0a104c72e9396717406ecb7c353bf9aa64.tar.gz caddy-2faeac0a104c72e9396717406ecb7c353bf9aa64.zip |
chore: Use slices package where possible (#6585)
* chore: Use slices package where possible
* More, mostly using ContainsFunc
* Even more slice operations
Diffstat (limited to 'modules')
-rw-r--r-- | modules/caddyevents/app.go | 25 | ||||
-rw-r--r-- | modules/caddyhttp/autohttps.go | 16 | ||||
-rw-r--r-- | modules/caddyhttp/encode/encode.go | 10 | ||||
-rw-r--r-- | modules/caddyhttp/fileserver/browsetplcontext.go | 10 | ||||
-rw-r--r-- | modules/caddyhttp/headers/headers.go | 13 | ||||
-rw-r--r-- | modules/caddyhttp/map/map.go | 14 | ||||
-rw-r--r-- | modules/caddyhttp/matchers.go | 7 | ||||
-rw-r--r-- | modules/caddyhttp/reverseproxy/healthchecks.go | 9 | ||||
-rw-r--r-- | modules/caddyhttp/reverseproxy/httptransport.go | 17 | ||||
-rw-r--r-- | modules/caddyhttp/server.go | 26 | ||||
-rw-r--r-- | modules/caddyhttp/templates/frontmatter.go | 1 | ||||
-rw-r--r-- | modules/caddytls/automation.go | 10 | ||||
-rw-r--r-- | modules/caddytls/certselection.go | 13 | ||||
-rw-r--r-- | modules/caddytls/matchers.go | 19 |
14 files changed, 65 insertions, 125 deletions
diff --git a/modules/caddyevents/app.go b/modules/caddyevents/app.go index fe76a6757..2e4a6f2c0 100644 --- a/modules/caddyevents/app.go +++ b/modules/caddyevents/app.go @@ -124,18 +124,19 @@ func (app *App) Provision(ctx caddy.Context) error { app.subscriptions = make(map[string]map[caddy.ModuleID][]Handler) for _, sub := range app.Subscriptions { - if sub.HandlersRaw != nil { - handlersIface, err := ctx.LoadModule(sub, "HandlersRaw") - if err != nil { - return fmt.Errorf("loading event subscriber modules: %v", err) - } - for _, h := range handlersIface.([]any) { - sub.Handlers = append(sub.Handlers, h.(Handler)) - } - if len(sub.Handlers) == 0 { - // pointless to bind without any handlers - return fmt.Errorf("no handlers defined") - } + if sub.HandlersRaw == nil { + continue + } + handlersIface, err := ctx.LoadModule(sub, "HandlersRaw") + if err != nil { + return fmt.Errorf("loading event subscriber modules: %v", err) + } + for _, h := range handlersIface.([]any) { + sub.Handlers = append(sub.Handlers, h.(Handler)) + } + if len(sub.Handlers) == 0 { + // pointless to bind without any handlers + return fmt.Errorf("no handlers defined") } } diff --git a/modules/caddyhttp/autohttps.go b/modules/caddyhttp/autohttps.go index 263cd14c7..ea5a07b3c 100644 --- a/modules/caddyhttp/autohttps.go +++ b/modules/caddyhttp/autohttps.go @@ -17,6 +17,7 @@ package caddyhttp import ( "fmt" "net/http" + "slices" "strconv" "strings" @@ -66,17 +67,6 @@ type AutoHTTPSConfig struct { IgnoreLoadedCerts bool `json:"ignore_loaded_certificates,omitempty"` } -// Skipped returns true if name is in skipSlice, which -// should be either the Skip or SkipCerts field on ahc. -func (ahc AutoHTTPSConfig) Skipped(name string, skipSlice []string) bool { - for _, n := range skipSlice { - if name == n { - return true - } - } - return false -} - // automaticHTTPSPhase1 provisions all route matchers, determines // which domain names found in the routes qualify for automatic // HTTPS, and sets up HTTP->HTTPS redirects. This phase must occur @@ -158,7 +148,7 @@ func (app *App) automaticHTTPSPhase1(ctx caddy.Context, repl *caddy.Replacer) er return fmt.Errorf("%s: route %d, matcher set %d, matcher %d, host matcher %d: %v", srvName, routeIdx, matcherSetIdx, matcherIdx, hostMatcherIdx, err) } - if !srv.AutoHTTPS.Skipped(d, srv.AutoHTTPS.Skip) { + if !slices.Contains(srv.AutoHTTPS.Skip, d) { serverDomainSet[d] = struct{}{} } } @@ -193,7 +183,7 @@ func (app *App) automaticHTTPSPhase1(ctx caddy.Context, repl *caddy.Replacer) er } else { for d := range serverDomainSet { if certmagic.SubjectQualifiesForCert(d) && - !srv.AutoHTTPS.Skipped(d, srv.AutoHTTPS.SkipCerts) { + !slices.Contains(srv.AutoHTTPS.SkipCerts, d) { // if a certificate for this name is already loaded, // don't obtain another one for it, unless we are // supposed to ignore loaded certificates diff --git a/modules/caddyhttp/encode/encode.go b/modules/caddyhttp/encode/encode.go index 00e507277..f0d56a90d 100644 --- a/modules/caddyhttp/encode/encode.go +++ b/modules/caddyhttp/encode/encode.go @@ -24,6 +24,7 @@ import ( "io" "math" "net/http" + "slices" "sort" "strconv" "strings" @@ -441,12 +442,9 @@ func AcceptedEncodings(r *http.Request, preferredOrder []string) []string { } // set server preference - prefOrder := -1 - for i, p := range preferredOrder { - if encName == p { - prefOrder = len(preferredOrder) - i - break - } + prefOrder := slices.Index(preferredOrder, encName) + if prefOrder > -1 { + prefOrder = len(preferredOrder) - prefOrder } prefs = append(prefs, encodingPreference{ diff --git a/modules/caddyhttp/fileserver/browsetplcontext.go b/modules/caddyhttp/fileserver/browsetplcontext.go index 37e1cc3dd..8e5d138f1 100644 --- a/modules/caddyhttp/fileserver/browsetplcontext.go +++ b/modules/caddyhttp/fileserver/browsetplcontext.go @@ -21,6 +21,7 @@ import ( "os" "path" "path/filepath" + "slices" "sort" "strconv" "strings" @@ -281,12 +282,9 @@ type fileInfo struct { // HasExt returns true if the filename has any of the given suffixes, case-insensitive. func (fi fileInfo) HasExt(exts ...string) bool { - for _, ext := range exts { - if strings.HasSuffix(strings.ToLower(fi.Name), strings.ToLower(ext)) { - return true - } - } - return false + return slices.ContainsFunc(exts, func(ext string) bool { + return strings.HasSuffix(strings.ToLower(fi.Name), strings.ToLower(ext)) + }) } // HumanSize returns the size of the file as a diff --git a/modules/caddyhttp/headers/headers.go b/modules/caddyhttp/headers/headers.go index bdb185f46..a3279d913 100644 --- a/modules/caddyhttp/headers/headers.go +++ b/modules/caddyhttp/headers/headers.go @@ -135,13 +135,14 @@ type HeaderOps struct { func (ops *HeaderOps) Provision(_ caddy.Context) error { for fieldName, replacements := range ops.Replace { for i, r := range replacements { - if r.SearchRegexp != "" { - re, err := regexp.Compile(r.SearchRegexp) - if err != nil { - return fmt.Errorf("replacement %d for header field '%s': %v", i, fieldName, err) - } - replacements[i].re = re + if r.SearchRegexp == "" { + continue + } + re, err := regexp.Compile(r.SearchRegexp) + if err != nil { + return fmt.Errorf("replacement %d for header field '%s': %v", i, fieldName, err) } + replacements[i].re = re } } return nil diff --git a/modules/caddyhttp/map/map.go b/modules/caddyhttp/map/map.go index 336f25723..d02085e76 100644 --- a/modules/caddyhttp/map/map.go +++ b/modules/caddyhttp/map/map.go @@ -18,6 +18,7 @@ import ( "fmt" "net/http" "regexp" + "slices" "strings" "github.com/caddyserver/caddy/v2" @@ -126,7 +127,7 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhtt // defer work until a variable is actually evaluated by using replacer's Map callback repl.Map(func(key string) (any, bool) { // return early if the variable is not even a configured destination - destIdx := h.destinationIndex(key) + destIdx := slices.Index(h.Destinations, key) if destIdx < 0 { return nil, false } @@ -170,17 +171,6 @@ func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhtt return next.ServeHTTP(w, r) } -// destinationIndex returns the positional index of the destination -// is name is a known destination; otherwise it returns -1. -func (h Handler) destinationIndex(name string) int { - for i, dest := range h.Destinations { - if dest == name { - return i - } - } - return -1 -} - // Mapping describes a mapping from input to outputs. type Mapping struct { // The input value to match. Must be distinct from other mappings. diff --git a/modules/caddyhttp/matchers.go b/modules/caddyhttp/matchers.go index b7952ab69..a0bc6d63a 100644 --- a/modules/caddyhttp/matchers.go +++ b/modules/caddyhttp/matchers.go @@ -764,12 +764,7 @@ func (m *MatchMethod) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { // Match returns true if r matches m. func (m MatchMethod) Match(r *http.Request) bool { - for _, method := range m { - if r.Method == method { - return true - } - } - return false + return slices.Contains(m, r.Method) } // CELLibrary produces options that expose this matcher for use in CEL diff --git a/modules/caddyhttp/reverseproxy/healthchecks.go b/modules/caddyhttp/reverseproxy/healthchecks.go index 179805f20..319cc9248 100644 --- a/modules/caddyhttp/reverseproxy/healthchecks.go +++ b/modules/caddyhttp/reverseproxy/healthchecks.go @@ -23,6 +23,7 @@ import ( "net/url" "regexp" "runtime/debug" + "slices" "strconv" "strings" "time" @@ -397,12 +398,8 @@ func (h *Handler) doActiveHealthCheck(dialInfo DialInfo, hostAddr string, networ u.Scheme = "https" // if the port is in the except list, flip back to HTTP - if ht, ok := h.Transport.(*HTTPTransport); ok { - for _, exceptPort := range ht.TLS.ExceptPorts { - if exceptPort == port { - u.Scheme = "http" - } - } + if ht, ok := h.Transport.(*HTTPTransport); ok && slices.Contains(ht.TLS.ExceptPorts, port) { + u.Scheme = "http" } } diff --git a/modules/caddyhttp/reverseproxy/httptransport.go b/modules/caddyhttp/reverseproxy/httptransport.go index 144960cf9..bc8233788 100644 --- a/modules/caddyhttp/reverseproxy/httptransport.go +++ b/modules/caddyhttp/reverseproxy/httptransport.go @@ -27,6 +27,7 @@ import ( "net/url" "os" "reflect" + "slices" "strings" "time" @@ -381,7 +382,7 @@ func (h *HTTPTransport) NewTransport(caddyCtx caddy.Context) (*http.Transport, e rt.DisableCompression = !*h.Compression } - if sliceContains(h.Versions, "2") { + if slices.Contains(h.Versions, "2") { if err := http2.ConfigureTransport(rt); err != nil { return nil, err } @@ -400,13 +401,13 @@ func (h *HTTPTransport) NewTransport(caddyCtx caddy.Context) (*http.Transport, e return nil, fmt.Errorf("making TLS client config for HTTP/3 transport: %v", err) } } - } else if len(h.Versions) > 1 && sliceContains(h.Versions, "3") { + } else if len(h.Versions) > 1 && slices.Contains(h.Versions, "3") { return nil, fmt.Errorf("if HTTP/3 is enabled to the upstream, no other HTTP versions are supported") } // if h2c is enabled, configure its transport (std lib http.Transport // does not "HTTP/2 over cleartext TCP") - if sliceContains(h.Versions, "h2c") { + if slices.Contains(h.Versions, "h2c") { // crafting our own http2.Transport doesn't allow us to utilize // most of the customizations/preferences on the http.Transport, // because, for some reason, only http2.ConfigureTransport() @@ -783,16 +784,6 @@ func decodeBase64DERCert(certStr string) (*x509.Certificate, error) { return x509.ParseCertificate(derBytes) } -// sliceContains returns true if needle is in haystack. -func sliceContains(haystack []string, needle string) bool { - for _, s := range haystack { - if s == needle { - return true - } - } - return false -} - // Interface guards var ( _ caddy.Provisioner = (*HTTPTransport)(nil) diff --git a/modules/caddyhttp/server.go b/modules/caddyhttp/server.go index 54b1c3b34..ece3f1cd2 100644 --- a/modules/caddyhttp/server.go +++ b/modules/caddyhttp/server.go @@ -25,6 +25,7 @@ import ( "net/netip" "net/url" "runtime" + "slices" "strings" "sync" "time" @@ -543,12 +544,9 @@ func (s *Server) hasListenerAddress(fullAddr string) bool { } func (s *Server) hasTLSClientAuth() bool { - for _, cp := range s.TLSConnPolicies { - if cp.ClientAuthentication != nil && cp.ClientAuthentication.Active() { - return true - } - } - return false + return slices.ContainsFunc(s.TLSConnPolicies, func(cp *caddytls.ConnectionPolicy) bool { + return cp.ClientAuthentication != nil && cp.ClientAuthentication.Active() + }) } // findLastRouteWithHostMatcher returns the index of the last route @@ -849,12 +847,7 @@ func (s *Server) logRequest( // protocol returns true if the protocol proto is configured/enabled. func (s *Server) protocol(proto string) bool { - for _, p := range s.Protocols { - if p == proto { - return true - } - } - return false + return slices.Contains(s.Protocols, proto) } // Listeners returns the server's listeners. These are active listeners, @@ -959,12 +952,9 @@ func determineTrustedProxy(r *http.Request, s *Server) (bool, string) { // isTrustedClientIP returns true if the given IP address is // in the list of trusted IP ranges. func isTrustedClientIP(ipAddr netip.Addr, trusted []netip.Prefix) bool { - for _, ipRange := range trusted { - if ipRange.Contains(ipAddr) { - return true - } - } - return false + return slices.ContainsFunc(trusted, func(prefix netip.Prefix) bool { + return prefix.Contains(ipAddr) + }) } // trustedRealClientIP finds the client IP from the request assuming it is diff --git a/modules/caddyhttp/templates/frontmatter.go b/modules/caddyhttp/templates/frontmatter.go index 3f7bd0cc4..fb62a4184 100644 --- a/modules/caddyhttp/templates/frontmatter.go +++ b/modules/caddyhttp/templates/frontmatter.go @@ -40,6 +40,7 @@ func extractFrontMatter(input string) (map[string]any, string, error) { if firstLine == fmType.FenceOpen { closingFence = fmType.FenceClose fmParser = fmType.ParseFunc + break } } diff --git a/modules/caddytls/automation.go b/modules/caddytls/automation.go index e2e02221d..1f1042ba0 100644 --- a/modules/caddytls/automation.go +++ b/modules/caddytls/automation.go @@ -21,6 +21,7 @@ import ( "errors" "fmt" "net" + "slices" "strings" "github.com/caddyserver/certmagic" @@ -373,12 +374,9 @@ func (ap *AutomationPolicy) Subjects() []string { // AllInternalSubjects returns true if all the subjects on this policy are internal. func (ap *AutomationPolicy) AllInternalSubjects() bool { - for _, subj := range ap.subjects { - if !certmagic.SubjectIsInternal(subj) { - return false - } - } - return true + return !slices.ContainsFunc(ap.subjects, func(s string) bool { + return !certmagic.SubjectIsInternal(s) + }) } func (ap *AutomationPolicy) onlyInternalIssuer() bool { diff --git a/modules/caddytls/certselection.go b/modules/caddytls/certselection.go index 84ca2e118..a561e3a1d 100644 --- a/modules/caddytls/certselection.go +++ b/modules/caddytls/certselection.go @@ -20,6 +20,7 @@ import ( "encoding/json" "fmt" "math/big" + "slices" "github.com/caddyserver/certmagic" @@ -72,15 +73,9 @@ nextChoice: } if len(p.SubjectOrganization) > 0 { - var found bool - for _, subjOrg := range p.SubjectOrganization { - for _, org := range cert.Leaf.Subject.Organization { - if subjOrg == org { - found = true - break - } - } - } + found := slices.ContainsFunc(p.SubjectOrganization, func(s string) bool { + return slices.Contains(cert.Leaf.Subject.Organization, s) + }) if !found { continue } diff --git a/modules/caddytls/matchers.go b/modules/caddytls/matchers.go index f44b4c02a..a74d6ea80 100644 --- a/modules/caddytls/matchers.go +++ b/modules/caddytls/matchers.go @@ -20,6 +20,7 @@ import ( "net" "net/netip" "regexp" + "slices" "strconv" "strings" @@ -321,12 +322,9 @@ func (MatchRemoteIP) parseIPRange(str string) ([]netip.Prefix, error) { } func (MatchRemoteIP) matches(ip netip.Addr, ranges []netip.Prefix) bool { - for _, ipRange := range ranges { - if ipRange.Contains(ip) { - return true - } - } - return false + return slices.ContainsFunc(ranges, func(prefix netip.Prefix) bool { + return prefix.Contains(ip) + }) } // UnmarshalCaddyfile sets up the MatchRemoteIP from Caddyfile tokens. Syntax: @@ -439,12 +437,9 @@ func (MatchLocalIP) parseIPRange(str string) ([]netip.Prefix, error) { } func (MatchLocalIP) matches(ip netip.Addr, ranges []netip.Prefix) bool { - for _, ipRange := range ranges { - if ipRange.Contains(ip) { - return true - } - } - return false + return slices.ContainsFunc(ranges, func(prefix netip.Prefix) bool { + return prefix.Contains(ip) + }) } // UnmarshalCaddyfile sets up the MatchLocalIP from Caddyfile tokens. Syntax: |