Go Traffic Forwarding Implementation
In Golang, implementing traffic forwarding functionality is typically done using TCP or UDP features within the net package. Here is a simple example code that demonstrates a basic TCP traffic forwarding functionality:
package main
import (
"fmt"
"net"
"os"
)
func main() {
// 监听端口
ln, err := net.Listen("tcp", "localhost:8080")
if err != nil {
fmt.Println("Error listening:", err)
os.Exit(1)
}
defer ln.Close()
fmt.Println("Listening on localhost:8080")
// 接受客户端连接
for {
conn, err := ln.Accept()
if err != nil {
fmt.Println("Error accepting connection:", err)
os.Exit(1)
}
fmt.Println("Accepted connection from", conn.RemoteAddr())
// 将数据转发到目标地址
go func(conn net.Conn) {
targetAddr := "localhost:9090"
targetConn, err := net.Dial("tcp", targetAddr)
if err != nil {
fmt.Println("Error connecting to target:", err)
conn.Close()
return
}
defer targetConn.Close()
// 进行数据转发
go func() {
_, err := io.Copy(targetConn, conn)
if err != nil {
fmt.Println("Error copying data to target:", err)
}
}()
_, err = io.Copy(conn, targetConn)
if err != nil {
fmt.Println("Error copying data to client:", err)
}
conn.Close()
}(conn)
}
}
In the above code, we start by listening on port 8080 on localhost and accepting client connections. Whenever a new client connects, we create a new goroutine to handle the connection, forwarding the client’s data to the target address localhost:9090 and also sending the target address’s data back to the client. Finally, we close the connection.
Of course, this is just a simple example, in real-world applications, one may need to consider more error handling, as well as optimization and security considerations.