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.
 
 
 

93 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 querystring
  15. import (
  16. "encoding/json"
  17. "github.com/google/martian"
  18. "github.com/google/martian/filter"
  19. "github.com/google/martian/parse"
  20. )
  21. var noop = martian.Noop("querystring.Filter")
  22. func init() {
  23. parse.Register("querystring.Filter", filterFromJSON)
  24. }
  25. // Filter runs modifiers iff the request query parameter for name matches value.
  26. type Filter struct {
  27. *filter.Filter
  28. }
  29. type filterJSON struct {
  30. Name string `json:"name"`
  31. Value string `json:"value"`
  32. Modifier json.RawMessage `json:"modifier"`
  33. ElseModifier json.RawMessage `json:"else"`
  34. Scope []parse.ModifierType `json:"scope"`
  35. }
  36. // NewFilter builds a querystring.Filter that filters on name and optionally
  37. // value.
  38. func NewFilter(name, value string) *Filter {
  39. m := NewMatcher(name, value)
  40. f := filter.New()
  41. f.SetRequestCondition(m)
  42. f.SetResponseCondition(m)
  43. return &Filter{f}
  44. }
  45. // filterFromJSON takes a JSON message and returns a querystring.Filter.
  46. //
  47. // Example JSON:
  48. // {
  49. // "name": "param",
  50. // "value": "example",
  51. // "scope": ["request", "response"],
  52. // "modifier": { ... }
  53. // }
  54. func filterFromJSON(b []byte) (*parse.Result, error) {
  55. msg := &filterJSON{}
  56. if err := json.Unmarshal(b, msg); err != nil {
  57. return nil, err
  58. }
  59. f := NewFilter(msg.Name, msg.Value)
  60. r, err := parse.FromJSON(msg.Modifier)
  61. if err != nil {
  62. return nil, err
  63. }
  64. f.RequestWhenTrue(r.RequestModifier())
  65. f.ResponseWhenTrue(r.ResponseModifier())
  66. if len(msg.ElseModifier) > 0 {
  67. em, err := parse.FromJSON(msg.ElseModifier)
  68. if err != nil {
  69. return nil, err
  70. }
  71. if em != nil {
  72. f.RequestWhenFalse(em.RequestModifier())
  73. f.ResponseWhenFalse(em.ResponseModifier())
  74. }
  75. }
  76. return parse.NewResult(f, msg.Scope)
  77. }