-
Notifications
You must be signed in to change notification settings - Fork 0
/
stub.go
61 lines (53 loc) · 1.5 KB
/
stub.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
package main
import (
"fmt"
"io/ioutil"
"net/http"
"regexp"
"time"
"github.com/gorilla/mux"
)
func StubHandler(stub Stub) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
var err error
for key, value := range stub.Response.Headers {
w.Header().Set(key, value)
}
w.WriteHeader(stub.Response.Status)
response := []byte(stub.Response.Body)
if stub.Response.File != "" {
response, err = ioutil.ReadFile(stub.Response.File)
if err != nil {
printError(fmt.Sprintf("[%s %s] error reading file '%s': %s", r.Method, stub.Request.Path, stub.Response.File, err))
}
}
_, err = w.Write(response)
if err != nil {
printError(fmt.Sprintf("[%s %s] error writing response: %s", r.Method, stub.Request.Path, err))
}
if stub.Response.Latency != 0 {
time.Sleep(time.Duration(stub.Response.Latency) * time.Millisecond)
}
}
}
func QueryMatcher(query KeyValuePairs) func(*http.Request, *mux.RouteMatch) bool {
return func(r *http.Request, rm *mux.RouteMatch) bool {
urlQuery := r.URL.Query()
for key, value := range query {
if matched, _ := regexp.MatchString(value, urlQuery.Get(key)); !matched {
return false
}
}
return true
}
}
func HeadersMatcher(headers KeyValuePairs) func(*http.Request, *mux.RouteMatch) bool {
return func(r *http.Request, rm *mux.RouteMatch) bool {
for key, value := range headers {
if matched, _ := regexp.MatchString(value, r.Header.Get(key)); !matched {
return false
}
}
return true
}
}