forked from openshift/origin
-
Notifications
You must be signed in to change notification settings - Fork 1
/
remotevalue.go
46 lines (41 loc) · 1.26 KB
/
remotevalue.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
package examples
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"strings"
)
// RemoteValueGenerator implements GeneratorInterface. It fetches random value
// from an external url endpoint based on the "[GET:<url>]" input expression.
//
// Example:
// - "[GET:http://api.example.com/generateRandomValue]"
type RemoteValueGenerator struct {
}
var remoteExp = regexp.MustCompile(`\[GET\:(http(s)?:\/\/(.+))\]`)
// NewRemoteValueGenerator creates new RemoteValueGenerator.
func NewRemoteValueGenerator() RemoteValueGenerator {
return RemoteValueGenerator{}
}
// GenerateValue fetches random value from an external url. The input
// expression must be of the form "[GET:<url>]".
func (g RemoteValueGenerator) GenerateValue(expression string) (interface{}, error) {
matches := remoteExp.FindAllStringIndex(expression, -1)
if len(matches) < 1 {
return expression, fmt.Errorf("no matches found.")
}
for _, r := range matches {
response, err := http.Get(expression[5 : len(expression)-1])
if err != nil {
return "", err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return "", err
}
expression = strings.Replace(expression, expression[r[0]:r[1]], strings.TrimSpace(string(body)), 1)
}
return expression, nil
}