Skip to content

Instantly share code, notes, and snippets.

@blt
Created Jan 5, 2011
Embed
What would you like to do?
First-stab at a transparent HTTP proxy in Go; a "getting started" project.
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)
}
$ 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