-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathhandler.go
More file actions
317 lines (281 loc) · 7.88 KB
/
handler.go
File metadata and controls
317 lines (281 loc) · 7.88 KB
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
package api
import (
"bytes"
"encoding/json"
"fmt"
"io/fs"
"mokapi/config/static"
"mokapi/runtime"
"mokapi/runtime/metrics"
"mokapi/webui"
"net/http"
"net/url"
"path/filepath"
"slices"
"strconv"
"strings"
log "github.com/sirupsen/logrus"
)
type Handler interface {
http.Handler
RegisterHealthHandler(path string, h http.Handler)
RegisterMcpHandler(path string, h http.Handler)
}
type handler struct {
config static.Api
path string
base string
app *runtime.App
fileServer http.Handler
index string
healthPath string
healthHandler http.Handler
mcpPath string
mcpHandler http.Handler
}
type info struct {
Version string `json:"version"`
BuildTime string `json:"buildTime"`
ActiveServices []string `json:"activeServices,omitempty"`
Search searchInfo `json:"search"`
}
type searchInfo struct {
Enabled bool `json:"enabled"`
}
type serviceType string
var (
ServiceHttp serviceType = "http"
ServiceKafka serviceType = "kafka"
ServiceMail serviceType = "mail"
ServiceLdap serviceType = "ldap"
)
type service struct {
Name string `json:"name"`
Description string `json:"description,omitempty"`
Contact *contact `json:"contact,omitempty"`
Version string `json:"version,omitempty"`
Type serviceType `json:"type"`
Metrics []metrics.Metric `json:"metrics,omitempty"`
}
type contact struct {
Name string `json:"name"`
Url string `json:"url"`
Email string `json:"email"`
}
type apiError struct {
Message string `json:"message"`
}
func New(app *runtime.App, config static.Api) Handler {
h := &handler{
config: config,
path: config.Path,
base: config.Base,
app: app,
}
if config.Dashboard {
webapp := webui.App
b, err := webapp.ReadFile("dist/index.html")
if err != nil {
panic(err)
}
h.index = string(b)
dist, err := fs.Sub(webapp, "dist")
if err != nil {
panic(err)
}
h.fileServer = http.FileServer(http.FS(dist))
}
return h
}
func BuildUrl(cfg static.Api) (*url.URL, error) {
s := fmt.Sprintf("http://:%v%v", cfg.Port, cfg.Path)
return url.Parse(s)
}
func (h *handler) RegisterHealthHandler(path string, handler http.Handler) {
h.healthPath = path
h.healthHandler = handler
}
func (h *handler) RegisterMcpHandler(path string, handler http.Handler) {
h.mcpPath = path
h.mcpHandler = handler
}
func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" && r.Method != "POST" {
http.Error(w, fmt.Sprintf("method %v is not allowed", r.Method), http.StatusMethodNotAllowed)
return
}
w.Header().Set("Access-Control-Allow-Origin", "*")
switch p := r.URL.Path; {
case len(h.path) > 0 && strings.HasPrefix(p, h.path):
r.URL.Path = r.URL.Path[len(h.path):]
h.ServeHTTP(w, r)
case p == "/api/info":
h.getInfo(w, r)
case p == "/api/services":
h.getServices(w, r)
case strings.HasPrefix(p, "/api/services/http/"):
h.getHttpService(w, r, h.app.Monitor)
case strings.HasPrefix(p, "/api/services/kafka"):
h.handleKafka(w, r)
case strings.HasPrefix(p, "/api/services/mail/"):
h.handleMailService(w, r)
case strings.HasPrefix(p, "/api/services/ldap/"):
h.handleLdapService(w, r)
case p == "/api/dashboard":
h.getDashboard(w, r)
case strings.HasPrefix(p, "/api/metrics"):
h.getMetrics(w, r)
case strings.HasPrefix(p, "/api/events"):
h.getEvents(w, r)
case p == "/api/schema/example":
h.getExampleData(w, r)
case p == "/api/schema/validate":
h.validate(w, r)
case strings.HasPrefix(p, "/api/system/"):
h.serveSystem(w, r)
case strings.HasPrefix(p, "/api/configs"):
h.handleConfig(w, r)
case strings.HasPrefix(p, "/api/faker/tree"):
h.handleFakerTree(w, r)
case strings.HasPrefix(p, "/api/search"):
h.getSearchResults(w, r)
case strings.HasPrefix(p, h.healthPath) && h.healthHandler != nil:
h.healthHandler.ServeHTTP(w, r)
case strings.HasPrefix(p, h.mcpPath) && h.mcpHandler != nil:
h.mcpHandler.ServeHTTP(w, r)
case h.fileServer != nil:
if r.Method != "GET" {
http.Error(w, fmt.Sprintf("method %v is not allowed", r.Method), http.StatusMethodNotAllowed)
return
}
if isAsset(r.URL.Path) {
r.URL.Path = "/assets/" + filepath.Base(r.URL.Path)
} else if isImage(r.URL.Path) {
// don't change url
} else {
if len(h.path) > 0 || len(h.base) > 0 {
base := h.path
if len(h.base) > 0 {
base = h.base
}
html := strings.Replace(h.index, "<base href=\"/\" />", fmt.Sprintf("<base href=\"%v/\" />", base), 1)
html = h.replaceMeta(r.URL, html)
_, err := w.Write([]byte(html))
if err != nil {
log.Errorf("unable to write index.html: %v", err)
}
return
} else {
r.URL.Path = "/"
}
}
h.fileServer.ServeHTTP(w, r)
default:
log.Errorf("dashboard file not found: %v", r.URL)
http.Error(w, "not found", http.StatusNotFound)
}
}
func (h *handler) getServices(w http.ResponseWriter, _ *http.Request) {
services := make([]interface{}, 0)
services = append(services, getHttpServices(h.app.ListHttp(), h.app.Monitor)...)
services = append(services, getKafkaServices(h.app.Kafka, h.app.Monitor)...)
services = append(services, getMailServices(h.app.Mail, h.app.Monitor)...)
services = append(services, getLdapServices(h.app.Ldap, h.app.Monitor)...)
slices.SortFunc(services, func(a interface{}, b interface{}) int {
return compareService(a, b)
})
w.Header().Set("Content-Type", "application/json")
writeJsonBody(w, services)
}
func writeError(w http.ResponseWriter, err error, status int) {
log.Error(err)
data, err := json.Marshal(apiError{Message: err.Error()})
if err != nil {
http.Error(w, err.Error(), status)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_, err = w.Write(data)
if err != nil {
log.Errorf("write response body failed: %v", err)
}
}
func (h *handler) getInfo(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
i := info{Version: h.app.Version, BuildTime: h.app.BuildTime, Search: searchInfo{Enabled: h.config.Search.Enabled}}
if len(h.app.ListHttp()) > 0 {
i.ActiveServices = append(i.ActiveServices, "http")
}
if len(h.app.Kafka.List()) > 0 {
i.ActiveServices = append(i.ActiveServices, "kafka")
}
if len(h.app.Mail.List()) > 0 {
i.ActiveServices = append(i.ActiveServices, "mail")
}
if len(h.app.Ldap.List()) > 0 {
i.ActiveServices = append(i.ActiveServices, "ldap")
}
writeJsonBody(w, i)
}
func writeJsonBody(w http.ResponseWriter, v interface{}) {
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
err := enc.Encode(v) // includes newline
if err != nil {
writeError(w, err, http.StatusInternalServerError)
return
}
b := bytes.TrimSuffix(buf.Bytes(), []byte("\n"))
_, err = w.Write(b)
if err != nil {
log.Errorf("write response body failed: %v", err)
}
}
func isAsset(path string) bool {
return strings.Contains(path, "/assets/")
}
func isImage(path string) bool {
str := filepath.Ext(path)
switch str {
case ".jpg", ".jpeg", ".png", ".svg":
return true
default:
return false
}
}
func compareService(a, b interface{}) int {
return strings.Compare(getServiceName(a), getServiceName(b))
}
func getServiceName(a interface{}) string {
switch v := a.(type) {
case *httpSummary:
return v.Name
case *kafkaSummary:
return v.Name
case *ldapSummary:
return v.Name
case *mailSummary:
return v.Name
}
return ""
}
func getPageInfo(r *http.Request) (index int, limit int, err error) {
limit = 10
sIndex := getQueryParamInsensitive(r.URL.Query(), searchIndex)
if sIndex != "" {
index, err = strconv.Atoi(sIndex)
if err != nil {
err = fmt.Errorf("invalid query parameter 'index': must be a number")
}
}
sLimit := getQueryParamInsensitive(r.URL.Query(), searchLimit)
if sLimit != "" {
limit, err = strconv.Atoi(sLimit)
if err != nil {
err = fmt.Errorf("invalid query parameter 'limit': must be a number")
}
}
return
}