-
Notifications
You must be signed in to change notification settings - Fork 1
/
querystring2body.go
78 lines (64 loc) · 1.71 KB
/
querystring2body.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package rzluramartian
import (
"bytes"
"encoding/json"
"html/template"
"io/ioutil"
"net/http"
"github.com/google/martian/parse"
)
const (
_contentType_applicationJSON = "application/json"
_contentType_applicationXML = "application/xml"
_contentTypeHeader = "Content-Type"
)
type (
QueryModifierConfig struct {
KeysToExtract []string `json:"keys_to_extract"`
Template string `json:"template"`
ContentType string `json:"content_type"`
}
Query2BodyModifier struct {
keysToExtract []string
template *template.Template
ContentType string
}
)
func queryModifierFromJSON(b []byte) (*parse.Result, error) {
cfg := &QueryModifierConfig{}
if err := json.Unmarshal(b, cfg); err != nil {
return nil, err
}
tmpl, err := template.New("query2body_modifier").Parse(cfg.Template)
if err != nil {
return nil, err
}
mod := &Query2BodyModifier{
keysToExtract: cfg.KeysToExtract,
template: tmpl,
ContentType: cfg.ContentType,
}
return parse.NewResult(mod, []parse.ModifierType{parse.Request})
}
func (m *Query2BodyModifier) ModifyRequest(req *http.Request) error {
query := req.URL.Query()
buf := new(bytes.Buffer)
if err := m.template.Execute(buf, query); err != nil {
return nil
}
for _, k := range m.keysToExtract {
query.Del(k)
}
req.ContentLength = int64(buf.Len())
req.Body = ioutil.NopCloser(buf)
req.URL.RawQuery = query.Encode()
if m.ContentType == "" && req.Header.Get("Content-Type") == "" {
// set default content-type header as application/json
req.Header.Set(_contentTypeHeader, _contentType_applicationJSON)
}
if m.ContentType != "" {
req.Header.Del(_contentTypeHeader)
req.Header.Set(_contentTypeHeader, m.ContentType)
}
return nil
}