forked from teler-sh/teler-waf
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhandler.go
79 lines (67 loc) · 2.41 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
// Copyright Dwi Siswanto and/or licensed to Dwi Siswanto under one
// or more contributor license agreements. Licensed under the Elastic License 2.0;
// you may not use this file except in compliance with the Elastic License 2.0.
// See the LICENSE-ELASTIC file in the project root for more information.
package teler
import (
"github.com/3JoB/unsafeConvert"
"github.com/savsgio/atreugo/v11"
"github.com/valyala/fasttemplate"
)
// rejectHandler is default rejection handler
func rejectHandler(c *atreugo.RequestCtx) error {
// Set Content-Type to text/html
c.Response.Header.Set("Content-Type", "text/html")
// Set the status code
c.SetStatusCode(respStatus)
// Set template interfaces
data := map[string]any{
// NOTE(dwisiswant0): Should we include *http.Request?
"ID": unsafeConvert.StringSlice(c.Response.Header.Peek(xTelerReqId)),
"message": unsafeConvert.StringSlice(c.Response.Header.Peek(xTelerMsg)),
"threat": unsafeConvert.StringSlice(c.Response.Header.Peek(xTelerThreat)),
}
// Use custom response HTML page template if non-empty
if customHTMLResponse != "" {
respTemplate = customHTMLResponse
}
// Parse response template
tpl := fasttemplate.New(respTemplate, "{{", "}}")
// Write a response from the template
// TODO(dwisiswant0): Add error handling here.
_, _ = tpl.Execute(c.Response.BodyWriter(), data)
return nil
}
// SetHandler sets the handler to call when the teler rejects a request.
func (t *Teler) SetHandler(handler atreugo.View) {
t.handler = handler
}
// Handler implements the http.HandlerFunc for integration with the standard net/http library.
func (t *Teler) Handler(next atreugo.View) atreugo.View {
return func(c *atreugo.RequestCtx) error {
// Let teler analyze the request. If it returns an error,
// that indicates the request should not continue.
k, err := t.analyzeRequest(c)
if err != nil {
// Process the analyzeRequest
t.postAnalyze(c, k, err)
return nil
}
return next(c)
}
}
// HandlerFuncWithNext is a special implementation for Negroni, but could be used elsewhere.
func (t *Teler) HandlerFuncWithNext(c *atreugo.RequestCtx, next atreugo.View) {
// Let teler analyze the request. If it returns an error,
// that indicates the request should not continue.
k, err := t.analyzeRequest(c)
if err != nil {
// Process the analyzeRequest
t.postAnalyze(c, k, err)
return
}
// If next handler is not nil, call it.
if next != nil {
next(c)
}
}