You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

65 lines
1.6 KiB

  1. // Copyright 2016 Google Inc. All rights reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package martianurl
  15. // MatchHost matches two URL hosts with support for wildcards.
  16. func MatchHost(host, match string) bool {
  17. // Short circuit if host is empty.
  18. if host == "" {
  19. return false
  20. }
  21. // Exact match, no need to loop.
  22. if host == match {
  23. return true
  24. }
  25. // Walk backward over the host.
  26. hi := len(host) - 1
  27. for mi := len(match) - 1; mi >= 0; mi-- {
  28. // Found wildcard, skip to next period.
  29. if match[mi] == '*' {
  30. for hi > 0 && host[hi] != '.' {
  31. hi--
  32. }
  33. // Wildcard was the leftmost part and we have walked the entire host,
  34. // success.
  35. if mi == 0 && hi == 0 {
  36. return true
  37. }
  38. continue
  39. }
  40. if host[hi] != match[mi] {
  41. return false
  42. }
  43. // We have walked the entire host, if we have not walked the entire matcher
  44. // (mi != 0) that means the matcher has remaining characters to match and
  45. // thus the host cannot match.
  46. if hi == 0 {
  47. return mi == 0
  48. }
  49. hi--
  50. }
  51. // We have walked the entire length of the matcher, but haven't finished
  52. // walking the host thus they cannot match.
  53. return false
  54. }