watchtower/pkg/dashboard/dashboard.go

83 lines
2 KiB
Go
Raw Normal View History

2022-11-10 23:32:26 +01:00
package dashboard
import (
2022-11-13 21:13:58 +01:00
"fmt"
"html/template"
2022-11-10 23:32:26 +01:00
"net/http"
2022-11-13 21:13:58 +01:00
"strings"
2022-11-10 23:32:26 +01:00
log "github.com/sirupsen/logrus"
)
// Dashboard is the http server responsible for serving the static Dashboard files
type Dashboard struct {
2022-11-13 21:13:58 +01:00
port string
rootDir string
apiPort string
apiScheme string
apiVersion string
2022-11-10 23:32:26 +01:00
}
// New is a factory function creating a new Dashboard instance
func New() *Dashboard {
2022-11-15 00:06:15 +01:00
const webRootDir = "./web/dist" // Todo: needs to work in containerized environment
const webPort = "8001" // Todo: make configurable?
const apiPort = "8080" // Todo: make configurable?
2022-11-13 21:13:58 +01:00
return &Dashboard{
apiPort: apiPort,
apiScheme: "http",
apiVersion: "v1",
rootDir: webRootDir,
port: webPort,
}
2022-11-10 23:32:26 +01:00
}
// Start the Dashboard and serve over HTTP
2022-11-13 21:13:58 +01:00
func (d *Dashboard) Start() error {
2022-11-10 23:32:26 +01:00
go func() {
2022-11-13 21:13:58 +01:00
d.runHTTPServer()
2022-11-10 23:32:26 +01:00
}()
return nil
}
2022-11-13 21:13:58 +01:00
func (d *Dashboard) templatedHttpHandler(h http.Handler) http.HandlerFunc {
const apiUrlTemplate = "%s://%s:%s/%s/"
indexTemplate, err := template.ParseFiles(d.rootDir + "/index.html")
if err != nil {
log.Error("Error when parsing index template")
log.Error(err)
return nil
}
2022-11-10 23:32:26 +01:00
2022-11-13 21:13:58 +01:00
return func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path == "/" {
hostName := strings.Split(r.Host, ":")[0]
apiUrl := fmt.Sprintf(apiUrlTemplate, d.apiScheme, hostName, d.apiPort, d.apiVersion)
err = indexTemplate.Execute(w, struct{ ApiUrl string }{
ApiUrl: apiUrl,
})
if err != nil {
log.Error("Error when executing index template")
log.Error(err)
w.WriteHeader(http.StatusInternalServerError)
return
}
} else {
h.ServeHTTP(w, r)
}
}
}
func (d *Dashboard) getHandler() http.Handler {
return d.templatedHttpHandler(http.FileServer(http.Dir(d.rootDir)))
2022-11-10 23:32:26 +01:00
}
2022-11-13 21:13:58 +01:00
func (d *Dashboard) runHTTPServer() {
serveMux := http.NewServeMux()
serveMux.Handle("/", d.getHandler())
log.Debug("Starting http dashboard server")
log.Fatal(http.ListenAndServe(":"+d.port, serveMux))
2022-11-10 23:32:26 +01:00
}