Ejemplo n.º 1
0
func TestWithBrowser(t *testing.T) {
	// an easy way to check if auth works with webserver
	// to test, run with
	// $ go test -run TestWithBrowser -- server
	// configure a browser to use the printed proxy address, use the proxy
	// and exit with Ctrl-C. It will throw error if your haven't acutally used the proxy
	if os.Args[len(os.Args)-1] != "server" {
		return
	}
	proxy := goproxy.NewProxyHttpServer()
	println("proxy localhost port 8082")
	access := int32(0)
	proxy.OnRequest().Do(auth.Basic("my_realm", func(user, passwd string) bool {
		atomic.AddInt32(&access, 1)
		return user == "user" && passwd == "1234"
	}))
	l, err := net.Listen("tcp", "localhost:8082")
	if err != nil {
		t.Fatal(err)
	}
	ch := make(chan os.Signal)
	signal.Notify(ch, os.Interrupt)
	go func() {
		<-ch
		l.Close()
	}()
	http.Serve(l, proxy)
	if access <= 0 {
		t.Error("No one accessed the proxy")
	}
}
Ejemplo n.º 2
0
func main() {
	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)
	}
	tr := transport.Transport{Proxy: transport.ProxyFromEnvironment}
	// For every incoming request, override the RoundTripper to extract
	// connection information. Store it is session context log it after
	// handling the response.
	proxy.OnRequest().DoFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (*http.Request, *http.Response) {
		ctx.RoundTripper = goproxy.RoundTripperFunc(func(req *http.Request, ctx *goproxy.ProxyCtx) (resp *http.Response, err error) {
			ctx.UserData, resp, err = tr.DetailedRoundTrip(req)
			return
		})
		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)
	}
	sl := newStoppableListener(l)
	ch := make(chan os.Signal)
	signal.Notify(ch, os.Interrupt)
	go func() {
		<-ch
		log.Println("Got SIGINT exiting")
		sl.Add(1)
		sl.Close()
		logger.Close()
		sl.Done()
	}()
	log.Println("Starting Proxy")
	http.Serve(sl, proxy)
	sl.Wait()
	log.Println("All connections closed - exit")
}