Skip to content

Instantly share code, notes, and snippets.

@roberto
Created March 15, 2016 18:26
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 roberto/144c4d56520da6855b2c to your computer and use it in GitHub Desktop.
Save roberto/144c4d56520da6855b2c to your computer and use it in GitHub Desktop.
package main
import (
"bytes"
"flag"
"fmt"
"github.com/elazarl/goproxy"
"github.com/robertkrimen/otto"
"io"
"io/ioutil"
"log"
. "net/http"
)
type nopCloser struct {
io.Reader
}
func (nopCloser) Close() error { return nil }
func main() {
verbose := flag.Bool("v", false, "should every proxy request be logged to stdout")
addr := flag.String("addr", ":8080", "proxy listen address")
flag.Parse()
proxy := goproxy.NewProxyHttpServer()
proxy.OnRequest().HandleConnect(goproxy.AlwaysMitm)
proxy.OnRequest().DoFunc(func(r *Request, ctx *goproxy.ProxyCtx) (*Request, *Response) {
fmt.Println(r.URL.Host + r.URL.Path)
return r, nil
})
proxy.OnResponse(goproxy.UrlIs("example.com:8001/endpoint/")).DoFunc(func(response *Response, context *goproxy.ProxyCtx) *Response {
defer response.Body.Close()
contents, _ := ioutil.ReadAll(response.Body)
data := string(contents)
vm := otto.New()
vm.Set("body", data)
vm.Run(`
var data;
data = JSON.parse(body);
data.message = "Hello";
body = JSON.stringify(data);
`)
newContents, _ := vm.Get("body")
{
newContents, _ := newContents.ToString()
response.Body = nopCloser{bytes.NewBufferString(newContents)}
}
return response
})
proxy.Verbose = *verbose
log.Fatal(ListenAndServe(*addr, proxy))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment