Skip to content

Instantly share code, notes, and snippets.

@cespare
Created June 16, 2012 01:08
Show Gist options
  • Save cespare/2939455 to your computer and use it in GitHub Desktop.
Save cespare/2939455 to your computer and use it in GitHub Desktop.
Reverse routing proxy in Go
[
["/foo", "localhost:8090"],
["/bar", "google.com:80"],
["/", "localhost:3000"]
]
/*
This is a simple routing reverse HTTP proxy. Its only purpose is to route HTTP requests to various servers by
matching simple rules against the paths of the requests. For example, suppose you're running a proxy on
localhost:4567 and you wish to proxy requests to 'localhost:4567/foo' to 'localhost:8888/foo' while other
requests go to 'localhost:9999/'. You can do that with the following config.json:
[
["/foo", "localhost:8888"],
["/", "localhost:9999"]
]
The matching rules will be matched in order (and this is why the format uses an array of tuples, rather than a
simple map).
*/
package main
import (
"encoding/json"
"io/ioutil"
"log"
"net/http"
"net/http/httputil"
"strings"
)
type RouteConfig [][2]string
func NewMuxingReverseProxy(config RouteConfig) *httputil.ReverseProxy {
director := func(request *http.Request) {
log.Printf("%v %v\n", request.Method, request.URL)
request.URL.Scheme = "http"
for _, pair := range config {
path, targetHost := pair[0], pair[1]
if strings.HasPrefix(request.URL.Path, path) {
request.URL.Host = targetHost
return
}
}
log.Printf("Warning: no matching pattern for path: %v\n", request.URL.Path)
}
return &httputil.ReverseProxy{Director: director}
}
func main() {
configText, e := ioutil.ReadFile("./config.json")
if e != nil {
log.Fatalf("Error: %v\n", e)
}
var config RouteConfig
if err := json.Unmarshal(configText, &config); err != nil {
log.Fatal("Error with config file: %v\n", err)
}
log.Println("# Routes:")
for _, pair := range config {
route, server := pair[0], pair[1]
log.Printf("# %v => %v\n", route, server)
}
log.Println()
log.Fatal(http.ListenAndServe(":9876", NewMuxingReverseProxy(config)))
}
@cespare
Copy link
Author

cespare commented Jun 16, 2012

This mostly seems to work except that it appears to have issues when there are a bunch of outstanding connections to a server and then the client cuts the connection. This seems to hang the backend server until the connections time out or something. To repro, load a really heavy-weight site and then try to refresh the whole page while it's busy making lots of XHRs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment