Skip to content

Instantly share code, notes, and snippets.

@legendtkl legendtkl/proxy.go
Created Aug 18, 2016

Embed
What would you like to do?
simple golang tcp proxy (forward request)
package main
import (
"fmt"
"net"
"io"
)
func main() {
//http.HandleFunc("/", handler)
//http.ListenAndServe(":8081", nil)
listener, err := net.Listen("tcp", ":8001")
if err != nil {
panic("connection error:" + err.Error())
}
for {
conn, err := listener.Accept()
if err != nil {
fmt.Println("Accept Error:", err)
continue
}
copyConn(conn)
}
}
func copyConn(src net.Conn) {
dst, err := net.Dial("tcp", ":8002")
if err != nil {
panic("Dial Error:" + err.Error())
}
done := make(chan struct{})
go func() {
defer src.Close()
defer dst.Close()
io.Copy(dst, src)
done<-struct{}{}
}()
go func() {
defer src.Close()
defer dst.Close()
io.Copy(src, dst)
done<-struct{}{}
}()
<-done
<-done
}
package main
import (
"fmt"
"net/http"
)
func handler(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "Hi there")
}
func main() {
http.HandleFunc("/", handler)
http.ListenAndServe(":8002", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.