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