/
imposter.go
101 lines (83 loc) · 2.32 KB
/
imposter.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
92
93
94
95
96
97
98
99
100
101
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"github.com/go-martini/martini"
"github.com/martini-contrib/encoder"
)
type Error struct {
Message string `json:"message"`
}
type PresetList []Preset
type Presets map[string]PresetList
func (this Presets) Add(preset *Preset) {
rule := rule(preset.Matcher.Method, preset.Matcher.Endpoint)
presets_for_rule, ok := this[rule]
if !ok {
presets_for_rule = PresetList(make([]Preset, 0, 5))
}
presets_for_rule = append(presets_for_rule, *preset)
this[rule] = presets_for_rule
}
var presets = Presets(make(map[string]PresetList))
func rule(method string, endpoint string) string {
return fmt.Sprintf("%s %s", method, endpoint)
}
func GetPreset(enc encoder.Encoder, w http.ResponseWriter) (int, []byte) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
return http.StatusOK, encoder.Must(enc.Encode(&presets))
}
func CreatePreset(
params martini.Params, w http.ResponseWriter,
r *http.Request, enc encoder.Encoder) (int, []byte) {
bytes, err := ioutil.ReadAll(r.Body)
if err != nil {
return http.StatusBadRequest,
encoder.Must(enc.Encode(&Error{err.Error()}))
}
preset := &Preset{}
err = json.Unmarshal(bytes, &preset)
if err != nil {
return http.StatusBadRequest,
encoder.Must(enc.Encode(&Error{err.Error()}))
}
presets.Add(preset)
w.Header().Set("Content-Type", "application/json; charset=utf-8")
return http.StatusCreated, encoder.Must(enc.Encode(preset))
}
func PresetRouter(r martini.Router) {
r.Get("/", GetPreset)
r.Post("/", CreatePreset)
}
func GetMock(req *http.Request, writer http.ResponseWriter, params martini.Params) (int, string) {
method := req.Method
endpoint := "/" + params["_1"]
presets, ok := presets[rule(method, endpoint)]
if !ok {
return http.StatusNotFound, ""
}
for _, preset := range presets {
if preset.Matcher.Match(req) {
for key, value := range preset.Response.Headers {
writer.Header().Set(key, value)
}
return preset.Response.StatusCode, preset.Response.Body
}
}
return 418, "Not a teapot :("
}
func MockRouter(r martini.Router) {
r.Get("/**", GetMock)
r.Post("/**", GetMock)
}
func main() {
m := martini.Classic()
m.Use(func(c martini.Context) {
c.MapTo(encoder.JsonEncoder{}, (*encoder.Encoder)(nil))
})
m.Group("/p", PresetRouter)
m.Group("/m", MockRouter)
m.Run()
}