domain_matcher.go 919 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package strmatcher
  2. import "strings"
  3. func breakDomain(domain string) []string {
  4. return strings.Split(domain, ".")
  5. }
  6. type node struct {
  7. value uint32
  8. sub map[string]*node
  9. }
  10. type DomainMatcherGroup struct {
  11. root *node
  12. }
  13. func (g *DomainMatcherGroup) Add(domain string, value uint32) {
  14. if g.root == nil {
  15. g.root = &node{
  16. sub: make(map[string]*node),
  17. }
  18. }
  19. current := g.root
  20. parts := breakDomain(domain)
  21. for i := len(parts) - 1; i >= 0; i-- {
  22. part := parts[i]
  23. next := current.sub[part]
  24. if next == nil {
  25. next = &node{sub: make(map[string]*node)}
  26. current.sub[part] = next
  27. }
  28. current = next
  29. }
  30. current.value = value
  31. }
  32. func (g *DomainMatcherGroup) Match(domain string) uint32 {
  33. current := g.root
  34. parts := breakDomain(domain)
  35. for i := len(parts) - 1; i >= 0; i-- {
  36. part := parts[i]
  37. next := current.sub[part]
  38. if next == nil {
  39. break
  40. }
  41. current = next
  42. }
  43. return current.value
  44. }