1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-06-27 01:45:23 +00:00
v2fly/app/router/rules/router.go

58 lines
1.0 KiB
Go
Raw Normal View History

2015-11-14 13:24:56 +00:00
package rules
2015-11-22 11:05:21 +00:00
import (
"errors"
"github.com/v2ray/v2ray-core/app/router"
v2net "github.com/v2ray/v2ray-core/common/net"
)
var (
2015-11-22 16:41:52 +00:00
InvalidRule = errors.New("Invalid Rule")
NoRuleApplicable = errors.New("No rule applicable")
2015-11-22 11:05:21 +00:00
)
type Router struct {
2015-12-07 21:47:47 +00:00
rules []Rule
}
func NewRouter() *Router {
return &Router{
rules: make([]Rule, 0, 16),
}
}
func (this *Router) AddRule(rule Rule) *Router {
this.rules = append(this.rules, rule)
return this
2015-11-22 11:05:21 +00:00
}
func (this *Router) TakeDetour(dest v2net.Destination) (string, error) {
2015-11-22 11:05:21 +00:00
for _, rule := range this.rules {
if rule.Apply(dest) {
return rule.Tag(), nil
}
}
return "", NoRuleApplicable
2015-11-22 11:05:21 +00:00
}
type RouterFactory struct {
}
func (this *RouterFactory) Create(rawConfig interface{}) (router.Router, error) {
2015-12-07 21:47:47 +00:00
config := rawConfig.(RouterRuleConfig)
2015-11-22 11:05:21 +00:00
rules := config.Rules()
2015-12-07 21:47:47 +00:00
router := NewRouter()
2015-11-22 11:05:21 +00:00
for _, rule := range rules {
if rule == nil {
return nil, InvalidRule
}
2015-12-07 21:47:47 +00:00
router.AddRule(rule)
2015-11-22 11:05:21 +00:00
}
2015-12-07 21:47:47 +00:00
return router, nil
2015-11-22 11:05:21 +00:00
}
func init() {
router.RegisterRouter("rules", &RouterFactory{})
}