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) } }