Created
August 18, 2016 11:49
-
-
Save legendtkl/c2483c73a3fdb01d36ed8f37d93d3b5c to your computer and use it in GitHub Desktop.
simple golang tcp proxy (forward request)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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