-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtarget.go
91 lines (74 loc) · 1.83 KB
/
target.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
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"bytes"
"errors"
"net/http"
"text/template"
"github.com/Masterminds/sprig"
vegeta "github.com/tsenart/vegeta/lib"
)
var (
errUndefinedTemplate = errors.New("Undefined template")
)
type Target struct {
URL string `yaml:"url"`
Method string `yaml:"method"`
Boby string `yaml:"body"`
Repeat int `yaml:"repeat"`
Headers map[string]string `yaml:"headers"`
header http.Header
pathTemplate *template.Template
bodyTemplate *template.Template
}
func (t *Target) parseTemplate() error {
pTpl, err := template.New("path").Funcs(sprig.TxtFuncMap()).Parse(t.URL)
if err != nil {
return err
}
t.pathTemplate = pTpl
if t.Boby != "" && t.Method != http.MethodGet {
bTpl, err := template.New("body").Funcs(sprig.TxtFuncMap()).Parse(t.Boby)
if err != nil {
return err
}
t.bodyTemplate = bTpl
}
return nil
}
func (t *Target) interpolatePath(data interface{}) (string, error) {
if t.pathTemplate == nil {
return "", errUndefinedTemplate
}
var buf bytes.Buffer
if err := t.pathTemplate.Execute(&buf, data); err != nil {
return "", err
}
return buf.String(), nil
}
func (t *Target) interpolateBody(data interface{}) (string, error) {
if t.bodyTemplate == nil {
return "", errUndefinedTemplate
}
var buf bytes.Buffer
if err := t.bodyTemplate.Execute(&buf, data); err != nil {
return "", err
}
return buf.String(), nil
}
func (t *Target) toVegetaTarget(target *vegeta.Target, data interface{}) error {
target.Method = t.Method
target.Header = t.header
path, err := t.interpolatePath(data)
if err != nil {
return err
}
target.URL = path
if t.Boby != "" && t.Method != http.MethodGet {
body, err := t.interpolateBody(data)
if err != nil {
return err
}
target.Body = []byte(body)
}
return nil
}