chore(lint): modernize Go (#7536)

Use modern Go constructs through the modernize analyzer from the
golang.org/x/tools package.

Signed-off-by: Ville Vesilehto <ville@vesilehto.fi>
This commit is contained in:
Ville Vesilehto
2025-09-10 23:08:27 +03:00
committed by GitHub
parent afdd41a266
commit 39abf5aeba
48 changed files with 150 additions and 193 deletions

View File

@@ -21,3 +21,5 @@ jobs:
uses: golangci/golangci-lint-action@4afd733a84b1f43292c63897423277bb7f4313a9 # v8.0.0 uses: golangci/golangci-lint-action@4afd733a84b1f43292c63897423277bb7f4313a9 # v8.0.0
with: with:
version: v2.4.0 version: v2.4.0
- name: modernize
run: go run golang.org/x/tools/gopls/internal/analysis/modernize/cmd/modernize@2e31135b736b96cd609904370c71563ce5447826 -diff -test ./... # v0.20.0

View File

@@ -4,6 +4,7 @@ package dnsserver
import ( import (
"context" "context"
"fmt" "fmt"
"maps"
"net" "net"
"runtime" "runtime"
"runtime/debug" "runtime/debug"
@@ -99,9 +100,7 @@ func NewServer(addr string, group []*Config) (*Server, error) {
} }
// copy tsig secrets // copy tsig secrets
for key, secret := range site.TsigSecret { maps.Copy(s.tsigSecret, site.TsigSecret)
s.tsigSecret[key] = secret
}
// compile custom plugin for everything // compile custom plugin for everything
var stack plugin.Handler var stack plugin.Handler

View File

@@ -62,7 +62,7 @@ func (s *ServergRPC) Serve(l net.Listener) error {
s.m.Unlock() s.m.Unlock()
if s.Tracer() != nil { if s.Tracer() != nil {
onlyIfParent := func(parentSpanCtx opentracing.SpanContext, method string, req, resp interface{}) bool { onlyIfParent := func(parentSpanCtx opentracing.SpanContext, method string, req, resp any) bool {
return parentSpanCtx != nil return parentSpanCtx != nil
} }
intercept := otgrpc.OpenTracingServerInterceptor(s.Tracer(), otgrpc.IncludingSpans(onlyIfParent)) intercept := otgrpc.OpenTracingServerInterceptor(s.Tracer(), otgrpc.IncludingSpans(onlyIfParent))

View File

@@ -115,8 +115,8 @@ func BenchmarkCoreServeDNS(b *testing.B) {
m.SetQuestion("aaa.example.com.", dns.TypeTXT) m.SetQuestion("aaa.example.com.", dns.TypeTXT)
b.ReportAllocs() b.ReportAllocs()
b.ResetTimer()
for range b.N { for b.Loop() {
s.ServeDNS(ctx, w, m) s.ServeDNS(ctx, w, m)
} }
} }

View File

@@ -89,7 +89,7 @@ func Run() {
// enabled. If this process is an upgrade, however, and the user // enabled. If this process is an upgrade, however, and the user
// might not be there anymore, this just logs to the process // might not be there anymore, this just logs to the process
// log and exits. // log and exits.
func mustLogFatal(args ...interface{}) { func mustLogFatal(args ...any) {
if !caddy.IsUpgrade() { if !caddy.IsUpgrade() {
log.SetOutput(os.Stderr) log.SetOutput(os.Stderr)
} }

View File

@@ -469,10 +469,7 @@ func NS(ctx context.Context, b ServiceBackend, zone string, state request.Reques
// SOA returns a SOA record from the backend. // SOA returns a SOA record from the backend.
func SOA(ctx context.Context, b ServiceBackend, zone string, state request.Request, opt Options) ([]dns.RR, error) { func SOA(ctx context.Context, b ServiceBackend, zone string, state request.Request, opt Options) ([]dns.RR, error) {
minTTL := b.MinTTL(state) minTTL := b.MinTTL(state)
ttl := uint32(300) ttl := min(minTTL, uint32(300))
if minTTL < ttl {
ttl = minTTL
}
header := dns.RR_Header{Name: zone, Rrtype: dns.TypeSOA, Ttl: ttl, Class: dns.ClassINET} header := dns.RR_Header{Name: zone, Rrtype: dns.TypeSOA, Ttl: ttl, Class: dns.ClassINET}

View File

@@ -117,13 +117,7 @@ func hash(qname string, qtype uint16, do, cd bool) uint64 {
} }
func computeTTL(msgTTL, minTTL, maxTTL time.Duration) time.Duration { func computeTTL(msgTTL, minTTL, maxTTL time.Duration) time.Duration {
ttl := msgTTL ttl := min(max(msgTTL, minTTL), maxTTL)
if ttl < minTTL {
ttl = minTTL
}
if ttl > maxTTL {
ttl = maxTTL
}
return ttl return ttl
} }

View File

@@ -600,10 +600,8 @@ func BenchmarkCacheResponse(b *testing.B) {
reqs[i].SetQuestion(q+".example.org.", dns.TypeA) reqs[i].SetQuestion(q+".example.org.", dns.TypeA)
} }
b.StartTimer()
j := 0 j := 0
for range b.N { for b.Loop() {
req := reqs[j] req := reqs[j]
c.ServeDNS(ctx, &test.ResponseWriter{}, req) c.ServeDNS(ctx, &test.ResponseWriter{}, req)
j = (j + 1) % 5 j = (j + 1) % 5

View File

@@ -22,7 +22,7 @@ import (
// is prefixed with 'debug: ' so the data can be easily extracted. // is prefixed with 'debug: ' so the data can be easily extracted.
// //
// msg will prefix the pcap dump. // msg will prefix the pcap dump.
func Hexdump(m *dns.Msg, v ...interface{}) { func Hexdump(m *dns.Msg, v ...any) {
if !log.D.Value() { if !log.D.Value() {
return return
} }
@@ -38,7 +38,7 @@ func Hexdump(m *dns.Msg, v ...interface{}) {
} }
// Hexdumpf dumps a DNS message as Hexdump, but allows a format string. // Hexdumpf dumps a DNS message as Hexdump, but allows a format string.
func Hexdumpf(m *dns.Msg, format string, v ...interface{}) { func Hexdumpf(m *dns.Msg, format string, v ...any) {
if !log.D.Value() { if !log.D.Value() {
return return
} }

View File

@@ -160,10 +160,7 @@ func (d *DNS64) Synthesize(origReq, origResponse, resp *dns.Msg) *dns.Msg {
aaaa, _ := to6(d.Prefix, rr.(*dns.A).A) aaaa, _ := to6(d.Prefix, rr.(*dns.A).A)
// ttl is min of SOA TTL and A TTL // ttl is min of SOA TTL and A TTL
ttl := SOATtl ttl := min(rr.Header().Ttl, SOATtl)
if rr.Header().Ttl < ttl {
ttl = rr.Header().Ttl
}
// Replace A answer with a DNS64 AAAA answer // Replace A answer with a DNS64 AAAA answer
ret.Answer = append(ret.Answer, &dns.AAAA{ ret.Answer = append(ret.Answer, &dns.AAAA{

View File

@@ -32,7 +32,7 @@ func periodicClean(c *cache.Cache, stop <-chan struct{}) {
// we sign for 8 days, check if a signature in the cache reached 75% of that (i.e. 6), if found delete // we sign for 8 days, check if a signature in the cache reached 75% of that (i.e. 6), if found delete
// the signature // the signature
is75 := time.Now().UTC().Add(twoDays) is75 := time.Now().UTC().Add(twoDays)
c.Walk(func(items map[uint64]interface{}, key uint64) bool { c.Walk(func(items map[uint64]any, key uint64) bool {
for _, rr := range items[key].([]dns.RR) { for _, rr := range items[key].([]dns.RR) {
if !rr.(*dns.RRSIG).ValidityPeriod(is75) { if !rr.(*dns.RRSIG).ValidityPeriod(is75) {
delete(items, key) delete(items, key)

View File

@@ -118,7 +118,7 @@ func (d Dnssec) sign(rrs []dns.RR, signerName string, ttl, incep, expir uint32,
return sgs, nil return sgs, nil
} }
sigs, err := d.inflight.Do(k, func() (interface{}, error) { sigs, err := d.inflight.Do(k, func() (any, error) {
var sigs []dns.RR var sigs []dns.RR
for _, k := range d.keys { for _, k := range d.keys {
if d.splitkeys { if d.splitkeys {

View File

@@ -3,6 +3,7 @@ package dnssec
import ( import (
"fmt" "fmt"
"path/filepath" "path/filepath"
"slices"
"strconv" "strconv"
"strings" "strings"
@@ -94,13 +95,7 @@ func dnssecParse(c *caddy.Controller) ([]string, []*DNSKEY, int, bool, error) {
// Check if each keys owner name can actually sign the zones we want them to sign. // Check if each keys owner name can actually sign the zones we want them to sign.
for _, k := range keys { for _, k := range keys {
kname := plugin.Name(k.K.Header().Name) kname := plugin.Name(k.K.Header().Name)
ok := false ok := slices.ContainsFunc(zones, kname.Matches)
for i := range zones {
if kname.Matches(zones[i]) {
ok = true
break
}
}
if !ok { if !ok {
return zones, keys, capacity, splitkeys, fmt.Errorf("key %s (keyid: %d) can not sign any of the zones", string(kname), k.tag) return zones, keys, capacity, splitkeys, fmt.Errorf("key %s (keyid: %d) can not sign any of the zones", string(kname), k.tag)
} }

View File

@@ -18,7 +18,7 @@ func BenchmarkServeDNS(b *testing.B) {
w := &test.ResponseWriter{} w := &test.ResponseWriter{}
ctx := context.TODO() ctx := context.TODO()
for range b.N { for b.Loop() {
_, err := h.ServeDNS(ctx, w, r) _, err := h.ServeDNS(ctx, w, r)
if err != nil { if err != nil {
b.Errorf("ServeDNS returned error: %s", err) b.Errorf("ServeDNS returned error: %s", err)

View File

@@ -22,7 +22,7 @@ type pattern struct {
count uint32 count uint32
period time.Duration period time.Duration
pattern *regexp.Regexp pattern *regexp.Regexp
logCallback func(format string, v ...interface{}) logCallback func(format string, v ...any)
} }
func (p *pattern) timer() *time.Timer { func (p *pattern) timer() *time.Timer {

View File

@@ -73,7 +73,7 @@ func TestErrors(t *testing.T) {
func TestLogPattern(t *testing.T) { func TestLogPattern(t *testing.T) {
type args struct { type args struct {
logCallback func(format string, v ...interface{}) logCallback func(format string, v ...any)
} }
tests := []struct { tests := []struct {
name string name string

View File

@@ -89,7 +89,7 @@ func parseConsolidate(c *caddy.Controller) (*pattern, error) {
return &pattern{period: p, pattern: re, logCallback: lc}, nil return &pattern{period: p, pattern: re, logCallback: lc}, nil
} }
func parseLogLevel(c *caddy.Controller, args []string) (func(format string, v ...interface{}), error) { func parseLogLevel(c *caddy.Controller, args []string) (func(format string, v ...any), error) {
if len(args) != 3 { if len(args) != 3 {
return log.Errorf, nil return log.Errorf, nil
} }

View File

@@ -167,9 +167,7 @@ func BenchmarkFileLookupDNSSEC(b *testing.B) {
m := tc.Msg() m := tc.Msg()
b.ResetTimer() for b.Loop() {
for range b.N {
fm.ServeDNS(ctx, rec, m) fm.ServeDNS(ctx, rec, m)
} }
} }

View File

@@ -6,7 +6,7 @@ import (
) )
func BenchmarkFileParseInsert(b *testing.B) { func BenchmarkFileParseInsert(b *testing.B) {
for range b.N { for b.Loop() {
Parse(strings.NewReader(dbMiekENTNL), testzone, "stdin", 0) Parse(strings.NewReader(dbMiekENTNL), testzone, "stdin", 0)
} }
} }

View File

@@ -316,9 +316,7 @@ func BenchmarkFileLookup(b *testing.B) {
m := tc.Msg() m := tc.Msg()
b.ResetTimer() for b.Loop() {
for range b.N {
fm.ServeDNS(ctx, rec, m) fm.ServeDNS(ctx, rec, m)
} }
} }

View File

@@ -68,9 +68,8 @@ func BenchmarkAutoPath(b *testing.B) {
state := request.Request{W: &test.ResponseWriter{}, Req: req} state := request.Request{W: &test.ResponseWriter{}, Req: req}
b.ReportAllocs() b.ReportAllocs()
b.ResetTimer()
for range b.N { for b.Loop() {
result := k.AutoPath(state) result := k.AutoPath(state)
_ = result _ = result
} }

View File

@@ -239,7 +239,7 @@ func (dns *dnsControl) EndpointSliceLatencyRecorder() *object.EndpointLatencyRec
} }
} }
func podIPIndexFunc(obj interface{}) ([]string, error) { func podIPIndexFunc(obj any) ([]string, error) {
p, ok := obj.(*object.Pod) p, ok := obj.(*object.Pod)
if !ok { if !ok {
return nil, errObj return nil, errObj
@@ -247,7 +247,7 @@ func podIPIndexFunc(obj interface{}) ([]string, error) {
return []string{p.PodIP}, nil return []string{p.PodIP}, nil
} }
func svcIPIndexFunc(obj interface{}) ([]string, error) { func svcIPIndexFunc(obj any) ([]string, error) {
svc, ok := obj.(*object.Service) svc, ok := obj.(*object.Service)
if !ok { if !ok {
return nil, errObj return nil, errObj
@@ -257,7 +257,7 @@ func svcIPIndexFunc(obj interface{}) ([]string, error) {
return idx, nil return idx, nil
} }
func svcExtIPIndexFunc(obj interface{}) ([]string, error) { func svcExtIPIndexFunc(obj any) ([]string, error) {
svc, ok := obj.(*object.Service) svc, ok := obj.(*object.Service)
if !ok { if !ok {
return nil, errObj return nil, errObj
@@ -267,7 +267,7 @@ func svcExtIPIndexFunc(obj interface{}) ([]string, error) {
return idx, nil return idx, nil
} }
func svcNameNamespaceIndexFunc(obj interface{}) ([]string, error) { func svcNameNamespaceIndexFunc(obj any) ([]string, error) {
s, ok := obj.(*object.Service) s, ok := obj.(*object.Service)
if !ok { if !ok {
return nil, errObj return nil, errObj
@@ -275,7 +275,7 @@ func svcNameNamespaceIndexFunc(obj interface{}) ([]string, error) {
return []string{s.Index}, nil return []string{s.Index}, nil
} }
func epNameNamespaceIndexFunc(obj interface{}) ([]string, error) { func epNameNamespaceIndexFunc(obj any) ([]string, error) {
s, ok := obj.(*object.Endpoints) s, ok := obj.(*object.Endpoints)
if !ok { if !ok {
return nil, errObj return nil, errObj
@@ -283,7 +283,7 @@ func epNameNamespaceIndexFunc(obj interface{}) ([]string, error) {
return []string{s.Index}, nil return []string{s.Index}, nil
} }
func epIPIndexFunc(obj interface{}) ([]string, error) { func epIPIndexFunc(obj any) ([]string, error) {
ep, ok := obj.(*object.Endpoints) ep, ok := obj.(*object.Endpoints)
if !ok { if !ok {
return nil, errObj return nil, errObj
@@ -291,7 +291,7 @@ func epIPIndexFunc(obj interface{}) ([]string, error) {
return ep.IndexIP, nil return ep.IndexIP, nil
} }
func svcImportNameNamespaceIndexFunc(obj interface{}) ([]string, error) { func svcImportNameNamespaceIndexFunc(obj any) ([]string, error) {
s, ok := obj.(*object.ServiceImport) s, ok := obj.(*object.ServiceImport)
if !ok { if !ok {
return nil, errObj return nil, errObj
@@ -299,7 +299,7 @@ func svcImportNameNamespaceIndexFunc(obj interface{}) ([]string, error) {
return []string{s.Index}, nil return []string{s.Index}, nil
} }
func mcEpNameNamespaceIndexFunc(obj interface{}) ([]string, error) { func mcEpNameNamespaceIndexFunc(obj any) ([]string, error) {
mcEp, ok := obj.(*object.MultiClusterEndpoints) mcEp, ok := obj.(*object.MultiClusterEndpoints)
if !ok { if !ok {
return nil, errObj return nil, errObj
@@ -647,12 +647,12 @@ func (dns *dnsControl) GetNamespaceByName(name string) (*object.Namespace, error
return ns, nil return ns, nil
} }
func (dns *dnsControl) Add(obj interface{}) { dns.updateModified() } func (dns *dnsControl) Add(obj any) { dns.updateModified() }
func (dns *dnsControl) Delete(obj interface{}) { dns.updateModified() } func (dns *dnsControl) Delete(obj any) { dns.updateModified() }
func (dns *dnsControl) Update(oldObj, newObj interface{}) { dns.detectChanges(oldObj, newObj) } func (dns *dnsControl) Update(oldObj, newObj any) { dns.detectChanges(oldObj, newObj) }
// detectChanges detects changes in objects, and updates the modified timestamp // detectChanges detects changes in objects, and updates the modified timestamp
func (dns *dnsControl) detectChanges(oldObj, newObj interface{}) { func (dns *dnsControl) detectChanges(oldObj, newObj any) {
// If both objects have the same resource version, they are identical. // If both objects have the same resource version, they are identical.
if newObj != nil && oldObj != nil && (oldObj.(meta.Object).GetResourceVersion() == newObj.(meta.Object).GetResourceVersion()) { if newObj != nil && oldObj != nil && (oldObj.(meta.Object).GetResourceVersion() == newObj.(meta.Object).GetResourceVersion()) {
return return
@@ -771,7 +771,7 @@ func multiclusterEndpointsEquivalent(a, b *object.MultiClusterEndpoints) bool {
// serviceModified checks the services passed for changes that result in changes // serviceModified checks the services passed for changes that result in changes
// to internal and or external records. It returns two booleans, one for internal // to internal and or external records. It returns two booleans, one for internal
// record changes, and a second for external record changes // record changes, and a second for external record changes
func serviceModified(oldObj, newObj interface{}) (intSvc, extSvc bool) { func serviceModified(oldObj, newObj any) (intSvc, extSvc bool) {
if oldObj != nil && newObj == nil { if oldObj != nil && newObj == nil {
// deleted service only modifies external zone records if it had external ips // deleted service only modifies external zone records if it had external ips
return true, len(oldObj.(*object.Service).ExternalIPs) > 0 return true, len(oldObj.(*object.Service).ExternalIPs) > 0
@@ -825,7 +825,7 @@ func serviceModified(oldObj, newObj interface{}) (intSvc, extSvc bool) {
// serviceImportEquivalent checks if the update to a ServiceImport is something // serviceImportEquivalent checks if the update to a ServiceImport is something
// that matters to us or if they are effectively equivalent. // that matters to us or if they are effectively equivalent.
func serviceImportEquivalent(oldObj, newObj interface{}) bool { func serviceImportEquivalent(oldObj, newObj any) bool {
if oldObj != nil && newObj == nil { if oldObj != nil && newObj == nil {
return false return false
} }

View File

@@ -69,8 +69,7 @@ func BenchmarkController(b *testing.B) {
m := new(dns.Msg) m := new(dns.Msg)
m.SetQuestion("svc1.testns.svc.cluster.local.", dns.TypeA) m.SetQuestion("svc1.testns.svc.cluster.local.", dns.TypeA)
b.ResetTimer() for b.Loop() {
for range b.N {
k.ServeDNS(ctx, rw, m) k.ServeDNS(ctx, rw, m)
} }
} }
@@ -294,8 +293,8 @@ func createMultiClusterHeadlessSvc(suffix int, mcsClient mcsClientset.Multiclust
func TestServiceModified(t *testing.T) { func TestServiceModified(t *testing.T) {
tests := []struct { tests := []struct {
oldSvc interface{} oldSvc any
newSvc interface{} newSvc any
ichanged bool ichanged bool
echanged bool echanged bool
}{ }{

View File

@@ -21,15 +21,15 @@ func (l *loggerAdapter) Enabled(_ int) bool {
return true return true
} }
func (l *loggerAdapter) Info(_ int, msg string, _ ...interface{}) { func (l *loggerAdapter) Info(_ int, msg string, _ ...any) {
l.P.Info(msg) l.P.Info(msg)
} }
func (l *loggerAdapter) Error(_ error, msg string, _ ...interface{}) { func (l *loggerAdapter) Error(_ error, msg string, _ ...any) {
l.P.Error(msg) l.P.Error(msg)
} }
func (l *loggerAdapter) WithValues(_ ...interface{}) logr.LogSink { func (l *loggerAdapter) WithValues(_ ...any) logr.LogSink {
return l return l
} }

View File

@@ -28,7 +28,7 @@ type RecordLatencyFunc func(meta.Object)
// DefaultProcessor is based on the Process function from cache.NewIndexerInformer except it does a conversion. // DefaultProcessor is based on the Process function from cache.NewIndexerInformer except it does a conversion.
func DefaultProcessor(convert ToFunc, recordLatency *EndpointLatencyRecorder) ProcessorBuilder { func DefaultProcessor(convert ToFunc, recordLatency *EndpointLatencyRecorder) ProcessorBuilder {
return func(clientState cache.Indexer, h cache.ResourceEventHandler) cache.ProcessFunc { return func(clientState cache.Indexer, h cache.ResourceEventHandler) cache.ProcessFunc {
return func(obj interface{}, isInitialList bool) error { return func(obj any, isInitialList bool) error {
for _, d := range obj.(cache.Deltas) { for _, d := range obj.(cache.Deltas) {
if recordLatency != nil { if recordLatency != nil {
if o, ok := d.Object.(meta.Object); ok { if o, ok := d.Object.(meta.Object); ok {
@@ -59,7 +59,7 @@ func DefaultProcessor(convert ToFunc, recordLatency *EndpointLatencyRecorder) Pr
recordLatency.record() recordLatency.record()
} }
case cache.Deleted: case cache.Deleted:
var obj interface{} var obj any
obj, ok := d.Object.(cache.DeletedFinalStateUnknown) obj, ok := d.Object.(cache.DeletedFinalStateUnknown)
if !ok { if !ok {
var err error var err error

View File

@@ -273,8 +273,7 @@ func BenchmarkLogged(b *testing.B) {
rec := dnstest.NewRecorder(&test.ResponseWriter{}) rec := dnstest.NewRecorder(&test.ResponseWriter{})
b.StartTimer() for b.Loop() {
for range b.N {
logger.ServeDNS(ctx, rec, r) logger.ServeDNS(ctx, rec, r)
} }
} }

View File

@@ -22,7 +22,7 @@ type Cache struct {
// shard is a cache with random eviction. // shard is a cache with random eviction.
type shard struct { type shard struct {
items map[uint64]interface{} items map[uint64]any
size int size int
sync.RWMutex sync.RWMutex
@@ -30,10 +30,7 @@ type shard struct {
// New returns a new cache. // New returns a new cache.
func New(size int) *Cache { func New(size int) *Cache {
ssize := size / shardSize ssize := max(size/shardSize, 4)
if ssize < 4 {
ssize = 4
}
c := &Cache{} c := &Cache{}
@@ -46,13 +43,13 @@ func New(size int) *Cache {
// Add adds a new element to the cache. If the element already exists it is overwritten. // Add adds a new element to the cache. If the element already exists it is overwritten.
// Returns true if an existing element was evicted to make room for this element. // Returns true if an existing element was evicted to make room for this element.
func (c *Cache) Add(key uint64, el interface{}) bool { func (c *Cache) Add(key uint64, el any) bool {
shard := key & (shardSize - 1) shard := key & (shardSize - 1)
return c.shards[shard].Add(key, el) return c.shards[shard].Add(key, el)
} }
// Get looks up element index under key. // Get looks up element index under key.
func (c *Cache) Get(key uint64) (interface{}, bool) { func (c *Cache) Get(key uint64) (any, bool) {
shard := key & (shardSize - 1) shard := key & (shardSize - 1)
return c.shards[shard].Get(key) return c.shards[shard].Get(key)
} }
@@ -73,18 +70,18 @@ func (c *Cache) Len() int {
} }
// Walk walks each shard in the cache. // Walk walks each shard in the cache.
func (c *Cache) Walk(f func(map[uint64]interface{}, uint64) bool) { func (c *Cache) Walk(f func(map[uint64]any, uint64) bool) {
for _, s := range &c.shards { for _, s := range &c.shards {
s.Walk(f) s.Walk(f)
} }
} }
// newShard returns a new shard with size. // newShard returns a new shard with size.
func newShard(size int) *shard { return &shard{items: make(map[uint64]interface{}), size: size} } func newShard(size int) *shard { return &shard{items: make(map[uint64]any), size: size} }
// Add adds element indexed by key into the cache. Any existing element is overwritten // Add adds element indexed by key into the cache. Any existing element is overwritten
// Returns true if an existing element was evicted to make room for this element. // Returns true if an existing element was evicted to make room for this element.
func (s *shard) Add(key uint64, el interface{}) bool { func (s *shard) Add(key uint64, el any) bool {
eviction := false eviction := false
s.Lock() s.Lock()
if len(s.items) >= s.size { if len(s.items) >= s.size {
@@ -119,7 +116,7 @@ func (s *shard) Evict() {
} }
// Get looks up the element indexed under key. // Get looks up the element indexed under key.
func (s *shard) Get(key uint64) (interface{}, bool) { func (s *shard) Get(key uint64) (any, bool) {
s.RLock() s.RLock()
el, found := s.items[key] el, found := s.items[key]
s.RUnlock() s.RUnlock()
@@ -135,7 +132,7 @@ func (s *shard) Len() int {
} }
// Walk walks the shard for each element the function f is executed while holding a write lock. // Walk walks the shard for each element the function f is executed while holding a write lock.
func (s *shard) Walk(f func(map[uint64]interface{}, uint64) bool) { func (s *shard) Walk(f func(map[uint64]any, uint64) bool) {
s.RLock() s.RLock()
items := make([]uint64, len(s.items)) items := make([]uint64, len(s.items))
i := 0 i := 0

View File

@@ -63,7 +63,7 @@ func TestCacheWalk(t *testing.T) {
exp[i] = 1 exp[i] = 1
} }
got := make([]int, 10*2) got := make([]int, 10*2)
c.Walk(func(items map[uint64]interface{}, key uint64) bool { c.Walk(func(items map[uint64]any, key uint64) bool {
got[key] = items[key].(int) got[key] = items[key].(int)
return true return true
}) })
@@ -78,7 +78,7 @@ func BenchmarkCache(b *testing.B) {
b.ReportAllocs() b.ReportAllocs()
c := New(4) c := New(4)
for range b.N { for b.Loop() {
c.Add(1, 1) c.Add(1, 1)
c.Get(1) c.Get(1)
} }

View File

@@ -62,8 +62,7 @@ func BenchmarkMinimalTTL(b *testing.B) {
utc := time.Now().UTC() utc := time.Now().UTC()
mt, _ := response.Typify(m, utc) mt, _ := response.Typify(m, utc)
b.ResetTimer() for b.Loop() {
for range b.N {
dur := MinimalTTL(m, mt) dur := MinimalTTL(m, mt)
if dur != 1000*time.Second { if dur != 1000*time.Second {
b.Fatalf("Wrong MinimalTTL %d, expected %d", dur, 1000*time.Second) b.Fatalf("Wrong MinimalTTL %d, expected %d", dur, 1000*time.Second)

View File

@@ -10,8 +10,8 @@ import (
) )
// DefaultEnv returns the default set of custom state variables and functions available to for use in expression evaluation. // DefaultEnv returns the default set of custom state variables and functions available to for use in expression evaluation.
func DefaultEnv(ctx context.Context, state *request.Request) map[string]interface{} { func DefaultEnv(ctx context.Context, state *request.Request) map[string]any {
return map[string]interface{}{ return map[string]any{
"incidr": func(ipStr, cidrStr string) (bool, error) { "incidr": func(ipStr, cidrStr string) (bool, error) {
ip := net.ParseIP(ipStr) ip := net.ParseIP(ipStr)
if ip == nil { if ip == nil {

View File

@@ -9,16 +9,16 @@ import (
// A usage example is, the external plugin k8s_event will replicate log prints to Kubernetes events. // A usage example is, the external plugin k8s_event will replicate log prints to Kubernetes events.
type Listener interface { type Listener interface {
Name() string Name() string
Debug(plugin string, v ...interface{}) Debug(plugin string, v ...any)
Debugf(plugin string, format string, v ...interface{}) Debugf(plugin string, format string, v ...any)
Info(plugin string, v ...interface{}) Info(plugin string, v ...any)
Infof(plugin string, format string, v ...interface{}) Infof(plugin string, format string, v ...any)
Warning(plugin string, v ...interface{}) Warning(plugin string, v ...any)
Warningf(plugin string, format string, v ...interface{}) Warningf(plugin string, format string, v ...any)
Error(plugin string, v ...interface{}) Error(plugin string, v ...any)
Errorf(plugin string, format string, v ...interface{}) Errorf(plugin string, format string, v ...any)
Fatal(plugin string, v ...interface{}) Fatal(plugin string, v ...any)
Fatalf(plugin string, format string, v ...interface{}) Fatalf(plugin string, format string, v ...any)
} }
type listeners struct { type listeners struct {
@@ -60,7 +60,7 @@ func DeregisterListener(old Listener) error {
return nil return nil
} }
func (ls *listeners) debug(plugin string, v ...interface{}) { func (ls *listeners) debug(plugin string, v ...any) {
ls.RLock() ls.RLock()
for _, l := range ls.listeners { for _, l := range ls.listeners {
l.Debug(plugin, v...) l.Debug(plugin, v...)
@@ -68,7 +68,7 @@ func (ls *listeners) debug(plugin string, v ...interface{}) {
ls.RUnlock() ls.RUnlock()
} }
func (ls *listeners) debugf(plugin string, format string, v ...interface{}) { func (ls *listeners) debugf(plugin string, format string, v ...any) {
ls.RLock() ls.RLock()
for _, l := range ls.listeners { for _, l := range ls.listeners {
l.Debugf(plugin, format, v...) l.Debugf(plugin, format, v...)
@@ -76,7 +76,7 @@ func (ls *listeners) debugf(plugin string, format string, v ...interface{}) {
ls.RUnlock() ls.RUnlock()
} }
func (ls *listeners) info(plugin string, v ...interface{}) { func (ls *listeners) info(plugin string, v ...any) {
ls.RLock() ls.RLock()
for _, l := range ls.listeners { for _, l := range ls.listeners {
l.Info(plugin, v...) l.Info(plugin, v...)
@@ -84,7 +84,7 @@ func (ls *listeners) info(plugin string, v ...interface{}) {
ls.RUnlock() ls.RUnlock()
} }
func (ls *listeners) infof(plugin string, format string, v ...interface{}) { func (ls *listeners) infof(plugin string, format string, v ...any) {
ls.RLock() ls.RLock()
for _, l := range ls.listeners { for _, l := range ls.listeners {
l.Infof(plugin, format, v...) l.Infof(plugin, format, v...)
@@ -92,7 +92,7 @@ func (ls *listeners) infof(plugin string, format string, v ...interface{}) {
ls.RUnlock() ls.RUnlock()
} }
func (ls *listeners) warning(plugin string, v ...interface{}) { func (ls *listeners) warning(plugin string, v ...any) {
ls.RLock() ls.RLock()
for _, l := range ls.listeners { for _, l := range ls.listeners {
l.Warning(plugin, v...) l.Warning(plugin, v...)
@@ -100,7 +100,7 @@ func (ls *listeners) warning(plugin string, v ...interface{}) {
ls.RUnlock() ls.RUnlock()
} }
func (ls *listeners) warningf(plugin string, format string, v ...interface{}) { func (ls *listeners) warningf(plugin string, format string, v ...any) {
ls.RLock() ls.RLock()
for _, l := range ls.listeners { for _, l := range ls.listeners {
l.Warningf(plugin, format, v...) l.Warningf(plugin, format, v...)
@@ -108,7 +108,7 @@ func (ls *listeners) warningf(plugin string, format string, v ...interface{}) {
ls.RUnlock() ls.RUnlock()
} }
func (ls *listeners) error(plugin string, v ...interface{}) { func (ls *listeners) error(plugin string, v ...any) {
ls.RLock() ls.RLock()
for _, l := range ls.listeners { for _, l := range ls.listeners {
l.Error(plugin, v...) l.Error(plugin, v...)
@@ -116,7 +116,7 @@ func (ls *listeners) error(plugin string, v ...interface{}) {
ls.RUnlock() ls.RUnlock()
} }
func (ls *listeners) errorf(plugin string, format string, v ...interface{}) { func (ls *listeners) errorf(plugin string, format string, v ...any) {
ls.RLock() ls.RLock()
for _, l := range ls.listeners { for _, l := range ls.listeners {
l.Errorf(plugin, format, v...) l.Errorf(plugin, format, v...)
@@ -124,7 +124,7 @@ func (ls *listeners) errorf(plugin string, format string, v ...interface{}) {
ls.RUnlock() ls.RUnlock()
} }
func (ls *listeners) fatal(plugin string, v ...interface{}) { func (ls *listeners) fatal(plugin string, v ...any) {
ls.RLock() ls.RLock()
for _, l := range ls.listeners { for _, l := range ls.listeners {
l.Fatal(plugin, v...) l.Fatal(plugin, v...)
@@ -132,7 +132,7 @@ func (ls *listeners) fatal(plugin string, v ...interface{}) {
ls.RUnlock() ls.RUnlock()
} }
func (ls *listeners) fatalf(plugin string, format string, v ...interface{}) { func (ls *listeners) fatalf(plugin string, format string, v ...any) {
ls.RLock() ls.RLock()
for _, l := range ls.listeners { for _, l := range ls.listeners {
l.Fatalf(plugin, format, v...) l.Fatalf(plugin, format, v...)

View File

@@ -80,42 +80,42 @@ func (l *mockListener) Name() string {
return l.name return l.name
} }
func (l *mockListener) Debug(plugin string, v ...interface{}) { func (l *mockListener) Debug(plugin string, v ...any) {
log(debug, l.name+" mocked debug") log(debug, l.name+" mocked debug")
} }
func (l *mockListener) Debugf(plugin string, format string, v ...interface{}) { func (l *mockListener) Debugf(plugin string, format string, v ...any) {
log(debug, l.name+" mocked debug") log(debug, l.name+" mocked debug")
} }
func (l *mockListener) Info(plugin string, v ...interface{}) { func (l *mockListener) Info(plugin string, v ...any) {
log(info, l.name+" mocked info") log(info, l.name+" mocked info")
} }
func (l *mockListener) Infof(plugin string, format string, v ...interface{}) { func (l *mockListener) Infof(plugin string, format string, v ...any) {
log(info, l.name+" mocked info") log(info, l.name+" mocked info")
} }
func (l *mockListener) Warning(plugin string, v ...interface{}) { func (l *mockListener) Warning(plugin string, v ...any) {
log(warning, l.name+" mocked warning") log(warning, l.name+" mocked warning")
} }
func (l *mockListener) Warningf(plugin string, format string, v ...interface{}) { func (l *mockListener) Warningf(plugin string, format string, v ...any) {
log(warning, l.name+" mocked warning") log(warning, l.name+" mocked warning")
} }
func (l *mockListener) Error(plugin string, v ...interface{}) { func (l *mockListener) Error(plugin string, v ...any) {
log(err, l.name+" mocked error") log(err, l.name+" mocked error")
} }
func (l *mockListener) Errorf(plugin string, format string, v ...interface{}) { func (l *mockListener) Errorf(plugin string, format string, v ...any) {
log(err, l.name+" mocked error") log(err, l.name+" mocked error")
} }
func (l *mockListener) Fatal(plugin string, v ...interface{}) { func (l *mockListener) Fatal(plugin string, v ...any) {
log(fatal, l.name+" mocked fatal") log(fatal, l.name+" mocked fatal")
} }
func (l *mockListener) Fatalf(plugin string, format string, v ...interface{}) { func (l *mockListener) Fatalf(plugin string, format string, v ...any) {
log(fatal, l.name+" mocked fatal") log(fatal, l.name+" mocked fatal")
} }

View File

@@ -40,18 +40,18 @@ func (d *d) Value() bool {
} }
// logf calls log.Printf prefixed with level. // logf calls log.Printf prefixed with level.
func logf(level, format string, v ...interface{}) { func logf(level, format string, v ...any) {
golog.Print(level, fmt.Sprintf(format, v...)) golog.Print(level, fmt.Sprintf(format, v...))
} }
// log calls log.Print prefixed with level. // log calls log.Print prefixed with level.
func log(level string, v ...interface{}) { func log(level string, v ...any) {
golog.Print(level, fmt.Sprint(v...)) golog.Print(level, fmt.Sprint(v...))
} }
// Debug is equivalent to log.Print(), but prefixed with "[DEBUG] ". It only outputs something // Debug is equivalent to log.Print(), but prefixed with "[DEBUG] ". It only outputs something
// if D is true. // if D is true.
func Debug(v ...interface{}) { func Debug(v ...any) {
if !D.Value() { if !D.Value() {
return return
} }
@@ -60,7 +60,7 @@ func Debug(v ...interface{}) {
// Debugf is equivalent to log.Printf(), but prefixed with "[DEBUG] ". It only outputs something // Debugf is equivalent to log.Printf(), but prefixed with "[DEBUG] ". It only outputs something
// if D is true. // if D is true.
func Debugf(format string, v ...interface{}) { func Debugf(format string, v ...any) {
if !D.Value() { if !D.Value() {
return return
} }
@@ -68,30 +68,30 @@ func Debugf(format string, v ...interface{}) {
} }
// Info is equivalent to log.Print, but prefixed with "[INFO] ". // Info is equivalent to log.Print, but prefixed with "[INFO] ".
func Info(v ...interface{}) { log(info, v...) } func Info(v ...any) { log(info, v...) }
// Infof is equivalent to log.Printf, but prefixed with "[INFO] ". // Infof is equivalent to log.Printf, but prefixed with "[INFO] ".
func Infof(format string, v ...interface{}) { logf(info, format, v...) } func Infof(format string, v ...any) { logf(info, format, v...) }
// Warning is equivalent to log.Print, but prefixed with "[WARNING] ". // Warning is equivalent to log.Print, but prefixed with "[WARNING] ".
func Warning(v ...interface{}) { log(warning, v...) } func Warning(v ...any) { log(warning, v...) }
// Warningf is equivalent to log.Printf, but prefixed with "[WARNING] ". // Warningf is equivalent to log.Printf, but prefixed with "[WARNING] ".
func Warningf(format string, v ...interface{}) { logf(warning, format, v...) } func Warningf(format string, v ...any) { logf(warning, format, v...) }
// Error is equivalent to log.Print, but prefixed with "[ERROR] ". // Error is equivalent to log.Print, but prefixed with "[ERROR] ".
func Error(v ...interface{}) { log(err, v...) } func Error(v ...any) { log(err, v...) }
// Errorf is equivalent to log.Printf, but prefixed with "[ERROR] ". // Errorf is equivalent to log.Printf, but prefixed with "[ERROR] ".
func Errorf(format string, v ...interface{}) { logf(err, format, v...) } func Errorf(format string, v ...any) { logf(err, format, v...) }
// Fatal is equivalent to log.Print, but prefixed with "[FATAL] ", and calling // Fatal is equivalent to log.Print, but prefixed with "[FATAL] ", and calling
// os.Exit(1). // os.Exit(1).
func Fatal(v ...interface{}) { log(fatal, v...); os.Exit(1) } func Fatal(v ...any) { log(fatal, v...); os.Exit(1) }
// Fatalf is equivalent to log.Printf, but prefixed with "[FATAL] ", and calling // Fatalf is equivalent to log.Printf, but prefixed with "[FATAL] ", and calling
// os.Exit(1) // os.Exit(1)
func Fatalf(format string, v ...interface{}) { logf(fatal, format, v...); os.Exit(1) } func Fatalf(format string, v ...any) { logf(fatal, format, v...); os.Exit(1) }
// Discard sets the log output to /dev/null. // Discard sets the log output to /dev/null.
func Discard() { golog.SetOutput(io.Discard) } func Discard() { golog.SetOutput(io.Discard) }

View File

@@ -14,16 +14,16 @@ type P struct {
// I.e [INFO] plugin/<name>: message. // I.e [INFO] plugin/<name>: message.
func NewWithPlugin(name string) P { return P{"plugin/" + name + ": "} } func NewWithPlugin(name string) P { return P{"plugin/" + name + ": "} }
func (p P) logf(level, format string, v ...interface{}) { func (p P) logf(level, format string, v ...any) {
log(level, p.plugin, fmt.Sprintf(format, v...)) log(level, p.plugin, fmt.Sprintf(format, v...))
} }
func (p P) log(level string, v ...interface{}) { func (p P) log(level string, v ...any) {
log(level+p.plugin, v...) log(level+p.plugin, v...)
} }
// Debug logs as log.Debug. // Debug logs as log.Debug.
func (p P) Debug(v ...interface{}) { func (p P) Debug(v ...any) {
if !D.Value() { if !D.Value() {
return return
} }
@@ -32,7 +32,7 @@ func (p P) Debug(v ...interface{}) {
} }
// Debugf logs as log.Debugf. // Debugf logs as log.Debugf.
func (p P) Debugf(format string, v ...interface{}) { func (p P) Debugf(format string, v ...any) {
if !D.Value() { if !D.Value() {
return return
} }
@@ -41,50 +41,50 @@ func (p P) Debugf(format string, v ...interface{}) {
} }
// Info logs as log.Info. // Info logs as log.Info.
func (p P) Info(v ...interface{}) { func (p P) Info(v ...any) {
ls.info(p.plugin, v...) ls.info(p.plugin, v...)
p.log(info, v...) p.log(info, v...)
} }
// Infof logs as log.Infof. // Infof logs as log.Infof.
func (p P) Infof(format string, v ...interface{}) { func (p P) Infof(format string, v ...any) {
ls.infof(p.plugin, format, v...) ls.infof(p.plugin, format, v...)
p.logf(info, format, v...) p.logf(info, format, v...)
} }
// Warning logs as log.Warning. // Warning logs as log.Warning.
func (p P) Warning(v ...interface{}) { func (p P) Warning(v ...any) {
ls.warning(p.plugin, v...) ls.warning(p.plugin, v...)
p.log(warning, v...) p.log(warning, v...)
} }
// Warningf logs as log.Warningf. // Warningf logs as log.Warningf.
func (p P) Warningf(format string, v ...interface{}) { func (p P) Warningf(format string, v ...any) {
ls.warningf(p.plugin, format, v...) ls.warningf(p.plugin, format, v...)
p.logf(warning, format, v...) p.logf(warning, format, v...)
} }
// Error logs as log.Error. // Error logs as log.Error.
func (p P) Error(v ...interface{}) { func (p P) Error(v ...any) {
ls.error(p.plugin, v...) ls.error(p.plugin, v...)
p.log(err, v...) p.log(err, v...)
} }
// Errorf logs as log.Errorf. // Errorf logs as log.Errorf.
func (p P) Errorf(format string, v ...interface{}) { func (p P) Errorf(format string, v ...any) {
ls.errorf(p.plugin, format, v...) ls.errorf(p.plugin, format, v...)
p.logf(err, format, v...) p.logf(err, format, v...)
} }
// Fatal logs as log.Fatal and calls os.Exit(1). // Fatal logs as log.Fatal and calls os.Exit(1).
func (p P) Fatal(v ...interface{}) { func (p P) Fatal(v ...any) {
ls.fatal(p.plugin, v...) ls.fatal(p.plugin, v...)
p.log(fatal, v...) p.log(fatal, v...)
os.Exit(1) os.Exit(1)
} }
// Fatalf logs as log.Fatalf and calls os.Exit(1). // Fatalf logs as log.Fatalf and calls os.Exit(1).
func (p P) Fatalf(format string, v ...interface{}) { func (p P) Fatalf(format string, v ...any) {
ls.fatalf(p.plugin, format, v...) ls.fatalf(p.plugin, format, v...)
p.logf(fatal, format, v...) p.logf(fatal, format, v...)
os.Exit(1) os.Exit(1)

View File

@@ -123,10 +123,7 @@ func (p *Proxy) Connect(ctx context.Context, state request.Request, opts Options
} }
// Set buffer size correctly for this client. // Set buffer size correctly for this client.
pc.c.UDPSize = uint16(state.Size()) pc.c.UDPSize = max(uint16(state.Size()), 512)
if pc.c.UDPSize < 512 {
pc.c.UDPSize = 512
}
pc.c.SetWriteDeadline(time.Now().Add(maxTimeout)) pc.c.SetWriteDeadline(time.Now().Add(maxTimeout))
// records the origin Id before upstream. // records the origin Id before upstream.

View File

@@ -256,7 +256,7 @@ func loadFormat(s string) replacer {
// bufPool stores pointers to scratch buffers. // bufPool stores pointers to scratch buffers.
var bufPool = sync.Pool{ var bufPool = sync.Pool{
New: func() interface{} { New: func() any {
return make([]byte, 0, 256) return make([]byte, 0, 256)
}, },
} }

View File

@@ -272,11 +272,10 @@ func BenchmarkReplacer(b *testing.B) {
r.AuthenticatedData = true r.AuthenticatedData = true
state := request.Request{W: w, Req: r} state := request.Request{W: w, Req: r}
b.ResetTimer()
b.ReportAllocs() b.ReportAllocs()
replacer := New() replacer := New()
for range b.N { for b.Loop() {
replacer.Replace(context.TODO(), state, nil, "{type} {name} {size}") replacer.Replace(context.TODO(), state, nil, "{type} {name} {size}")
} }
} }
@@ -295,15 +294,14 @@ func BenchmarkReplacer_CommonLogFormat(b *testing.B) {
replacer := New() replacer := New()
ctxt := context.TODO() ctxt := context.TODO()
b.ResetTimer()
b.ReportAllocs() b.ReportAllocs()
for range b.N { for b.Loop() {
replacer.Replace(ctxt, state, w, CommonLogFormat) replacer.Replace(ctxt, state, w, CommonLogFormat)
} }
} }
func BenchmarkParseFormat(b *testing.B) { func BenchmarkParseFormat(b *testing.B) {
for range b.N { for b.Loop() {
parseFormat(CommonLogFormat) parseFormat(CommonLogFormat)
} }
} }

View File

@@ -23,7 +23,7 @@ import "sync"
// call is an in-flight or completed Do call // call is an in-flight or completed Do call
type call struct { type call struct {
wg sync.WaitGroup wg sync.WaitGroup
val interface{} val any
err error err error
} }
@@ -38,7 +38,7 @@ type Group struct {
// sure that only one execution is in-flight for a given key at a // sure that only one execution is in-flight for a given key at a
// time. If a duplicate comes in, the duplicate caller waits for the // time. If a duplicate comes in, the duplicate caller waits for the
// original to complete and receives the same results. // original to complete and receives the same results.
func (g *Group) Do(key uint64, fn func() (interface{}, error)) (interface{}, error) { func (g *Group) Do(key uint64, fn func() (any, error)) (any, error) {
g.mu.Lock() g.mu.Lock()
if g.m == nil { if g.m == nil {
g.m = make(map[uint64]*call) g.m = make(map[uint64]*call)

View File

@@ -27,7 +27,7 @@ import (
func TestDo(t *testing.T) { func TestDo(t *testing.T) {
var g Group var g Group
v, err := g.Do(1, func() (interface{}, error) { v, err := g.Do(1, func() (any, error) {
return "bar", nil return "bar", nil
}) })
if got, want := fmt.Sprintf("%v (%T)", v, v), "bar (string)"; got != want { if got, want := fmt.Sprintf("%v (%T)", v, v), "bar (string)"; got != want {
@@ -41,7 +41,7 @@ func TestDo(t *testing.T) {
func TestDoErr(t *testing.T) { func TestDoErr(t *testing.T) {
var g Group var g Group
someErr := errors.New("some error") someErr := errors.New("some error")
v, err := g.Do(1, func() (interface{}, error) { v, err := g.Do(1, func() (any, error) {
return nil, someErr return nil, someErr
}) })
if err != someErr { if err != someErr {
@@ -56,7 +56,7 @@ func TestDoDupSuppress(t *testing.T) {
var g Group var g Group
c := make(chan string) c := make(chan string)
var calls int32 var calls int32
fn := func() (interface{}, error) { fn := func() (any, error) {
atomic.AddInt32(&calls, 1) atomic.AddInt32(&calls, 1)
return <-c, nil return <-c, nil
} }

View File

@@ -60,7 +60,7 @@ func parse(corefile caddy.Input) ([]byte, error) {
return json.Marshal(serverBlocks) return json.Marshal(serverBlocks)
} }
func hook(event caddy.EventName, info interface{}) error { func hook(event caddy.EventName, info any) error {
if event != caddy.InstanceStartupEvent { if event != caddy.InstanceStartupEvent {
return nil return nil
} }

View File

@@ -40,8 +40,8 @@ func (r *cnameTargetRule) getFromAndToTarget(inputCName string) (from string, to
case ExactMatch: case ExactMatch:
return r.paramFromTarget, r.paramToTarget return r.paramFromTarget, r.paramToTarget
case PrefixMatch: case PrefixMatch:
if strings.HasPrefix(inputCName, r.paramFromTarget) { if after, ok := strings.CutPrefix(inputCName, r.paramFromTarget); ok {
return inputCName, r.paramToTarget + strings.TrimPrefix(inputCName, r.paramFromTarget) return inputCName, r.paramToTarget + after
} }
case SuffixMatch: case SuffixMatch:
if strings.HasSuffix(inputCName, r.paramFromTarget) { if strings.HasSuffix(inputCName, r.paramFromTarget) {

View File

@@ -203,8 +203,8 @@ func newPrefixNameRule(nextAction string, auto bool, prefix, replacement string,
} }
func (rule *prefixNameRule) Rewrite(ctx context.Context, state request.Request) (ResponseRules, Result) { func (rule *prefixNameRule) Rewrite(ctx context.Context, state request.Request) (ResponseRules, Result) {
if strings.HasPrefix(state.Name(), rule.prefix) { if after, ok := strings.CutPrefix(state.Name(), rule.prefix); ok {
state.Req.Question[0].Name = rule.replacement + strings.TrimPrefix(state.Name(), rule.prefix) state.Req.Question[0].Name = rule.replacement + after
return rule.responseRuleFor(state) return rule.responseRuleFor(state)
} }
return nil, RewriteIgnored return nil, RewriteIgnored

View File

@@ -33,8 +33,7 @@ func TestRewriteIllegalName(t *testing.T) {
} }
func TestRewriteNamePrefixSuffix(t *testing.T) { func TestRewriteNamePrefixSuffix(t *testing.T) {
ctx, close := context.WithCancel(context.TODO()) ctx := t.Context()
defer close()
tests := []struct { tests := []struct {
next string next string
@@ -75,8 +74,7 @@ func TestRewriteNamePrefixSuffix(t *testing.T) {
} }
func TestRewriteNameNoRewrite(t *testing.T) { func TestRewriteNameNoRewrite(t *testing.T) {
ctx, close := context.WithCancel(context.TODO()) ctx := t.Context()
defer close()
tests := []struct { tests := []struct {
next string next string
@@ -117,8 +115,7 @@ func TestRewriteNameNoRewrite(t *testing.T) {
} }
func TestRewriteNamePrefixSuffixNoAutoAnswer(t *testing.T) { func TestRewriteNamePrefixSuffixNoAutoAnswer(t *testing.T) {
ctx, close := context.WithCancel(context.TODO()) ctx := t.Context()
defer close()
tests := []struct { tests := []struct {
next string next string
@@ -159,8 +156,7 @@ func TestRewriteNamePrefixSuffixNoAutoAnswer(t *testing.T) {
} }
func TestRewriteNamePrefixSuffixAutoAnswer(t *testing.T) { func TestRewriteNamePrefixSuffixAutoAnswer(t *testing.T) {
ctx, close := context.WithCancel(context.TODO()) ctx := t.Context()
defer close()
tests := []struct { tests := []struct {
next string next string
@@ -207,8 +203,7 @@ func TestRewriteNamePrefixSuffixAutoAnswer(t *testing.T) {
} }
func TestRewriteNameExactAnswer(t *testing.T) { func TestRewriteNameExactAnswer(t *testing.T) {
ctx, close := context.WithCancel(context.TODO()) ctx := t.Context()
defer close()
tests := []struct { tests := []struct {
next string next string
@@ -255,8 +250,7 @@ func TestRewriteNameExactAnswer(t *testing.T) {
} }
func TestRewriteNameRegexAnswer(t *testing.T) { func TestRewriteNameRegexAnswer(t *testing.T) {
ctx, close := context.WithCancel(context.TODO()) ctx := t.Context()
defer close()
tests := []struct { tests := []struct {
next string next string

View File

@@ -75,8 +75,7 @@ func (fakeRoute53) ListResourceRecordSets(_ context.Context, in *route53.ListRes
} }
func TestRoute53(t *testing.T) { func TestRoute53(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background()) ctx := t.Context()
defer cancel()
r, err := New(ctx, fakeRoute53{}, map[string][]string{"bad.": {"0987654321"}}, time.Minute) r, err := New(ctx, fakeRoute53{}, map[string][]string{"bad.": {"0987654321"}}, time.Minute)
if err != nil { if err != nil {

View File

@@ -1,7 +1,7 @@
package sign package sign
import ( import (
"sort" "slices"
"github.com/coredns/coredns/plugin/file" "github.com/coredns/coredns/plugin/file"
"github.com/coredns/coredns/plugin/file/tree" "github.com/coredns/coredns/plugin/file/tree"
@@ -26,7 +26,7 @@ func names(origin string, z *file.Zone) []string {
// NSEC returns an NSEC record according to name, next, ttl and bitmap. Note that the bitmap is sorted before use. // NSEC returns an NSEC record according to name, next, ttl and bitmap. Note that the bitmap is sorted before use.
func NSEC(name, next string, ttl uint32, bitmap []uint16) *dns.NSEC { func NSEC(name, next string, ttl uint32, bitmap []uint16) *dns.NSEC {
sort.Slice(bitmap, func(i, j int) bool { return bitmap[i] < bitmap[j] }) slices.Sort(bitmap)
return &dns.NSEC{ return &dns.NSEC{
Hdr: dns.RR_Header{Name: name, Ttl: ttl, Rrtype: dns.TypeNSEC, Class: dns.ClassINET}, Hdr: dns.RR_Header{Name: name, Ttl: ttl, Rrtype: dns.TypeNSEC, Class: dns.ClassINET},

View File

@@ -36,10 +36,10 @@ import (
type ( type (
// MetricFamily holds a prometheus metric. // MetricFamily holds a prometheus metric.
MetricFamily struct { MetricFamily struct {
Name string `json:"name"` Name string `json:"name"`
Help string `json:"help"` Help string `json:"help"`
Type string `json:"type"` Type string `json:"type"`
Metrics []interface{} `json:"metrics,omitempty"` // Either metric or summary. Metrics []any `json:"metrics,omitempty"` // Either metric or summary.
} }
// metric is for all "single value" metrics. // metric is for all "single value" metrics.
@@ -150,7 +150,7 @@ func newMetricFamily(dtoMF *dto.MetricFamily) *MetricFamily {
Name: dtoMF.GetName(), Name: dtoMF.GetName(),
Help: dtoMF.GetHelp(), Help: dtoMF.GetHelp(),
Type: dtoMF.GetType().String(), Type: dtoMF.GetType().String(),
Metrics: make([]interface{}, len(dtoMF.GetMetric())), Metrics: make([]any, len(dtoMF.GetMetric())),
} }
for i, m := range dtoMF.GetMetric() { for i, m := range dtoMF.GetMetric() {
if dtoMF.GetType() == dto.MetricType_SUMMARY { if dtoMF.GetType() == dto.MetricType_SUMMARY {

View File

@@ -319,7 +319,7 @@ func TestRequestMatch(t *testing.T) {
func BenchmarkRequestDo(b *testing.B) { func BenchmarkRequestDo(b *testing.B) {
st := testRequest() st := testRequest()
for range b.N { for b.Loop() {
st.Do() st.Do()
} }
} }
@@ -327,7 +327,7 @@ func BenchmarkRequestDo(b *testing.B) {
func BenchmarkRequestSize(b *testing.B) { func BenchmarkRequestSize(b *testing.B) {
st := testRequest() st := testRequest()
for range b.N { for b.Loop() {
st.Size() st.Size()
} }
} }
@@ -346,8 +346,7 @@ func BenchmarkRequestScrub(b *testing.B) {
fmt.Sprintf("10-0-0-%d.default.pod.k8s.example.com. 10 IN A 10.0.0.%d", i, i))) fmt.Sprintf("10-0-0-%d.default.pod.k8s.example.com. 10 IN A 10.0.0.%d", i, i)))
} }
b.ResetTimer() for b.Loop() {
for range b.N {
st.Scrub(reply.Copy()) st.Scrub(reply.Copy())
} }
} }

View File

@@ -70,8 +70,7 @@ func BenchmarkProxyLookup(b *testing.B) {
m := new(dns.Msg) m := new(dns.Msg)
m.SetQuestion("example.org.", dns.TypeA) m.SetQuestion("example.org.", dns.TypeA)
b.ResetTimer() for b.Loop() {
for range b.N {
if _, err := dns.Exchange(m, udp); err != nil { if _, err := dns.Exchange(m, udp); err != nil {
b.Fatal("Expected to receive reply, but didn't") b.Fatal("Expected to receive reply, but didn't")
} }