本文整理匯總了Golang中github.com/elazarl/goproxy.NewProxyHttpServer函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewProxyHttpServer函數的具體用法?Golang NewProxyHttpServer怎麽用?Golang NewProxyHttpServer使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewProxyHttpServer函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: TestContentType
func TestContentType(t *testing.T) {
proxy := goproxy.NewProxyHttpServer()
proxy.OnResponse(goproxy.ContentTypeIs("image/png")).DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
resp.Header.Set("X-Shmoopi", "1")
return resp
})
client, l := oneShotProxy(proxy, t)
defer l.Close()
for _, file := range []string{"test_data/panda.png", "test_data/football.png"} {
if resp, err := client.Get(localFile(file)); err != nil || resp.Header.Get("X-Shmoopi") != "1" {
if err == nil {
t.Error("pngs should have X-Shmoopi header = 1, actually", resp.Header.Get("X-Shmoopi"))
} else {
t.Error("error reading png", err)
}
}
}
file := "baby.jpg"
if resp, err := client.Get(localFile(file)); err != nil || resp.Header.Get("X-Shmoopi") != "" {
if err == nil {
t.Error("Non png images should NOT have X-Shmoopi header at all", resp.Header.Get("X-Shmoopi"))
} else {
t.Error("error reading png", err)
}
}
}
示例2: startProxy
func startProxy() {
verbose := flag.Bool("v", false, "should every proxy request be logged to stdout")
addr := flag.String("l", ":8080", "on which address should the proxy listen")
flag.Parse()
proxy := goproxy.NewProxyHttpServer()
proxy.Verbose = *verbose
if err := os.MkdirAll("db", 0755); err != nil {
log.Fatal("Can't create dir", err)
}
logger, err := NewLogger("db")
if err != nil {
log.Fatal("can't open log file", err)
}
proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
logger.LogReq(req, ctx)
return req, nil
})
proxy.OnResponse().DoFunc(func(resp *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
logger.LogResp(resp, ctx)
return resp
})
l, err := net.Listen("tcp", *addr)
if err != nil {
log.Fatal("listen:", err)
}
http.Serve(l, proxy)
}
示例3: main
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
flag.PrintDefaults()
fmt.Fprintln(os.Stderr, " -h : show help usage")
}
flag.Parse()
if *ip == "" && *iface != "" {
*ip = getIpFromInterface(*iface)
} else {
log.Fatal("IP address or Interface must be specified")
}
var servers []string
if *dnsServers == "" {
log.Fatal("DNS servers must be specified")
}
servers = strings.Split(*dnsServers, " ")
r := &resolver.Resolver{Servers: servers, LocalAddr: *ip}
proxy := goproxy.NewProxyHttpServer()
proxy.Verbose = *verbose
proxy.Tr.Dial = func(network, addr string) (c net.Conn, err error) {
if network == "tcp" {
var remoteAddr *net.TCPAddr
var err error
localAddr, err := net.ResolveTCPAddr(network, *ip+":0")
if err != nil {
return nil, err
}
chunks := strings.Split(addr, ":")
addrIp, err := r.LookupAddr(chunks[0])
if err != nil {
remoteAddr, err = net.ResolveTCPAddr(network, addr)
} else {
remoteAddr, err = net.ResolveTCPAddr(network, addrIp+":"+chunks[1])
}
if err != nil {
return nil, err
}
return net.DialTCP(network, localAddr, remoteAddr)
}
return net.Dial(network, addr)
}
go http.ListenAndServe(*listen, proxy)
log.Printf("DaisyProxy listen on %s outgoing from %s\n", *listen, *ip)
select {}
}
示例4: main
func main() {
flag.Parse()
proxy := goproxy.NewProxyHttpServer()
proxy.Verbose = true
println("Proxy server listening on " + *port)
log.Fatal(http.ListenAndServe(":"+*port, proxy))
}
示例5: Run
func Run() {
proxy := goproxy.NewProxyHttpServer()
proxy.Verbose = true
proxy.OnRequest().DoFunc(
func(r *Request, ctx *goproxy.ProxyCtx) (*Request, *Response) {
sessions[ctx.Session] = NewRoundTrip(time.Now())
for _, f := range onRequestCallbacks {
f(ctx.Req)
}
return r, nil
})
proxy.OnResponse().DoFunc(
func(r *Response, ctx *goproxy.ProxyCtx) *Response {
for _, f := range onResponseCallbacks {
f(ctx.Resp)
}
if ctx.Resp != nil {
roundTrip := sessions[ctx.Session]
roundTrip.ResponseTime = time.Now()
for _, f := range onDoneCallbacks {
f(&DoneRequestData{ctx.Req, ctx.Resp, roundTrip})
}
}
return r
})
log.Fatal(ListenAndServe(listen+":"+port, proxy))
}
示例6: main
func main() {
var proxy *goproxy.ProxyHttpServer
app.Main(func(a app.App) {
var sz size.Event
for e := range a.Events() {
switch e := app.Filter(e).(type) {
case lifecycle.Event:
if e.Crosses(lifecycle.StageAlive) == lifecycle.CrossOn && proxy == nil {
proxy = goproxy.NewProxyHttpServer()
//proxy.Verbose = true
re := regexp.MustCompile(`.*`)
proxy.OnResponse(goproxy.UrlMatches(re)).DoFunc(
func(res *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
if label != nil {
label.Text = fmt.Sprintf("%s\n%s\n", ctx.Req.URL, label.Text)
log.Println(ctx.Req.URL)
}
return res
})
go func() {
log.Fatal(http.ListenAndServe(":8888", proxy))
}()
}
case paint.Event:
onPaint(sz)
a.EndPaint(e)
case size.Event:
sz = e
}
}
})
}
示例7: main
func main() {
proxy := goproxy.NewProxyHttpServer()
proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*baidu.com$"))).
HandleConnect(goproxy.AlwaysReject)
proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*$"))).
HandleConnect(goproxy.AlwaysMitm)
// enable curl -p for all hosts on port 80
proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*:80$"))).
HijackConnect(func(req *http.Request, client net.Conn, ctx *goproxy.ProxyCtx) {
defer func() {
if e := recover(); e != nil {
ctx.Logf("error connecting to remote: %v", e)
client.Write([]byte("HTTP/1.1 500 Cannot reach destination\r\n\r\n"))
}
client.Close()
}()
clientBuf := bufio.NewReadWriter(bufio.NewReader(client), bufio.NewWriter(client))
remote, err := net.Dial("tcp", req.URL.Host)
orPanic(err)
remoteBuf := bufio.NewReadWriter(bufio.NewReader(remote), bufio.NewWriter(remote))
for {
req, err := http.ReadRequest(clientBuf.Reader)
orPanic(err)
orPanic(req.Write(remoteBuf))
orPanic(remoteBuf.Flush())
resp, err := http.ReadResponse(remoteBuf.Reader, req)
orPanic(err)
orPanic(resp.Write(clientBuf.Writer))
orPanic(clientBuf.Flush())
}
})
proxy.Verbose = true
log.Fatal(http.ListenAndServe(":8080", proxy))
}
示例8: TestProxy
func TestProxy(t *testing.T) {
c := httpclient.New(nil)
if !c.SupportsProxy() {
t.Skipf("current run environment does not support support proxies")
}
const addr = "127.0.0.1:12345"
proxy := goproxy.NewProxyHttpServer()
count := 0
proxy.OnRequest().DoFunc(
func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
count++
return r, nil
})
go func() {
http.ListenAndServe(addr, proxy)
}()
time.Sleep(time.Millisecond)
c.SetProxy(func(_ *http.Request) (*url.URL, error) {
return url.Parse("http://" + addr)
})
testUserAgent(t, c, httpclient.DefaultUserAgent)
if count != 1 {
t.Errorf("expecting 1 proxy request, got %d instead", count)
}
testUserAgent(t, c.Clone(nil), httpclient.DefaultUserAgent)
if count != 2 {
t.Errorf("expecting 2 proxy request, got %d instead", count)
}
}
示例9: TestGoproxyHijackConnect
func TestGoproxyHijackConnect(t *testing.T) {
proxy := goproxy.NewProxyHttpServer()
proxy.OnRequest(goproxy.ReqHostIs(srv.Listener.Addr().String())).
HijackConnect(func(req *http.Request, client net.Conn, ctx *goproxy.ProxyCtx) {
t.Logf("URL %+#v\nSTR %s", req.URL, req.URL.String())
resp, err := http.Get("http:" + req.URL.String() + "/bobo")
panicOnErr(err, "http.Get(CONNECT url)")
panicOnErr(resp.Write(client), "resp.Write(client)")
resp.Body.Close()
client.Close()
})
client, l := oneShotProxy(proxy, t)
defer l.Close()
proxyAddr := l.Listener.Addr().String()
conn, err := net.Dial("tcp", proxyAddr)
panicOnErr(err, "conn "+proxyAddr)
buf := bufio.NewReader(conn)
writeConnect(conn)
readConnectResponse(buf)
if txt := readResponse(buf); txt != "bobo" {
t.Error("Expected bobo for CONNECT /foo, got", txt)
}
if r := string(getOrFail(https.URL+"/bobo", client, t)); r != "bobo" {
t.Error("Expected bobo would keep working with CONNECT", r)
}
}
示例10: CreateDefault
func CreateDefault(listen string, configFile string, verbose bool) {
proxy := goproxy.NewProxyHttpServer()
proxy.Verbose = verbose
records := getConfig(configFile)
fmt.Println("Configuration from", configFile, ":")
for i, config := range records {
if i == 0 {
// header line
continue
}
defaultUrl := config[0]
regexpUrl, e := regexp.Compile(defaultUrl)
if e != nil {
fmt.Errorf("Can't parse regexp", defaultUrl, e.Error())
}
contentType := config[1]
newFile := config[2]
fmt.Println("- replace", defaultUrl, "by", newFile)
proxy.OnRequest(goproxy.UrlMatches(regexpUrl)).DoFunc(
func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
fmt.Print("Intercept ", defaultUrl, " and serve ", newFile)
response := NewResponse(r, contentType, http.StatusOK, newFile)
return r, response
})
}
fmt.Println("")
fmt.Println("Listen", listen)
fmt.Println("^C to stop")
fmt.Println("")
log.Fatal(http.ListenAndServe(listen, proxy))
}
示例11: main
func main() {
verbose := flag.Bool("v", false, "should every proxy request be logged to stdout")
flag.Parse()
proxy := goproxy.NewProxyHttpServer()
proxy.Verbose = *verbose
log.Fatal(http.ListenAndServe(":8080", proxy))
}
示例12: NewJqueryVersionProxy
// NewJQueryVersionProxy creates a proxy checking responses HTML content, looks
// for scripts referencing jQuery library and emits warnings if different
// versions of the library are being used for a given host.
func NewJqueryVersionProxy() *goproxy.ProxyHttpServer {
proxy := goproxy.NewProxyHttpServer()
m := make(map[string]string)
jqueryMatcher := regexp.MustCompile(`(?i:jquery\.)`)
proxy.OnResponse(goproxy_html.IsHtml).Do(goproxy_html.HandleString(
func(s string, ctx *goproxy.ProxyCtx) string {
for _, src := range findScriptSrc(s) {
if !jqueryMatcher.MatchString(src) {
continue
}
prev, ok := m[ctx.Req.Host]
if ok {
if prev != src {
ctx.Warnf("In %v, Contradicting jqueries %v %v",
ctx.Req.URL, prev, src)
break
}
} else {
ctx.Warnf("%s uses jquery %s", ctx.Req.Host, src)
m[ctx.Req.Host] = src
}
}
return s
}))
return proxy
}
示例13: ProxyThatModifiesResponsesFromURL
func ProxyThatModifiesResponsesFromURL(url string, modifier func(*http.Response, *goproxy.ProxyCtx) (newResponse *http.Response, newUrl string)) *goproxy.ProxyHttpServer {
proxy := goproxy.NewProxyHttpServer()
proxy.OnRequest().DoFunc(func(r *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
dump, _ := httputil.DumpRequest(ctx.Req, true)
println(string(dump))
return r, nil
})
proxy.OnResponse().DoFunc(func(r *http.Response, ctx *goproxy.ProxyCtx) *http.Response {
var coloredStatusCode string
status := fmt.Sprintf("[%d]", r.StatusCode)
if url != "" && strings.HasPrefix(ctx.Req.URL.String(), url) {
r, newUrl := modifier(r, ctx)
coloredStatusCode = termcolor.ColoredWithBackground(status, termcolor.White, termcolor.BgMagenta, termcolor.Bold)
fmt.Printf("%s %s %v => %s\n", coloredStatusCode, termcolor.Colored(ctx.Req.Method, termcolor.White, termcolor.Bold), ctx.Req.URL, newUrl)
return r
}
switch r.StatusCode {
case 301, 302:
coloredStatusCode = termcolor.Colored(status, termcolor.Cyan)
case 200:
coloredStatusCode = termcolor.Colored(status, termcolor.White)
case 404, 500:
coloredStatusCode = termcolor.Colored(status, termcolor.Red)
default:
coloredStatusCode = termcolor.Colored(status, termcolor.Magenta)
}
fmt.Printf("%s %s %v\n", coloredStatusCode, termcolor.Colored(ctx.Req.Method, termcolor.White, termcolor.Bold), ctx.Req.URL)
return r
})
return proxy
}
示例14: main
func main() {
var templateFilePath string
if len(os.Args) == 1 {
templateFilePath = "./template.html"
} else if len(os.Args) == 2 {
templateFilePath = os.Args[1]
} else {
panic("Unknown number of arguments. Please enter a template file")
}
content, err := ioutil.ReadFile(templateFilePath)
if err != nil {
panic(err)
}
var htmlStr string = string(content)
proxy := goproxy.NewProxyHttpServer()
proxy.OnRequest(goproxy.ReqHostMatches(regexp.MustCompile("^.*$"))).HandleConnect(goproxy.AlwaysMitm)
proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
return req, goproxy.NewResponse(req, goproxy.ContentTypeHtml, http.StatusForbidden, htmlStr)
})
log.Fatalln(http.ListenAndServe(":8401", proxy))
}
示例15: main
func main() {
addr := flag.String("addr", "[fe80::1%lxdbr0]:3128", "proxy listen address")
flag.Parse()
proxy := goproxy.NewProxyHttpServer()
log.Fatal(http.ListenAndServe(*addr, proxy))
}