Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.
 
 
 

80 linhas
2.4 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 stash provides a modifier that stores the request URL in a
  15. // specified header.
  16. package stash
  17. import (
  18. "encoding/json"
  19. "fmt"
  20. "net/http"
  21. "github.com/google/martian/parse"
  22. )
  23. func init() {
  24. parse.Register("stash.Modifier", modifierFromJSON)
  25. }
  26. // Modifier adds a header to the request containing the current state of the URL.
  27. // The header will be named with the value stored in headerName.
  28. // There will be no validation done on this header name.
  29. type Modifier struct {
  30. headerName string
  31. }
  32. type modifierJSON struct {
  33. HeaderName string `json:"headerName"`
  34. Scope []parse.ModifierType `json:"scope"`
  35. }
  36. // NewModifier returns a RequestModifier that write the current URL into a header.
  37. func NewModifier(headerName string) *Modifier {
  38. return &Modifier{headerName: headerName}
  39. }
  40. // ModifyRequest writes the current URL into a header.
  41. func (m *Modifier) ModifyRequest(req *http.Request) error {
  42. req.Header.Set(m.headerName, req.URL.String())
  43. return nil
  44. }
  45. // ModifyResponse writes the same header written in the request into the response.
  46. func (m *Modifier) ModifyResponse(res *http.Response) error {
  47. res.Header.Set(m.headerName, res.Request.Header.Get(m.headerName))
  48. return nil
  49. }
  50. func modifierFromJSON(b []byte) (*parse.Result, error) {
  51. // If you would like the saved state of the URL to be written in the response you must specify
  52. // this modifier's scope as both request and response.
  53. msg := &modifierJSON{}
  54. if err := json.Unmarshal(b, msg); err != nil {
  55. return nil, err
  56. }
  57. mod := NewModifier(msg.HeaderName)
  58. r, err := parse.NewResult(mod, msg.Scope)
  59. if err != nil {
  60. return nil, err
  61. }
  62. if r.ResponseModifier() != nil && r.RequestModifier() == nil {
  63. return nil, fmt.Errorf("to write header on a response, specify scope as both request and response")
  64. }
  65. return r, nil
  66. }