Skip to content

Instantly share code, notes, and snippets.

@blt
Created January 5, 2011 02:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save blt/765860 to your computer and use it in GitHub Desktop.
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.
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