-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproxy.go
66 lines (59 loc) · 1.3 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
package socks
import (
"context"
"io"
"net"
"time"
)
// ProxyHandler is the interface for handling the proxy requests
type ProxyHandler interface {
Init(context.Context, Request) (context.Context, io.ReadWriteCloser, *Error)
ReadFromClient(context.Context, io.ReadCloser, io.WriteCloser) error
ReadFromRemote(context.Context, io.ReadCloser, io.WriteCloser) error
Close(context.Context) error
Refresh(context.Context)
}
// Proxy is the main struct
type Proxy struct {
ServerAddr string
Done chan struct{}
Proxyhandler ProxyHandler
Timeout time.Duration
Log Logger
}
// Start is the main function to start a proxy
func (p *Proxy) Start(ctx context.Context) error {
if p.Log == nil {
p.Log = &NilLogger{} // allow not to set logger
}
listener, err := net.Listen("tcp", p.ServerAddr)
if err != nil {
return err
}
go p.run(ctx, listener)
return nil
}
func (p *Proxy) run(ctx context.Context, listener net.Listener) {
for {
select {
case <-p.Done:
return
default:
connection, err := listener.Accept()
if err == nil {
go p.handle(ctx, connection)
} else {
p.Log.Errorf("Error accepting conn: %v", err)
}
}
}
}
// Stop stops the proxy
func (p *Proxy) Stop() {
p.Log.Warn("Stopping proxy")
if p.Done == nil {
return
}
close(p.Done)
p.Done = nil
}