-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
95 lines (78 loc) · 1.96 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
package main
import (
"bufio"
"fmt"
"io"
"strings"
"encoding/json"
"html/template"
"net/http"
"net/http/httptest"
"github.com/teler-sh/teler-waf"
"github.com/teler-sh/teler-waf/option"
)
func indexHandler(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseFiles("www/index.html")
if err != nil {
handleError(w, http.StatusInternalServerError, err.Error())
return
}
err = tmpl.Execute(w, meta)
if err != nil {
handleError(w, http.StatusInternalServerError, err.Error())
return
}
}
func playHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method != http.MethodPost {
handleError(w, http.StatusMethodNotAllowed, errOnlyPOSTMethod)
return
}
if r.ContentLength == 0 {
handleError(w, http.StatusBadRequest, errNoBody)
return
}
body, err := io.ReadAll(r.Body)
if err != nil {
handleError(w, http.StatusBadRequest, fmt.Sprintf(errReadReqBody, err.Error()))
return
}
data := new(data)
if err := json.Unmarshal(body, &data); err != nil {
handleError(w, http.StatusBadRequest, fmt.Sprintf(errParseJSON, err.Error()))
return
}
if data.Request == "" {
handleError(w, http.StatusBadRequest, errEmptyReq)
return
}
req, err := http.ReadRequest(bufio.NewReader(strings.NewReader(data.Request)))
if err != nil {
handleError(w, http.StatusBadRequest, fmt.Sprintf(errReadReq, err.Error()))
return
}
res := httptest.NewRecorder()
opt, err := option.LoadFromYAMLString(data.Config)
if err != nil {
handleError(w, http.StatusBadRequest, fmt.Sprintf(errLoadConfig, err.Error()))
return
}
opt = setDefaultOpts(opt)
out := map[string]any{
"ok": false,
"message": nil,
"error": nil,
}
waf := teler.New(opt)
err = waf.Analyze(res, req)
if err != nil {
w.WriteHeader(http.StatusForbidden)
out["message"] = err.Error()
_ = json.NewEncoder(w).Encode(out)
return
}
w.WriteHeader(http.StatusOK)
out["ok"] = true
_ = json.NewEncoder(w).Encode(out)
}