Skip to content

Commit

Permalink
chore(pkg/middlewares): use settings for cache and filter constructor…
Browse files Browse the repository at this point in the history
…s (future proofing for compatibility)
  • Loading branch information
qdm12 committed Nov 15, 2023
1 parent e07c215 commit b2f7d28
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 6 deletions.
13 changes: 10 additions & 3 deletions pkg/middlewares/cache/middleware.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cache

import (
"fmt"

"github.com/miekg/dns"
"github.com/qdm12/dns/v2/internal/stateful"
)
Expand All @@ -9,10 +11,15 @@ type Middleware struct {
cache Cache
}

func New(cache Cache) *Middleware {
return &Middleware{
cache: cache,
func New(settings Settings) (middleware *Middleware, err error) {
err = settings.Validate()
if err != nil {
return nil, fmt.Errorf("settings validation: %w", err)
}

return &Middleware{
cache: settings.Cache,
}, nil
}

func (m *Middleware) Wrap(next dns.Handler) dns.Handler { //nolint:ireturn
Expand Down
22 changes: 22 additions & 0 deletions pkg/middlewares/cache/settings.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package cache

import (
"errors"
"fmt"
)

type Settings struct {
Cache Cache
}

var (
ErrCacheMustBeSet = errors.New("cache must be set")
)

func (s *Settings) Validate() (err error) {
if s.Cache == nil {
return fmt.Errorf("%w", ErrCacheMustBeSet)
}

return nil
}
13 changes: 10 additions & 3 deletions pkg/middlewares/filter/middleware.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package filter

import (
"fmt"

"github.com/miekg/dns"
"github.com/qdm12/dns/v2/internal/stateful"
)
Expand All @@ -9,10 +11,15 @@ type Middleware struct {
filter Filter
}

func New(filter Filter) *Middleware {
return &Middleware{
filter: filter,
func New(settings Settings) (middleware *Middleware, err error) {
err = settings.Validate()
if err != nil {
return nil, fmt.Errorf("settings validation: %w", err)
}

return &Middleware{
filter: settings.Filter,
}, nil
}

func (m *Middleware) Wrap(next dns.Handler) dns.Handler { //nolint:ireturn
Expand Down
22 changes: 22 additions & 0 deletions pkg/middlewares/filter/settings.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package filter

import (
"errors"
"fmt"
)

type Settings struct {
Filter Filter
}

var (
ErrFilterMustBeSet = errors.New("filter must be set")
)

func (s *Settings) Validate() (err error) {
if s.Filter == nil {
return fmt.Errorf("%w", ErrFilterMustBeSet)
}

return nil
}

0 comments on commit b2f7d28

Please sign in to comment.