Skip to content

Instantly share code, notes, and snippets.

@jschpp
Forked from JalfResi/revprox.go
Last active December 10, 2015 17:13
Show Gist options
  • Save jschpp/bba4bba9f71651ed0071 to your computer and use it in GitHub Desktop.
Save jschpp/bba4bba9f71651ed0071 to your computer and use it in GitHub Desktop.
Simple reverse proxy in Go - Prints forwarded addresses
package main
import (
"bytes"
"log"
"net/http"
"net/http/httputil"
"net/url"
"time"
)
func toJson(r *http.Request) *bytes.Buffer {
var out string
out += "{"
if r.Header.Get("X-Forwarded-For") != "" {
out += "\"X-Forwarded-For\":\""
out += r.Header.Get("X-Forwarded-For")
out += "\","
}
if r.URL.Path != "" {
out += "\"GET\":\""
out += r.URL.Path
out += "\","
}
if r.URL.Host != "" {
out += "\"Host\":\""
out += r.URL.Host
out += "\","
}
if r.Header.Get("CF-IPCountry") != "" {
out += "\"CF-IPCountry\":\""
out += r.Header.Get("CF-IPCountry")
out += "\","
}
if r.Header.Get("user-agent") != "" {
out += "\"user-agent\":\""
out += r.Header.Get("user-agent")
out += "\","
}
out += "\"time\":\""
out += time.Now().String() + "\""
out += "}"
log.Println(out)
return bytes.NewBufferString(out)
}
func main() {
remote, err := url.Parse("http://127.0.0.1:81")
if err != nil {
panic(err)
}
proxy := httputil.NewSingleHostReverseProxy(remote)
http.HandleFunc("/", handler(proxy))
err = http.ListenAndServe(":80", nil)
if err != nil {
panic(err)
}
}
func handler(p *httputil.ReverseProxy) func(http.ResponseWriter, *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
_, err := http.Post("http://localhost:9200/gatling/request/?pretty", "application/json", toJson(r))
if err != nil {
panic(err)
}
p.ServeHTTP(w, r)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment