-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathresponse_interceptor.go
56 lines (47 loc) · 1.24 KB
/
response_interceptor.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
package coraza
import (
"fmt"
"net/http"
"github.com/jptosso/coraza-waf/v2"
)
type HTTPResponseInterceptor struct {
http.ResponseWriter
StatusCode int
tx *coraza.Transaction
}
func NewHTTPResponseInterceptor(w http.ResponseWriter, tx *coraza.Transaction) *HTTPResponseInterceptor {
return &HTTPResponseInterceptor{w, http.StatusOK, tx}
}
func (i *HTTPResponseInterceptor) WriteHeader(code int) {
if i.tx.Interruption.Action == "deny" {
i.StatusCode = i.tx.Interruption.Status
i.ResponseWriter.WriteHeader(i.tx.Interruption.Status)
} else {
i.StatusCode = code
i.ResponseWriter.WriteHeader(code)
}
}
func (i *HTTPResponseInterceptor) Write(data []byte) (int, error) {
c, err := i.tx.ResponseBodyBuffer.Write(data)
if err != nil {
return c, err
}
if i.tx.Interrupted() {
return 0, fmt.Errorf("transaction interrupted")
}
return i.ResponseWriter.Write(data)
}
func (i *HTTPResponseInterceptor) Header() http.Header {
for k, vs := range i.ResponseWriter.Header() {
for _, v := range vs {
i.tx.AddResponseHeader(k, v)
}
}
if it := i.tx.ProcessResponseHeaders(i.StatusCode, "http/1.1"); it != nil {
h := http.Header{}
h.Add("Content-Type", "text/html")
return h
} else {
return i.ResponseWriter.Header()
}
}