Skip to content

Instantly share code, notes, and snippets.

@jeddenlea
Created May 13, 2015 23:11
Show Gist options
  • Save jeddenlea/eafe976ef5366e207981 to your computer and use it in GitHub Desktop.
Save jeddenlea/eafe976ef5366e207981 to your computer and use it in GitHub Desktop.
Stupid http proxy
package main
import (
"flag"
"log"
"net/http"
"net/http/httputil"
"strings"
)
var (
flagLog = flag.Bool("log", true, "Log requests")
flagBind = flag.String("bind", ":8888", "Address to bind to")
flagTarget = flag.String("target", "localhost:8180", "Target address")
flagHeaders = flag.String("headers", "", "Headers to add in transit \"k=v|...\"")
)
func getHeaders() map[string]string {
if *flagHeaders == "" {
return nil
}
ret := make(map[string]string)
parts := strings.Split(*flagHeaders, "|")
for _, part := range parts {
eq := strings.IndexByte(part, '=')
if eq == -1 {
continue
}
key := part[:eq]
val := part[eq+1:]
ret[key] = val
}
return ret
}
func main() {
flag.Parse()
headers := getHeaders()
p := httputil.ReverseProxy{
Director: func(req *http.Request) {
if *flagLog {
log.Printf("%s %s %s", req.Method, req.Host, req.RequestURI)
}
req.URL.Scheme = "http"
req.URL.Host = *flagTarget
for k, v := range headers {
k = http.CanonicalHeaderKey(k)
switch k {
case "Host":
req.Host = v
case "Connection":
if v == "close" {
req.Close = true
} else {
req.Header.Set(k, v)
}
default:
req.Header.Set(k, v)
}
}
},
}
log.Fatalln(http.ListenAndServe(*flagBind, &p))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment