github.com/google/martian/v3@v3.3.3/header/header_modifier.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 header 16 17 import ( 18 "encoding/json" 19 "net/http" 20 21 "github.com/google/martian/v3" 22 "github.com/google/martian/v3/parse" 23 "github.com/google/martian/v3/proxyutil" 24 ) 25 26 func init() { 27 parse.Register("header.Modifier", modifierFromJSON) 28 } 29 30 type modifier struct { 31 name, value string 32 } 33 34 type modifierJSON struct { 35 Name string `json:"name"` 36 Value string `json:"value"` 37 Scope []parse.ModifierType `json:"scope"` 38 } 39 40 // ModifyRequest sets the header at name with value on the request. 41 func (m *modifier) ModifyRequest(req *http.Request) error { 42 return proxyutil.RequestHeader(req).Set(m.name, m.value) 43 } 44 45 // ModifyResponse sets the header at name with value on the response. 46 func (m *modifier) ModifyResponse(res *http.Response) error { 47 return proxyutil.ResponseHeader(res).Set(m.name, m.value) 48 } 49 50 // NewModifier returns a modifier that will set the header at name with 51 // the given value for both requests and responses. If the header name already 52 // exists all values will be overwritten. 53 func NewModifier(name, value string) martian.RequestResponseModifier { 54 return &modifier{ 55 name: http.CanonicalHeaderKey(name), 56 value: value, 57 } 58 } 59 60 // modifierFromJSON takes a JSON message as a byte slice and returns 61 // a headerModifier and an error. 62 // 63 // Example JSON configuration message: 64 // { 65 // "scope": ["request", "result"], 66 // "name": "X-Martian", 67 // "value": "true" 68 // } 69 func modifierFromJSON(b []byte) (*parse.Result, error) { 70 msg := &modifierJSON{} 71 if err := json.Unmarshal(b, msg); err != nil { 72 return nil, err 73 } 74 75 modifier := NewModifier(msg.Name, msg.Value) 76 77 return parse.NewResult(modifier, msg.Scope) 78 }