vendor/github.com/go-rod/rod/lib/launcher/url_parser.go

139 lines · 2803 bytes

  1package launcher
  2
  3import (
  4	"context"
  5	"errors"
  6	"io"
  7	"net/http"
  8	"net/url"
  9	"regexp"
 10	"strings"
 11	"sync"
 12
 13	"github.com/go-rod/rod/lib/utils"
 14	"github.com/ysmood/gson"
 15)
 16
 17var _ io.Writer = &URLParser{}
 18
 19// URLParser to get control url from stderr.
 20type URLParser struct {
 21	URL    chan string
 22	Buffer string // buffer for the browser stdout
 23
 24	lock *sync.Mutex
 25	ctx  context.Context
 26	done bool
 27}
 28
 29// NewURLParser instance.
 30func NewURLParser() *URLParser {
 31	return &URLParser{
 32		URL:  make(chan string),
 33		lock: &sync.Mutex{},
 34		ctx:  context.Background(),
 35	}
 36}
 37
 38var regWS = regexp.MustCompile(`ws://.+/`)
 39
 40// Context sets the context.
 41func (r *URLParser) Context(ctx context.Context) *URLParser {
 42	r.ctx = ctx
 43	return r
 44}
 45
 46// Write interface.
 47func (r *URLParser) Write(p []byte) (n int, err error) {
 48	r.lock.Lock()
 49	defer r.lock.Unlock()
 50
 51	if !r.done {
 52		r.Buffer += string(p)
 53
 54		str := regWS.FindString(r.Buffer)
 55		if str != "" {
 56			u, err := url.Parse(strings.TrimSpace(str))
 57			utils.E(err)
 58
 59			select {
 60			case <-r.ctx.Done():
 61			case r.URL <- "http://" + u.Host:
 62			}
 63
 64			r.done = true
 65			r.Buffer = ""
 66		}
 67	}
 68
 69	return len(p), nil
 70}
 71
 72// Err returns the common error parsed from stdout and stderr.
 73func (r *URLParser) Err() error {
 74	r.lock.Lock()
 75	defer r.lock.Unlock()
 76
 77	msg := "[launcher] Failed to get the debug url: "
 78
 79	if strings.Contains(r.Buffer, "error while loading shared libraries") {
 80		msg = "[launcher] Failed to launch the browser, the doc might help https://go-rod.github.io/#/compatibility?id=os: "
 81	}
 82
 83	return errors.New(msg + r.Buffer)
 84}
 85
 86// MustResolveURL is similar to ResolveURL.
 87func MustResolveURL(u string) string {
 88	u, err := ResolveURL(u)
 89	utils.E(err)
 90	return u
 91}
 92
 93var (
 94	regPort     = regexp.MustCompile(`^\:?(\d+)$`)
 95	regProtocol = regexp.MustCompile(`^\w+://`)
 96)
 97
 98// ResolveURL by requesting the u, it will try best to normalize the u.
 99// The format of u can be "9222", ":9222", "host:9222", "ws://host:9222", "wss://host:9222",
100// "https://host:9222" "http://host:9222". The return string will look like:
101// "ws://host:9222/devtools/browser/4371405f-84df-4ad6-9e0f-eab81f7521cc"
102func ResolveURL(u string) (string, error) {
103	if u == "" {
104		u = "9222"
105	}
106
107	u = strings.TrimSpace(u)
108	u = regPort.ReplaceAllString(u, "127.0.0.1:$1")
109
110	if !regProtocol.MatchString(u) {
111		u = "http://" + u
112	}
113
114	parsed, err := url.Parse(u)
115	if err != nil {
116		return "", err
117	}
118
119	parsed = toHTTP(*parsed)
120	parsed.Path = "/json/version"
121
122	res, err := http.Get(parsed.String()) //nolint: noctx
123	if err != nil {
124		return "", err
125	}
126	defer func() { _ = res.Body.Close() }()
127
128	data, err := io.ReadAll(res.Body)
129	utils.E(err)
130
131	wsURL := gson.New(data).Get("webSocketDebuggerUrl").Str()
132
133	parsedWS, err := url.Parse(wsURL)
134	utils.E(err)
135
136	parsedWS.Host = parsed.Host
137
138	return parsedWS.String(), nil
139}