cookie_matcher.go 1.9 KB

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