25'ten fazla konu seçemezsiniz Konular bir harf veya rakamla başlamalı, kısa çizgiler ('-') içerebilir ve en fazla 35 karakter uzunluğunda olabilir.
 
 
 

94 satır
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/filter"
  20. "github.com/google/martian/parse"
  21. )
  22. var noop = martian.Noop("header.Filter")
  23. // Filter filters requests and responses based on header name and value.
  24. type Filter struct {
  25. *filter.Filter
  26. }
  27. type filterJSON struct {
  28. Name string `json:"name"`
  29. Value string `json:"value"`
  30. Modifier json.RawMessage `json:"modifier"`
  31. ElseModifier json.RawMessage `json:"else"`
  32. Scope []parse.ModifierType `json:"scope"`
  33. }
  34. func init() {
  35. parse.Register("header.Filter", filterFromJSON)
  36. }
  37. // NewFilter builds a new header filter.
  38. func NewFilter(name, value string) *Filter {
  39. m := NewMatcher(http.CanonicalHeaderKey(name), value)
  40. f := filter.New()
  41. f.SetRequestCondition(m)
  42. f.SetResponseCondition(m)
  43. return &Filter{f}
  44. }
  45. // filterFromJSON builds a header.Filter from JSON.
  46. //
  47. // Example JSON:
  48. // {
  49. // "scope": ["request", "result"],
  50. // "name": "Martian-Testing",
  51. // "value": "true",
  52. // "modifier": { ... },
  53. // "else": { ... }
  54. // }
  55. func filterFromJSON(b []byte) (*parse.Result, error) {
  56. msg := &filterJSON{}
  57. if err := json.Unmarshal(b, msg); err != nil {
  58. return nil, err
  59. }
  60. filter := NewFilter(msg.Name, msg.Value)
  61. m, err := parse.FromJSON(msg.Modifier)
  62. if err != nil {
  63. return nil, err
  64. }
  65. filter.RequestWhenTrue(m.RequestModifier())
  66. filter.ResponseWhenTrue(m.ResponseModifier())
  67. if len(msg.ElseModifier) > 0 {
  68. em, err := parse.FromJSON(msg.ElseModifier)
  69. if err != nil {
  70. return nil, err
  71. }
  72. if em != nil {
  73. filter.RequestWhenFalse(em.RequestModifier())
  74. filter.ResponseWhenFalse(em.ResponseModifier())
  75. }
  76. }
  77. return parse.NewResult(filter, msg.Scope)
  78. }