-
Notifications
You must be signed in to change notification settings - Fork 34
/
localtunnel.go
72 lines (61 loc) · 1.3 KB
/
localtunnel.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
package localtunnel
import (
"fmt"
"io"
"net"
)
// LocalTunnel forwards remote requests to a port on localhost
type LocalTunnel struct {
listener *Listener
localAddr string
}
// New returns a LocalTunnel forwarding requests to port on host
//
// host defaults to 'localhost', and options defaults to using localtunnel.me
func New(port int, host string, options Options) (*LocalTunnel, error) {
if host == "" {
host = "localhost"
}
l, err := Listen(options)
if err != nil {
return nil, err
}
lt := &LocalTunnel{
listener: l,
localAddr: fmt.Sprintf("%s:%d", host, port),
}
go lt.listen()
return lt, nil
}
// URL returns the URL at which the localtunnel is exposed
func (lt *LocalTunnel) URL() string {
return lt.listener.URL()
}
func (lt *LocalTunnel) listen() {
for {
remoteConn, err := lt.listener.Accept()
if err != nil {
break
}
go lt.forward(remoteConn)
}
}
func (lt *LocalTunnel) forward(remoteConn net.Conn) {
localConn, err := net.Dial("tcp", lt.localAddr)
if err != nil {
remoteConn.Close()
return
}
go func() {
io.Copy(remoteConn, localConn)
remoteConn.Close()
}()
go func() {
io.Copy(localConn, remoteConn)
localConn.Close()
}()
}
// Close the localtunnel aborting all connections
func (lt *LocalTunnel) Close() error {
return lt.listener.Close()
}