-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy.go
76 lines (68 loc) · 1.09 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
package toxy
import (
"errors"
"fmt"
"io"
"log"
"net"
)
type Proxy struct {
service *ResolverService
conn net.Conn
OutBuf chan []byte
}
func NewProxy(service *ResolverService) *Proxy {
proxy := &Proxy{
service: service,
OutBuf: make(chan []byte),
}
return proxy
}
func (p *Proxy) connect() {
var err error
p.conn, err = net.Dial("tcp", fmt.Sprintf("%s:%d", p.service.Hostname, p.service.Port))
if err != nil {
p.OutBuf <- nil
return
}
}
func (p *Proxy) write(buf []byte) {
if p.conn == nil {
return
}
n, err := p.conn.Write(buf)
if err != nil {
log.Println(n, err)
p.conn.Close()
return
}
}
func (p *Proxy) read() {
buf := make([]byte, 4096)
for {
if p.conn == nil {
p.OutBuf <- nil
log.Printf("Proxy connection is nil")
return
}
n, err := p.conn.Read(buf)
r := make([]byte, n)
copy(r, buf[:n])
p.OutBuf <- r
if err != nil {
if errors.Is(err, io.EOF) {
p.OutBuf <- nil
p.conn.Close()
return
}
log.Printf("%v", err)
p.conn.Close()
return
}
}
}
func (p *Proxy) Close() {
if p.conn != nil {
p.conn.Close()
}
}