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.
 
 
 

84 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/log"
  20. "github.com/google/martian/parse"
  21. "github.com/google/martian/proxyutil"
  22. )
  23. func init() {
  24. parse.Register("header.Copy", copyModifierFromJSON)
  25. }
  26. type copyModifier struct {
  27. from, to string
  28. }
  29. type copyModifierJSON struct {
  30. From string `json:"from"`
  31. To string `json:"to"`
  32. Scope []parse.ModifierType `json:"scope"`
  33. }
  34. // ModifyRequest copies the header in from to the request header for to.
  35. func (m *copyModifier) ModifyRequest(req *http.Request) error {
  36. log.Debugf("header: copyModifier.ModifyRequest %s, from: %s, to: %s", req.URL, m.from, m.to)
  37. h := proxyutil.RequestHeader(req)
  38. return h.Set(m.to, h.Get(m.from))
  39. }
  40. // ModifyResponse copies the header in from to the response header for to.
  41. func (m *copyModifier) ModifyResponse(res *http.Response) error {
  42. log.Debugf("header: copyModifier.ModifyResponse %s, from: %s, to: %s", res.Request.URL, m.from, m.to)
  43. h := proxyutil.ResponseHeader(res)
  44. return h.Set(m.to, h.Get(m.from))
  45. }
  46. // NewCopyModifier returns a modifier that will copy the header in from to the
  47. // header in to.
  48. func NewCopyModifier(from, to string) martian.RequestResponseModifier {
  49. return &copyModifier{
  50. from: from,
  51. to: to,
  52. }
  53. }
  54. // copyModifierFromJSON builds a copy modifier from JSON.
  55. //
  56. // Example JSON:
  57. // {
  58. // "header.Copy": {
  59. // "scope": ["request", "response"],
  60. // "from": "Original-Header",
  61. // "to": "Copy-Header"
  62. // }
  63. // }
  64. func copyModifierFromJSON(b []byte) (*parse.Result, error) {
  65. msg := &copyModifierJSON{}
  66. if err := json.Unmarshal(b, msg); err != nil {
  67. return nil, err
  68. }
  69. return parse.NewResult(NewCopyModifier(msg.From, msg.To), msg.Scope)
  70. }