1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
|
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
}
}
}
func RecipeEditHandler(w http.ResponseWriter, r *http.Request) {
var recipe model.Recipe
var err error
vars := mux.Vars(r)
recipe.Id = vars[`id`]
err = recipe.FromDB()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
err = html.ExecuteTemplate(w, `recipe-edit`, recipe)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
|