-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
107 lines (78 loc) · 2.26 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
package main
import (
"fmt"
"log"
"net/http"
"os"
"regexp"
"strings"
"time"
"github.com/brianvoe/gofakeit/v7"
"github.com/gorilla/mux"
)
type HttpResource struct {
FilePath string
Params []string
}
func mapWorkingDirectory(path string, resources map[string]HttpResource, parent string) {
entries, err := os.ReadDir(path)
if err != nil {
log.Fatal(err)
}
for _, e := range entries {
if e.Type().IsDir() {
mapWorkingDirectory(path+"/"+e.Name(), resources, strings.Join([]string{parent, e.Name()}, "/"))
return
}
var fileName = e.Name()
if !strings.HasSuffix(fileName, ".json") {
return
}
filePath := fileName
filePath = strings.Replace(filePath, ".json", "", len(filePath)-5)
var matches []string
var params []string
if strings.Contains(filePath, "[") && strings.Contains(filePath, "]") {
filePath = strings.ReplaceAll(filePath, "[", "{")
filePath = strings.ReplaceAll(filePath, "]", "}")
compile, _ := regexp.Compile(`(?i){([a-z0-9]+)}`)
matches = compile.FindAllString(filePath, -1)
for _, m := range matches {
matchedParam := m
matchedParam = strings.ReplaceAll(matchedParam, "{", "")
matchedParam = strings.ReplaceAll(matchedParam, "}", "")
params = append(params, matchedParam)
}
}
resources[strings.Join([]string{parent, filePath}, "/")] = HttpResource{
FilePath: path + "/" + fileName,
Params: params,
}
}
}
func (h *HttpResource) handleRequest(w http.ResponseWriter, req *http.Request) {
start := time.Now()
fileContent, err := os.ReadFile(h.FilePath)
if err != nil {
log.Fatal(err)
}
w.Header().Add("Content-Type", "application/json")
ctx := mux.Vars(req)
gofakeit.Seed(0)
content, err := gofakeit.Template(string(fileContent), &gofakeit.TemplateOptions{Data: ctx})
if err != nil {
log.Print(err)
}
fmt.Fprint(w, content)
fmt.Printf("%s ........................................... %d ms\n", req.URL.Path, time.Since(start).Milliseconds())
}
func HandlesRequests(address string, path string) {
r := mux.NewRouter()
resources := make(map[string]HttpResource)
mapWorkingDirectory(path, resources, "")
for k, v := range resources {
r.HandleFunc(k, v.handleRequest)
}
fmt.Printf("Listening to requests at %s\n", address)
log.Fatal(http.ListenAndServe(address, r))
}