How can we implement data forwarding function in the Go…

To achieve data forwarding functionality, you can utilize Go language’s goroutine and channel mechanism.

Firstly, create a function that receives data and sends it to the target address. This function can utilize relevant functions in the net package for network communication.

func forwardData(source net.Conn, destination net.Conn) {
    defer source.Close()
    defer destination.Close()

    // 创建一个缓冲区,用于存储从源地址读取到的数据
    buffer := make([]byte, 4096)

    for {
        // 从源地址读取数据
        bytesRead, err := source.Read(buffer)
        if err != nil {
            log.Println("Error reading data from source:", err)
            return
        }

        // 将读取到的数据发送到目标地址
        _, err = destination.Write(buffer[:bytesRead])
        if err != nil {
            log.Println("Error forwarding data:", err)
            return
        }
    }
}

Next, a listener is created in the main function to accept connection requests. Each time a new connection is established, a goroutine is launched to handle the data forwarding.

func main() {
    // 创建一个监听器
    listener, err := net.Listen("tcp", "localhost:8000")
    if err != nil {
        log.Fatal("Error creating listener:", err)
    }
    defer listener.Close()

    for {
        // 接受连接请求
        source, err := listener.Accept()
        if err != nil {
            log.Println("Error accepting connection:", err)
            continue
        }

        // 连接到目标地址
        destination, err := net.Dial("tcp", "example.com:80")
        if err != nil {
            log.Println("Error connecting to destination:", err)
            source.Close()
            continue
        }

        // 启动一个goroutine来处理数据转发
        go forwardData(source, destination)
    }
}

In this way, whenever a new connection is established, a new goroutine will be launched to handle data forwarding, enabling the functionality of data forwarding.

bannerAds