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