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.
 
 
 

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