|
| 1 | +package route |
| 2 | + |
| 3 | +import ( |
| 4 | + "encoding/json" |
| 5 | + "fmt" |
| 6 | + "strings" |
| 7 | + |
| 8 | + "github.com/layou233/zbproxy/v3/adapter" |
| 9 | + "github.com/layou233/zbproxy/v3/common/jsonx" |
| 10 | + "github.com/layou233/zbproxy/v3/common/set" |
| 11 | + "github.com/layou233/zbproxy/v3/config" |
| 12 | +) |
| 13 | + |
| 14 | +type RuleServiceName struct { |
| 15 | + sets []set.StringSet |
| 16 | + config *config.Rule |
| 17 | +} |
| 18 | + |
| 19 | +var _ Rule = (*RuleServiceName)(nil) |
| 20 | + |
| 21 | +func NewServiceNameRule(newConfig *config.Rule, listMap map[string]set.StringSet) (Rule, error) { |
| 22 | + var serviceList jsonx.Listable[string] |
| 23 | + err := json.Unmarshal(newConfig.Parameter, &serviceList) |
| 24 | + if err != nil { |
| 25 | + return nil, fmt.Errorf("bad service name list %v: %w", newConfig.Parameter, err) |
| 26 | + } |
| 27 | + sets := []set.StringSet{ |
| 28 | + {}, // new set for individual names |
| 29 | + } |
| 30 | + for _, i := range serviceList { |
| 31 | + if strings.HasPrefix(i, parameterListPrefix) { |
| 32 | + i = strings.TrimPrefix(i, parameterListPrefix) |
| 33 | + nameSet, found := listMap[i] |
| 34 | + if !found { |
| 35 | + return nil, fmt.Errorf("list [%v] is not found", i) |
| 36 | + } |
| 37 | + sets = append(sets, nameSet) |
| 38 | + } else { |
| 39 | + sets[0].Add(i) |
| 40 | + } |
| 41 | + } |
| 42 | + return &RuleServiceName{ |
| 43 | + sets: sets, |
| 44 | + config: newConfig, |
| 45 | + }, nil |
| 46 | +} |
| 47 | + |
| 48 | +func (r RuleServiceName) Config() *config.Rule { |
| 49 | + return r.config |
| 50 | +} |
| 51 | + |
| 52 | +func (r RuleServiceName) Match(metadata *adapter.Metadata) (match bool) { |
| 53 | + for _, nameSet := range r.sets { |
| 54 | + match = nameSet.Has(metadata.ServiceName) |
| 55 | + if match { |
| 56 | + break |
| 57 | + } |
| 58 | + } |
| 59 | + if r.config.Invert { |
| 60 | + match = !match |
| 61 | + } |
| 62 | + return |
| 63 | +} |
0 commit comments