Local Port Forwarding as well as Network Tunnelling are useful tools for debugging, navigating infrastructure and much, much more. They’re frequently used by sysadmins and ops-engineers, but also provide some nice use-cases for developers.

In this post, we will take a look at how simple it is to do local port forwarding with just the Go standard library.

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
package main

import (
	"crypto/tls"
	"io"
	"log"
	"net"
	"time"
)

const (
	timeOutTime   = time.Second * 10
	keepAliveTime = time.Second * 60
)

var (
	lAddr = ":8082"
	tAddr = ":8083"
)

func main() {
	var cf, kf = "cert.pem", "key.pem"
	cert, err := tls.LoadX509KeyPair(cf, kf)
	if err != nil {
		log.Println(err)
		return
	}

	// run
	config := &tls.Config{
		Certificates: []tls.Certificate{cert},
	}
	log.Println(config.ServerName)
	ln, err := tls.Listen("tcp", lAddr, config)
	if err != nil {
		log.Printf("build listener failed:%s", err.Error())
		return
	}
	defer ln.Close()

	log.Println(ln.Addr())

	// run loop
	for {
		conn, err := ln.Accept()
		if err != nil {
			log.Printf("accept failed:%s", err.Error())
			if opErr, ok := err.(*net.OpError); ok {
				if !opErr.Temporary() {
					break
				}
			}
			continue
		}
		log.Println("new client:", conn.LocalAddr().(*net.TCPAddr), conn.RemoteAddr())
		go handleConn(conn)
	}
}

func forward(source net.Conn, dest net.Conn) {
	defer dest.Close()
	defer source.Close()
	_, _ = io.Copy(dest, source)
}

func handleConn(source net.Conn) {
	d := net.Dialer{
		Timeout:   timeOutTime,
		KeepAlive: keepAliveTime,
	}
	dest, err := d.Dial("tcp", tAddr)
	if err != nil {
		_ = source.Close()
		log.Printf("connect to %s failed: %s", tAddr, err.Error())
		return
	}

	go forward(source, dest.(*net.TCPConn))
	forward(dest.(*net.TCPConn), source)
}

There is a simple port-forwarding, what you want is a reverse proxy. In that case, there are some resources base on reverseproxy.go.