refactor: Extract services form router

This commit is contained in:
世界
2024-11-10 16:46:59 +08:00
parent 606abff177
commit dea80da0eb
27 changed files with 314 additions and 464 deletions

View File

@@ -219,7 +219,7 @@ func NewDefaultRule(ctx context.Context, logger log.ContextLogger, options optio
rule.allItems = append(rule.allItems, item)
}
if options.ClashMode != "" {
item := NewClashModeItem(router, options.ClashMode)
item := NewClashModeItem(ctx, options.ClashMode)
rule.items = append(rule.items, item)
rule.allItems = append(rule.allItems, item)
}

View File

@@ -216,7 +216,7 @@ func NewDefaultDNSRule(ctx context.Context, logger log.ContextLogger, options op
rule.allItems = append(rule.allItems, item)
}
if options.ClashMode != "" {
item := NewClashModeItem(router, options.ClashMode)
item := NewClashModeItem(ctx, options.ClashMode)
rule.items = append(rule.items, item)
rule.allItems = append(rule.allItems, item)
}

View File

@@ -1,31 +1,38 @@
package rule
import (
"context"
"strings"
"github.com/sagernet/sing-box/adapter"
"github.com/sagernet/sing/service"
)
var _ RuleItem = (*ClashModeItem)(nil)
type ClashModeItem struct {
router adapter.Router
mode string
ctx context.Context
clashServer adapter.ClashServer
mode string
}
func NewClashModeItem(router adapter.Router, mode string) *ClashModeItem {
func NewClashModeItem(ctx context.Context, mode string) *ClashModeItem {
return &ClashModeItem{
router: router,
mode: mode,
ctx: ctx,
mode: mode,
}
}
func (r *ClashModeItem) Start() error {
r.clashServer = service.FromContext[adapter.ClashServer](r.ctx)
return nil
}
func (r *ClashModeItem) Match(metadata *adapter.InboundContext) bool {
clashServer := r.router.ClashServer()
if clashServer == nil {
if r.clashServer == nil {
return false
}
return strings.EqualFold(clashServer.Mode(), r.mode)
return strings.EqualFold(r.clashServer.Mode(), r.mode)
}
func (r *ClashModeItem) String() string {