This commit is contained in:
parent
e75a4d4607
commit
4507728dae
32 changed files with 725 additions and 551 deletions
67
polyculeconnect/controller/ui/static.go
Normal file
67
polyculeconnect/controller/ui/static.go
Normal file
|
@ -0,0 +1,67 @@
|
|||
package ui
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
|
||||
"git.faercol.me/faercol/polyculeconnect/polyculeconnect/helpers"
|
||||
"github.com/sirupsen/logrus"
|
||||
)
|
||||
|
||||
const StaticRoute = "/static/"
|
||||
|
||||
type StaticController struct {
|
||||
}
|
||||
|
||||
func (sc *StaticController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
fs := http.FileServer(http.Dir("./static"))
|
||||
http.StripPrefix(StaticRoute, fs).ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
type IndexController struct {
|
||||
l *logrus.Logger
|
||||
}
|
||||
|
||||
func NewIndexController(l *logrus.Logger) *IndexController {
|
||||
return &IndexController{
|
||||
l: l,
|
||||
}
|
||||
}
|
||||
|
||||
func (ic IndexController) serveUI(w http.ResponseWriter, r *http.Request) (int, int, error) {
|
||||
lp := filepath.Join("templates", "index.html")
|
||||
tmpl, err := template.ParseFiles(lp)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, -1, fmt.Errorf("failed to init template: %w", err)
|
||||
}
|
||||
buf := new(bytes.Buffer)
|
||||
|
||||
if err := tmpl.Execute(buf, nil); err != nil {
|
||||
return http.StatusInternalServerError, -1, fmt.Errorf("failed to execute template: %w", err)
|
||||
}
|
||||
n, err := io.Copy(w, buf)
|
||||
if err != nil {
|
||||
return http.StatusInternalServerError, int(n), fmt.Errorf("failed to write response; %w", err)
|
||||
}
|
||||
|
||||
return http.StatusOK, int(n), nil
|
||||
}
|
||||
|
||||
func (ic *IndexController) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
if r.RequestURI != "/" {
|
||||
ic.l.Errorf("Unhandled route %q", r.RequestURI)
|
||||
helpers.HandleResponse(w, r, http.StatusNotFound, nil, ic.l)
|
||||
return
|
||||
}
|
||||
returncode, contentLength, err := ic.serveUI(w, r)
|
||||
if err != nil {
|
||||
ic.l.Errorf("Error serving UI: %s", err.Error())
|
||||
helpers.HandleResponse(w, r, returncode, nil, ic.l)
|
||||
} else {
|
||||
helpers.AddToContext(r, returncode, contentLength)
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue