Skip to content

Commit

Permalink
cmd/coordinator: rewrite scheme-less URLs and redirects in dev mode
Browse files Browse the repository at this point in the history
This was created in preparation of removal of dashboard v2, which was
going to use a redirect. However dashboard v2 turned out to be useful
enough to warrant keeping and maintaining it.

Apply this enhancement to the local development serving path since it
is generally useful and already prepared.

For golang/go#65913.

Change-Id: I6006bfa02d512675b63773c22c9ed21d8d5b4ab4
Reviewed-on: https://go-review.googlesource.com/c/build/+/567497
Reviewed-by: Dmitri Shuralyov <[email protected]>
Auto-Submit: Dmitri Shuralyov <[email protected]>
LUCI-TryBot-Result: Go LUCI <[email protected]>
Reviewed-by: Michael Knyszek <[email protected]>
  • Loading branch information
dmitshur authored and gopherbot committed Feb 29, 2024
1 parent 9d46ba7 commit bf23401
Showing 1 changed file with 20 additions and 5 deletions.
25 changes: 20 additions & 5 deletions cmd/coordinator/coordinator.go
Original file line number Diff line number Diff line change
Expand Up @@ -174,15 +174,30 @@ func hostPathHandler(h http.Handler) http.Handler {

// A linkRewriter is a ResponseWriter that rewrites links in HTML output.
// It rewrites relative links /foo to be /host/foo, and it rewrites any link
// https://h/foo, where h is in validHosts, to be /h/foo. This corrects the
// links to have the right form for the test server.
// https://h/foo or //h/foo, where h is in validHosts, to be /h/foo.
// This corrects the links to have the right form for the local development mode.
type linkRewriter struct {
http.ResponseWriter
host string
buf []byte
ct string // content-type
}

func (r *linkRewriter) WriteHeader(code int) {
if l := r.Header().Get("Location"); l != "" {
if u, err := url.Parse(l); err == nil {
if u.Host == "" {
u.Path = "/" + r.host + u.Path
} else if validHosts[u.Host] {
u.Path = "/" + u.Host + u.Path
u.Scheme, u.Host = "", ""
}
r.Header().Set("Location", u.String())
}
}
r.ResponseWriter.WriteHeader(code)
}

func (r *linkRewriter) Write(data []byte) (int, error) {
if r.ct == "" {
ct := r.Header().Get("Content-Type")
Expand All @@ -200,12 +215,12 @@ func (r *linkRewriter) Write(data []byte) (int, error) {
}

func (r *linkRewriter) Flush() {
repl := []string{
`href="/`, `href="/` + r.host + `/`,
}
var repl []string
for host := range validHosts {
repl = append(repl, `href="https://`+host, `href="/`+host)
repl = append(repl, `href="//`+host, `href="/`+host) // Handle scheme-less URLs.
}
repl = append(repl, `href="/`, `href="/`+r.host+`/`)
strings.NewReplacer(repl...).WriteString(r.ResponseWriter, string(r.buf))
r.buf = nil
}
Expand Down

0 comments on commit bf23401

Please sign in to comment.