| 1 |
// Package main ... |
| 2 |
package main |
| 3 |
|
| 4 |
import ( |
| 5 |
"fmt" |
| 6 |
"log" |
| 7 |
"net/http" |
| 8 |
"net/http/httptest" |
| 9 |
"net/http/httputil" |
| 10 |
|
| 11 |
"github.com/go-rod/rod" |
| 12 |
"github.com/go-rod/rod/lib/launcher" |
| 13 |
) |
| 14 |
|
| 15 |
func main() { |
| 16 |
p := httptest.NewServer(newProxy()) |
| 17 |
defer p.Close() |
| 18 |
|
| 19 |
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 20 |
_, _ = fmt.Fprint(w, "test") |
| 21 |
})) |
| 22 |
defer s.Close() |
| 23 |
|
| 24 |
url := launcher.New().Proxy(p.URL).Set("proxy-bypass-list", "<-loopback>").MustLaunch() |
| 25 |
|
| 26 |
browser := rod.New().ControlURL(url).MustConnect() |
| 27 |
defer browser.MustClose() |
| 28 |
|
| 29 |
browser.MustIgnoreCertErrors(true) |
| 30 |
|
| 31 |
go browser.MustHandleAuth("u", "p")() |
| 32 |
|
| 33 |
page := browser.MustPage(s.URL) |
| 34 |
|
| 35 |
page.MustNavigate(s.URL + "/tab") |
| 36 |
} |
| 37 |
|
| 38 |
// newProxy creates a proxy that requires authentication. |
| 39 |
func newProxy() *httputil.ReverseProxy { |
| 40 |
return &httputil.ReverseProxy{ |
| 41 |
Director: func(r *http.Request) { |
| 42 |
if dump, err := httputil.DumpRequest(r, true); err == nil { |
| 43 |
log.Printf("%s", dump) |
| 44 |
} |
| 45 |
// hardcode username/password "u:p" (base64 encoded: dTpw ) to make it simple |
| 46 |
if auth := r.Header.Get("Proxy-Authorization"); auth != "Basic dTpw" { |
| 47 |
r.Header.Set("X-Failed", "407") |
| 48 |
} |
| 49 |
}, |
| 50 |
Transport: &transport{http.DefaultTransport}, |
| 51 |
ErrorHandler: func(w http.ResponseWriter, _ *http.Request, err error) { |
| 52 |
if err.Error() == "407" { |
| 53 |
log.Println("proxy: not authorized") |
| 54 |
w.Header().Add("Proxy-Authenticate", `Basic realm="Proxy Authorization"`) |
| 55 |
w.WriteHeader(http.StatusProxyAuthRequired) |
| 56 |
} else { |
| 57 |
w.WriteHeader(http.StatusBadGateway) |
| 58 |
} |
| 59 |
}, |
| 60 |
} |
| 61 |
} |
| 62 |
|
| 63 |
type transport struct { |
| 64 |
http.RoundTripper |
| 65 |
} |
| 66 |
|
| 67 |
func (t *transport) RoundTrip(r *http.Request) (*http.Response, error) { |
| 68 |
if h := r.Header.Get("X-Failed"); h != "" { |
| 69 |
return nil, fmt.Errorf(h) |
| 70 |
} |
| 71 |
return t.RoundTripper.RoundTrip(r) |
| 72 |
} |