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.3 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.Append", appendModifierFromJSON)
  24. }
  25. type appendModifier struct {
  26. name, value string
  27. }
  28. type appendModifierJSON struct {
  29. Name string `json:"name"`
  30. Value string `json:"value"`
  31. Scope []parse.ModifierType `json:"scope"`
  32. }
  33. // ModifyRequest appends the header at name with value to the request.
  34. func (m *appendModifier) ModifyRequest(req *http.Request) error {
  35. return proxyutil.RequestHeader(req).Add(m.name, m.value)
  36. }
  37. // ModifyResponse appends the header at name with value to the response.
  38. func (m *appendModifier) ModifyResponse(res *http.Response) error {
  39. return proxyutil.ResponseHeader(res).Add(m.name, m.value)
  40. }
  41. // NewAppendModifier returns an appendModifier that will append a header with
  42. // with the given name and value for both requests and responses. Existing
  43. // headers with the same name will be left in place.
  44. func NewAppendModifier(name, value string) martian.RequestResponseModifier {
  45. return &appendModifier{
  46. name: http.CanonicalHeaderKey(name),
  47. value: value,
  48. }
  49. }
  50. // appendModifierFromJSON takes a JSON message as a byte slice and returns
  51. // an appendModifier and an error.
  52. //
  53. // Example JSON configuration message:
  54. // {
  55. // "scope": ["request", "result"],
  56. // "name": "X-Martian",
  57. // "value": "true"
  58. // }
  59. func appendModifierFromJSON(b []byte) (*parse.Result, error) {
  60. msg := &modifierJSON{}
  61. if err := json.Unmarshal(b, msg); err != nil {
  62. return nil, err
  63. }
  64. modifier := NewAppendModifier(msg.Name, msg.Value)
  65. return parse.NewResult(modifier, msg.Scope)
  66. }