/
proxy.go
123 lines (99 loc) · 2.42 KB
/
proxy.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
package quickproxy
import (
"github.com/elazarl/goproxy"
"log"
. "net/http"
"time"
)
const (
DEFAULT_PORT = "8888"
LISTEN = "127.0.0.1"
VERBOSE = false
)
type (
requestCallback func(request *Request)
responseCallback func(response *Response)
doneCallback func(doneReuqestData *DoneRequestData)
)
type (
requestCallbacks []requestCallback
responseCallbacks []responseCallback
doneCallbacks []doneCallback
)
type RoundTrip struct {
RequestTime time.Time
ResponseTime time.Time
}
type DoneRequestData struct {
Request *Request
Response *Response
RoundTripTime *RoundTrip
}
var (
port string = DEFAULT_PORT
listen string = LISTEN
verbose bool = VERBOSE
sessions = map[int64]*RoundTrip{}
onRequestCallbacks = requestCallbacks{}
onResponseCallbacks = responseCallbacks{}
onDoneCallbacks = doneCallbacks{}
)
func NewRoundTrip(requestTime time.Time) *RoundTrip {
roundTrip := new(RoundTrip)
roundTrip.RequestTime = requestTime
return roundTrip
}
func (r *RoundTrip) ElapsedTime() time.Duration {
return r.ResponseTime.Sub(r.RequestTime)
}
func Prepare(options map[string]string) {
if options["port"] != "" {
port = options["port"]
}
if options["listen"] != "" {
listen = options["listen"]
}
if options["verbose"] != "" {
if options["verbose"] == "true" {
verbose = true
} else {
verbose = false
}
}
}
func OnRequest(f requestCallback) {
onRequestCallbacks = append(onRequestCallbacks, f)
}
func OnResponse(f responseCallback) {
onResponseCallbacks = append(onResponseCallbacks, f)
}
func OnDone(f doneCallback) {
onDoneCallbacks = append(onDoneCallbacks, f)
}
func Run() {
proxy := goproxy.NewProxyHttpServer()
proxy.Verbose = true
proxy.OnRequest().DoFunc(
func(r *Request, ctx *goproxy.ProxyCtx) (*Request, *Response) {
sessions[ctx.Session] = NewRoundTrip(time.Now())
for _, f := range onRequestCallbacks {
f(ctx.Req)
}
return r, nil
})
proxy.OnResponse().DoFunc(
func(r *Response, ctx *goproxy.ProxyCtx) *Response {
for _, f := range onResponseCallbacks {
f(ctx.Resp)
}
if ctx.Resp != nil {
roundTrip := sessions[ctx.Session]
roundTrip.ResponseTime = time.Now()
for _, f := range onDoneCallbacks {
f(&DoneRequestData{ctx.Req, ctx.Resp, roundTrip})
}
}
return r
})
log.Fatal(ListenAndServe(listen+":"+port, proxy))
}