golang.org/x/build@v0.0.0-20240506185731-218518f32b70/internal/gomoteserver/ui/ui.go (about)

     1  // Copyright 2023 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  //go:build linux || darwin
     6  
     7  package ui
     8  
     9  import (
    10  	"bytes"
    11  	_ "embed"
    12  	"html"
    13  	"html/template"
    14  	"net/http"
    15  	"time"
    16  
    17  	"golang.org/x/build/internal/coordinator/remote"
    18  )
    19  
    20  var (
    21  	processStartTime = time.Now()
    22  	statusHTMLTmpl   = template.Must(template.New("statusHTML").Parse(string(statusHTML)))
    23  )
    24  
    25  // HandleStatusFunc gives a HTTP handler which can report the status of the instances
    26  // in the session pool.
    27  func HandleStatusFunc(pool interface{ List() []*remote.Session }, version string) http.HandlerFunc {
    28  	return func(w http.ResponseWriter, r *http.Request) {
    29  		if r.URL.Path != "/" {
    30  			http.NotFound(w, r)
    31  			return
    32  		}
    33  		type Instance struct {
    34  			Name    string
    35  			Created time.Duration
    36  			Expires time.Duration
    37  		}
    38  		type Status struct {
    39  			Instances []Instance
    40  			Version   string
    41  		}
    42  		var instances []Instance
    43  		sessions := pool.List()
    44  		for _, s := range sessions {
    45  			instances = append(instances, Instance{
    46  				Name:    html.EscapeString(s.ID),
    47  				Created: time.Since(s.Created),
    48  				Expires: time.Until(s.Expires),
    49  			})
    50  		}
    51  		statusHTMLTmpl.Execute(w, Status{
    52  			Instances: instances,
    53  			Version:   version,
    54  		})
    55  	}
    56  }
    57  
    58  //go:embed style.css
    59  var styleCSS []byte
    60  
    61  //go:embed status.html
    62  var statusHTML []byte
    63  
    64  // HandleStyleCSS responds with the CSS code.
    65  func HandleStyleCSS(w http.ResponseWriter, r *http.Request) {
    66  	w.Header().Set("Cache-Control", "no-cache, max-age=0")
    67  	http.ServeContent(w, r, "style.css", processStartTime, bytes.NewReader(styleCSS))
    68  }
    69  
    70  // Redirect redirects requests from the source host to the destination host if the host
    71  // matches the source host. If the host does not match the source host, then the request
    72  // will be passed to the passed in handler.
    73  func Redirect(hf http.HandlerFunc, srcHost, dstHost string) http.HandlerFunc {
    74  	return func(w http.ResponseWriter, r *http.Request) {
    75  		if r.Host == srcHost {
    76  			http.Redirect(w, r, "https://"+dstHost, http.StatusSeeOther)
    77  			return
    78  		}
    79  		hf(w, r)
    80  	}
    81  }