Created
January 5, 2011 02:57
-
-
Save blt/765860 to your computer and use it in GitHub Desktop.
First-stab at a transparent HTTP proxy in Go; a "getting started" project.
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 ( | |
"http" | |
"net" | |
"io/ioutil" | |
"os" | |
"fmt" | |
) | |
type handler struct{} | |
func (h *handler) ServeHTTP(resp http.ResponseWriter, req *http.Request) { | |
// Open new TCP connection to the server | |
client_tcp_conn, err := net.Dial("tcp", "", req.URL.Host) | |
if client_tcp_conn == nil { | |
fmt.Printf("Error: %s\n", err.String()) | |
os.Exit(1) | |
} | |
// Start a new HTTP connection on it | |
client_http_conn := http.NewClientConn(client_tcp_conn, nil) | |
// Pass on the request | |
client_http_conn.Write(req) | |
// Read back the reply | |
client_resp, _ := client_http_conn.Read() | |
// Write the reply to the original connection | |
reply, _ := ioutil.ReadAll(client_resp.Body) | |
resp.Write(reply) | |
// Close the connection to the server | |
client_http_conn.Close() | |
} | |
func main() { | |
local, err := net.Listen("tcp", "127.0.0.1:10000") | |
if local == nil { | |
fmt.Printf("Error: %s\n", err.String()) | |
os.Exit(1) | |
} | |
h := new(handler) | |
http.Serve(local, h) | |
} |
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
$ curl -sS http://troutwine.us | wc -l | |
52 | |
$ curl -sS --proxy1.0 127.0.0.1:100000 http://troutwine.us | wc -l | |
curl: (7) couldn't connect to host |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment