github.com/google/martian/v3@v3.3.3/cookie/cookie_matcher.go (about) 1 // Copyright 2017 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 cookie 16 17 import ( 18 "net/http" 19 20 "github.com/google/martian/v3/log" 21 ) 22 23 // Matcher is a conditonal evalutor of request or 24 // response cookies to be used in structs that take conditions. 25 type Matcher struct { 26 cookie *http.Cookie 27 } 28 29 // NewMatcher builds a cookie matcher. 30 func NewMatcher(cookie *http.Cookie) *Matcher { 31 return &Matcher{ 32 cookie: cookie, 33 } 34 } 35 36 // MatchRequest evaluates a request and returns whether or not 37 // the request contains a cookie that matches the provided name, path 38 // and value. 39 func (m *Matcher) MatchRequest(req *http.Request) bool { 40 for _, c := range req.Cookies() { 41 if m.match(c) { 42 log.Debugf("cookie.MatchRequest: %s, matched: cookie: %s", req.URL, c) 43 return true 44 } 45 } 46 47 return false 48 } 49 50 // MatchResponse evaluates a response and returns whether or not the response 51 // contains a cookie that matches the provided name and value. 52 func (m *Matcher) MatchResponse(res *http.Response) bool { 53 for _, c := range res.Cookies() { 54 if m.match(c) { 55 log.Debugf("cookie.MatchResponse: %s, matched: cookie: %s", res.Request.URL, c) 56 return true 57 } 58 } 59 60 return false 61 } 62 63 func (m *Matcher) match(cs *http.Cookie) bool { 64 switch { 65 case m.cookie.Name != cs.Name: 66 return false 67 case m.cookie.Value != "" && m.cookie.Value != cs.Value: 68 return false 69 } 70 71 return true 72 }