@@ -63,20 +63,20 @@ type Option func(*Proxy)
63
63
// SwitchConn wraps a net.Conn and a bufio.Reader
64
64
type SwitchConn struct {
65
65
net.Conn
66
- reader * bufio.Reader
66
+ * bufio.Reader
67
67
}
68
68
69
69
// NewSwitchConn creates a new SwitchConn
70
70
func NewSwitchConn (conn net.Conn ) * SwitchConn {
71
71
return & SwitchConn {
72
72
Conn : conn ,
73
- reader : bufio .NewReader (conn ),
73
+ Reader : bufio .NewReader (conn ),
74
74
}
75
75
}
76
76
77
77
// Read reads data into p, first from the bufio.Reader, then from the net.Conn
78
78
func (c * SwitchConn ) Read (p []byte ) (n int , err error ) {
79
- return c .reader .Read (p )
79
+ return c .Reader .Read (p )
80
80
}
81
81
82
82
func (p * Proxy ) ListenAndServe () error {
@@ -116,6 +116,7 @@ func (p *Proxy) ListenAndServe() error {
116
116
// Start a new goroutine to handle each connection
117
117
// This way, the server can handle multiple connections concurrently
118
118
go func () {
119
+ defer conn .Close ()
119
120
err := p .handleConnection (conn )
120
121
if err != nil {
121
122
p .logger .Error (err .Error ()) // Log errors from ServeConn
@@ -129,23 +130,16 @@ func (p *Proxy) handleConnection(conn net.Conn) error {
129
130
// Create a SwitchConn
130
131
switchConn := NewSwitchConn (conn )
131
132
132
- // Read one byte to determine the protocol
133
- buf := make ([]byte , 1 )
134
- _ , err := switchConn .Read (buf )
133
+ // Peek one byte to determine the protocol
134
+ buf , err := switchConn .Peek (1 )
135
135
if err != nil {
136
136
return err
137
137
}
138
138
139
- // Unread the byte so it's available for the next read
140
- err = switchConn .reader .UnreadByte ()
141
- if err != nil {
142
- return err
143
- }
144
-
145
- switch {
146
- case buf [0 ] == 5 :
139
+ switch buf [0 ] {
140
+ case 5 :
147
141
err = p .socks5Proxy .ServeConn (switchConn )
148
- case buf [ 0 ] == 4 :
142
+ case 4 :
149
143
err = p .socks4Proxy .ServeConn (switchConn )
150
144
default :
151
145
err = p .httpProxy .ServeConn (switchConn )
0 commit comments