summaryrefslogtreecommitdiff
path: root/view/common.go
diff options
context:
space:
mode:
Diffstat (limited to 'view/common.go')
-rw-r--r--view/common.go64
1 files changed, 64 insertions, 0 deletions
diff --git a/view/common.go b/view/common.go
new file mode 100644
index 0000000..c371fa0
--- /dev/null
+++ b/view/common.go
@@ -0,0 +1,64 @@
+package view
+
+import (
+ "embed"
+ "html/template"
+ "net/http"
+ "strings"
+ "reflect"
+
+ "xengineering.eu/ceres/model"
+
+ "github.com/gorilla/mux"
+)
+
+//go:embed html/*.html
+var htmlFS embed.FS
+
+var html *template.Template
+
+func Init() {
+ html = template.Must(template.New("html").ParseFS(htmlFS, "html/*.html"))
+}
+
+func HandlerHTML(prototype model.ReadableData) http.HandlerFunc {
+ t := reflect.TypeOf(prototype).Elem()
+
+ tmpl := t.String()
+ tmpl = strings.TrimPrefix(tmpl, `model.`)
+ tmpl = strings.ToLower(tmpl)
+
+ return func(w http.ResponseWriter, r *http.Request) {
+ data := reflect.New(t).Interface().(model.ReadableData)
+ var err error
+
+ v := reflect.ValueOf(data).Elem()
+ if v.Kind() == reflect.Struct {
+ id, ok := mux.Vars(r)[`id`]
+ if ok {
+ f := v.FieldByName(`Id`)
+ if f.IsValid() && f.CanSet() && f.Kind() == reflect.String {
+ f.SetString(id)
+ } else {
+ http.Error(w, `Requested struct data does not have a settable string ID`, http.StatusBadRequest)
+ return
+ }
+ } else {
+ http.Error(w, `Requested struct data without giving an ID`, http.StatusBadRequest)
+ return
+ }
+ }
+
+ err = data.FromDB()
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+
+ err = html.ExecuteTemplate(w, tmpl, data)
+ if err != nil {
+ http.Error(w, err.Error(), http.StatusInternalServerError)
+ return
+ }
+ }
+}