-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathinterceptor.go
More file actions
85 lines (70 loc) · 2.33 KB
/
interceptor.go
File metadata and controls
85 lines (70 loc) · 2.33 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
package mitmproxy
import (
"context"
"net/http"
"github.com/josexy/mitmproxy-go/buf"
)
// WSDirection indicates the direction of a WebSocket message
type WSDirection byte
const (
// Send indicates a message sent from client to server
Send WSDirection = iota
// Receive indicates a message received from server to client
Receive
)
func (d WSDirection) String() string {
switch d {
case Send:
return "Send"
case Receive:
return "Receive"
default:
return "Unknown"
}
}
type WsFrame interface {
Direction() WSDirection
MessageType() int
DataBuffer() *buf.Buffer
// Forward the websocket message and release the data buffer
Invoke() error
// MUST be called to release the data buffer
Release()
}
type (
HTTPDelegatedInvoker interface {
Invoke(request *http.Request) (*http.Response, error)
}
WebsocketDelegatedInvoker interface {
Invoke(msgType int, dataPtr *buf.Buffer) error
}
WebsocketFramesWatcher interface {
Receive() <-chan WsFrame
}
)
type (
HTTPDelegatedInvokerFunc func(*http.Request) (*http.Response, error)
WebsocketDelegatedInvokerFunc func(int, *buf.Buffer) error
HTTPInterceptor func(context.Context, *http.Request, HTTPDelegatedInvoker) (*http.Response, error)
WebsocketInterceptor func(context.Context, *http.Request, *http.Response, WebsocketFramesWatcher)
)
func (f HTTPDelegatedInvokerFunc) Invoke(r *http.Request) (*http.Response, error) { return f(r) }
func (f WebsocketDelegatedInvokerFunc) Invoke(t int, data *buf.Buffer) error { return f(t, data) }
func wrapperInvoker(fn func(messageType int, data []byte) error) WebsocketDelegatedInvokerFunc {
return func(i int, b *buf.Buffer) error {
return fn(i, b.Bytes())
}
}
func chainHTTPInterceptors(interceptors []HTTPInterceptor) HTTPInterceptor {
return func(ctx context.Context, req *http.Request, hi HTTPDelegatedInvoker) (*http.Response, error) {
return interceptors[0](ctx, req, getChainHTTPInterceptor(interceptors, 0, ctx, hi))
}
}
func getChainHTTPInterceptor(interceptors []HTTPInterceptor, curr int, ctx context.Context, finalInvoker HTTPDelegatedInvoker) HTTPDelegatedInvoker {
if curr == len(interceptors)-1 {
return finalInvoker
}
return HTTPDelegatedInvokerFunc(func(r *http.Request) (*http.Response, error) {
return interceptors[curr+1](ctx, r, getChainHTTPInterceptor(interceptors, curr+1, ctx, finalInvoker))
})
}