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.
 
 
 

74 lines
2.0 KiB

  1. // Copyright 2015 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. import (
  16. "net/http"
  17. "net/url"
  18. "github.com/google/martian/log"
  19. )
  20. // Matcher is a conditional evaluator of request urls to be used in
  21. // filters that take conditionals.
  22. type Matcher struct {
  23. url *url.URL
  24. }
  25. // NewMatcher builds a new url matcher.
  26. func NewMatcher(url *url.URL) *Matcher {
  27. return &Matcher{
  28. url: url,
  29. }
  30. }
  31. // MatchRequest retuns true if all non-empty URL segments in m.url match the
  32. // request URL.
  33. func (m *Matcher) MatchRequest(req *http.Request) bool {
  34. matched := m.matches(req.URL)
  35. if matched {
  36. log.Debugf("martianurl.Matcher.MatchRequest: matched: %s", req.URL)
  37. }
  38. return matched
  39. }
  40. // MatchResponse retuns true if all non-empty URL segments in m.url match the
  41. // request URL.
  42. func (m *Matcher) MatchResponse(res *http.Response) bool {
  43. matched := m.matches(res.Request.URL)
  44. if matched {
  45. log.Debugf("martianurl.Matcher.MatchResponse: matched: %s", res.Request.URL)
  46. }
  47. return matched
  48. }
  49. // matches forces all non-empty URL segments to match or it returns false.
  50. func (m *Matcher) matches(u *url.URL) bool {
  51. switch {
  52. case m.url.Scheme != "" && m.url.Scheme != u.Scheme:
  53. return false
  54. case m.url.Host != "" && !MatchHost(u.Host, m.url.Host):
  55. return false
  56. case m.url.Path != "" && m.url.Path != u.Path:
  57. return false
  58. case m.url.RawQuery != "" && m.url.RawQuery != u.RawQuery:
  59. return false
  60. case m.url.Fragment != "" && m.url.Fragment != u.Fragment:
  61. return false
  62. }
  63. return true
  64. }