-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
80 lines (66 loc) · 2.01 KB
/
handler.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
package router
import (
"html/template"
"io/ioutil"
"net/http"
"github.com/gorilla/mux"
"github.com/leekchan/gtf"
"github.com/ncatelli/mockserver/pkg/router/generator"
)
type templateVariables struct {
Request *http.Request
PathVars map[string]string
}
// Generate plugins
//go:generate go run ./generator/gen.go
// Handler includes all the metadata to decide on and serve a response.
type Handler struct {
Weight int `yaml:"weight"`
ResponseHeaders map[string]string `yaml:"response_headers"`
StaticResponse string `yaml:"static_response"`
ResponseStatus int `yaml:"response_status"`
ResponsePath string `yaml:"response_path"`
bodyTemplate *template.Template
}
// getBodyTemplate will attempt to retrieve, preferably from a cache field, the
// template used to generate the response body of a Handler.
func (handler *Handler) getBodyTemplate() (*template.Template, error) {
// short circut if the template is cached
if handler.bodyTemplate != nil {
return handler.bodyTemplate, nil
}
// placeholder for future template data.
var body string
// static response is highest precedence
if len(handler.StaticResponse) > 0 {
body = handler.StaticResponse
} else if len(handler.ResponsePath) > 0 {
bb, err := ioutil.ReadFile(handler.ResponsePath)
if err != nil {
return nil, err
}
body = string(bb)
}
t, err := template.New("").Funcs(gtf.GtfFuncMap).Funcs(generator.PluginsFuncMap()).Parse(body)
if err != nil {
return nil, err
}
handler.bodyTemplate = t
return t, nil
}
// ServeHTTP implements the http.Handler interface eventually serving a request.
func (handler *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
t, err := handler.getBodyTemplate()
if err != nil {
http.Error(w, "", http.StatusInternalServerError)
return
}
for h, v := range handler.ResponseHeaders {
w.Header().Set(h, v)
}
w.WriteHeader(handler.ResponseStatus)
t.Execute(w, &templateVariables{
Request: r,
PathVars: mux.Vars(r),
})
}