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