Created
March 15, 2016 18:26
-
-
Save roberto/144c4d56520da6855b2c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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