-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathhandlers.go
64 lines (55 loc) · 1.27 KB
/
handlers.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
package main
import (
"net/http"
"path/filepath"
"text/template"
"time"
"github.com/gorilla/mux"
log "github.com/sirupsen/logrus"
"github.com/spf13/afero"
)
func newHandleFunc(fs afero.Fs, path string, r Response) func(writer http.ResponseWriter, request *http.Request) {
return func(writer http.ResponseWriter, request *http.Request) {
if r.Status != 200 {
writer.WriteHeader(r.Status)
}
if r.Latency != "" {
duration, err := time.ParseDuration(r.Latency)
if err != nil {
log.Error(err)
}
time.Sleep(duration)
}
if r.JsonBody != "" {
tmpl, err := parseFile(fs, path, r.JsonBody)
if err != nil {
log.Error(err)
writer.WriteHeader(500)
_, _ = writer.Write([]byte(err.Error()))
return
}
writer.Header().Add("Content-Type", "application/json")
err = tmpl.Execute(writer, mux.Vars(request))
if err != nil {
log.Error(err)
}
}
}
}
func parseFile(fs afero.Fs, path string, filename string) (*template.Template, error) {
if path != "" {
filename = filepath.Join(path, filename)
}
b, err := afero.ReadFile(fs, filename)
if err != nil {
return nil, err
}
s := string(b)
name := filepath.Base(filename)
tmpl := template.New(name)
_, err = tmpl.Parse(s)
if err != nil {
return nil, err
}
return tmpl, nil
}