forked from simagix/hatchet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_handler.go
79 lines (75 loc) · 2.33 KB
/
api_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
// Copyright 2022-present Kuei-chun Chen. All rights reserved.
package hatchet
import (
"encoding/json"
"fmt"
"net/http"
"strings"
)
// apiHandler responds to API calls
func apiHandler(w http.ResponseWriter, r *http.Request) {
/** APIs
* /api/hatchet/v1.0/tables/{table}/logs
* /api/hatchet/v1.0/tables/{table}/logs/slowops
* /api/hatchet/v1.0/tables/{table}/stats/slowops
*/
apiPrefix := "/api/hatchet/v1.0/tables/"
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
tokens := strings.Split(r.URL.Path[len(apiPrefix):], "/")
if len(tokens) == 3 {
tableName := tokens[0]
category := tokens[1]
attr := tokens[2]
if attr == "slowops" && category == "stats" {
orderBy := r.URL.Query().Get("orderBy")
b, err := getSlowOpsStats(tableName, orderBy)
if err != nil {
json.NewEncoder(w).Encode(map[string]interface{}{"ok": 0, "error": err.Error()})
} else {
w.Write(b)
}
return
} else if attr == "slowops" && category == "logs" {
topN := ToInt(r.URL.Query().Get("topN"))
b, err := getSlowLogs(tableName, topN)
if err != nil {
json.NewEncoder(w).Encode(map[string]interface{}{"ok": 0, "error": err.Error()})
} else {
w.Write(b)
}
return
}
json.NewEncoder(w).Encode(map[string]interface{}{"table": tableName, "data_type": attr})
} else if len(tokens) == 2 && tokens[1] == "logs" {
tableName := tokens[0]
component := r.URL.Query().Get("component")
context := r.URL.Query().Get("context")
severity := r.URL.Query().Get("severity")
duration := r.URL.Query().Get("duration")
logs, err := getLogs(tableName, fmt.Sprintf("component=%v", component),
fmt.Sprintf("context=%v", context), fmt.Sprintf("severity=%v", severity), fmt.Sprintf("duration=%v", duration))
if err != nil {
json.NewEncoder(w).Encode(map[string]interface{}{"ok": 0, "error": err.Error()})
return
}
var b []byte
if b, err = json.Marshal(logs); err != nil {
json.NewEncoder(w).Encode(map[string]interface{}{"ok": 0, "error": err.Error()})
return
}
w.Write(b)
return
}
json.NewEncoder(w).Encode(map[string]interface{}{"ok": 1, "message": "Hello Hatchet API!"})
}
func getSlowLogs(tableName string, topN int) ([]byte, error) {
if topN == 0 {
topN = 25
}
logstrs, err := getSlowestLogs(tableName, topN)
if err != nil {
return nil, err
}
return json.Marshal(logstrs)
}