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.
 
 
 

76 lines
1.7 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 header
  15. import (
  16. "net/http"
  17. "github.com/google/martian/proxyutil"
  18. )
  19. // Matcher is a conditonal evalutor of request or
  20. // response headers to be used in structs that take conditions.
  21. type Matcher struct {
  22. name, value string
  23. }
  24. // NewMatcher builds a new header matcher.
  25. func NewMatcher(name, value string) *Matcher {
  26. return &Matcher{
  27. name: name,
  28. value: value,
  29. }
  30. }
  31. // MatchRequest evaluates a request and returns whether or not
  32. // the request contains a header that matches the provided name
  33. // and value.
  34. func (m *Matcher) MatchRequest(req *http.Request) bool {
  35. h := proxyutil.RequestHeader(req)
  36. vs, ok := h.All(m.name)
  37. if !ok {
  38. return false
  39. }
  40. for _, v := range vs {
  41. if v == m.value {
  42. return true
  43. }
  44. }
  45. return false
  46. }
  47. // MatchResponse evaluates a response and returns whether or not
  48. // the response contains a header that matches the provided name
  49. // and value.
  50. func (m *Matcher) MatchResponse(res *http.Response) bool {
  51. h := proxyutil.ResponseHeader(res)
  52. vs, ok := h.All(m.name)
  53. if !ok {
  54. return false
  55. }
  56. for _, v := range vs {
  57. if v == m.value {
  58. return true
  59. }
  60. }
  61. return false
  62. }