原文:https://socketloop.com/tutorials/golang-forwarding-a-local-port-to-a-remote-server-examplegolang
端口转发, 本地的端口转发到远端服务器的80端口。web
------------------------------------------------------------------------------------------------------------------------------------------------服务器
Got a strange request yesterday. A friend who is an IT manager in his company needs to implement some control over his local network. He needs to block all the staffs(his co-workers) access to Facebook during working hours, but at the same time open up a "secret" door access to Facebook for his boss.socket
It is pretty trivial to configure the local network firewall to block access to certain websites nowadays. However, he prefers not to configure the "secret" door in the local network firewall. The next best solution is to implement a local port forwarding to remote server.tcp
Below is a simple port forwarding solution in Golang that will initiate a bi-directional communication with a remote server(Facebook for example).oop
Here you go!.net
package main import ( "io" "log" "net" ) var localServerHost = "localhost:8880" var remoteServerHost = "www.facebook.com:80" func main() { ln, err := net.Listen("tcp", localServerHost) if err != nil { log.Fatal(err) } log.Println("Port forwarding server up and listening on ", localServerHost) for { conn, err := ln.Accept() if err != nil { log.Fatal(err) } go handleConnection(conn) } } func forward(src, dest net.Conn) { defer src.Close() defer dest.Close() io.Copy(src, dest) } func handleConnection(c net.Conn) { log.Println("Connection from : ", c.RemoteAddr()) remote, err := net.Dial("tcp", remoteServerHost) if err != nil { log.Fatal(err) } log.Println("Connected to ", remoteServerHost) // go routines to initiate bi-directional communication for local server with a // remote server go forward(c, remote) go forward(remote, c) }
Sample output:code
1) Run the program at the background andserver
2) On the browser, enter localhost:8880
in the address bar.blog
References:
https://www.socketloop.com/tutorials/golang-simple-client-server-example