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.
 
 
 

77 satır
2.0 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 contains a modifier to rewrite query strings in a request.
  15. package querystring
  16. import (
  17. "encoding/json"
  18. "net/http"
  19. "github.com/google/martian"
  20. "github.com/google/martian/parse"
  21. )
  22. func init() {
  23. parse.Register("querystring.Modifier", modifierFromJSON)
  24. }
  25. type modifier struct {
  26. key, value string
  27. }
  28. type modifierJSON struct {
  29. Name string `json:"name"`
  30. Value string `json:"value"`
  31. Scope []parse.ModifierType `json:"scope"`
  32. }
  33. // ModifyRequest modifies the query string of the request with the given key and value.
  34. func (m *modifier) ModifyRequest(req *http.Request) error {
  35. query := req.URL.Query()
  36. query.Set(m.key, m.value)
  37. req.URL.RawQuery = query.Encode()
  38. return nil
  39. }
  40. // NewModifier returns a request modifier that will set the query string
  41. // at key with the given value. If the query string key already exists all
  42. // values will be overwritten.
  43. func NewModifier(key, value string) martian.RequestModifier {
  44. return &modifier{
  45. key: key,
  46. value: value,
  47. }
  48. }
  49. // modifierFromJSON takes a JSON message as a byte slice and returns
  50. // a querystring.modifier and an error.
  51. //
  52. // Example JSON:
  53. // {
  54. // "name": "param",
  55. // "value": "true",
  56. // "scope": ["request", "response"]
  57. // }
  58. func modifierFromJSON(b []byte) (*parse.Result, error) {
  59. msg := &modifierJSON{}
  60. if err := json.Unmarshal(b, msg); err != nil {
  61. return nil, err
  62. }
  63. return parse.NewResult(NewModifier(msg.Name, msg.Value), msg.Scope)
  64. }