prysm-pulse/validator/web/handler.go
Preston Van Loon 1f707842d2
Serve Prysm Web UI from Validator (#7470)
* Prysm web UI basic idea

* Refactor to use shared.Service interface, add sanity test

* register web server

* Determine mimetype

* Use 4242 as port for web

* Allow localhost or 127.0.0.1 for CORS. More tests, commentary

* Add flags, add site_data.go

* ignore site data

* Add sha

* gofmt

* gofmt

* fix script

* Lints

* fix vis

Co-authored-by: Victor Farazdagi <simple.square@gmail.com>
2020-10-09 09:58:30 -05:00

50 lines
1.4 KiB
Go

package web
import (
"mime"
"net/http"
"net/url"
"path"
log "github.com/sirupsen/logrus"
)
const prefix = "external/prysm_web_ui"
// webHandler serves web requests from the bundled site data.
var webHandler = func(res http.ResponseWriter, req *http.Request) {
u, err := url.ParseRequestURI(req.RequestURI)
if err != nil {
panic(err)
}
p := u.Path
if p == "/" {
p = "/index.html"
}
p = path.Join(prefix, p)
if d, ok := site[p]; ok {
m := mime.TypeByExtension(path.Ext(p))
res.Header().Add("Content-Type", m)
res.WriteHeader(200)
if _, err := res.Write(d); err != nil {
log.WithError(err).Error("Failed to write http response")
}
} else if d, ok := site[path.Join(prefix, "index.html")]; ok {
// Angular routing expects that routes are rewritten to serve index.html. For example, if
// requesting /login, this should serve the single page app index.html.
m := mime.TypeByExtension(".html")
res.Header().Add("Content-Type", m)
res.WriteHeader(200)
if _, err := res.Write(d); err != nil {
log.WithError(err).Error("Failed to write http response")
}
} else { // If index.html is not present, serve 404. This should never happen.
log.WithField("URI", req.RequestURI).Error("Path not found")
res.WriteHeader(404)
if _, err := res.Write([]byte("Not found")); err != nil {
log.WithError(err).Error("Failed to write http response")
}
}
}