gonotes/internal/notes/views/views.go

104 lines
2.6 KiB
Go

package views
import (
"html/template"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"gitea.gwairfelin.com/max/gonotes/internal/conf"
"gitea.gwairfelin.com/max/gonotes/internal/notes"
"gitea.gwairfelin.com/max/gonotes/internal/urls"
)
var myurls urls.URLs
func GetRoutes(prefix string) *http.ServeMux {
myurls = urls.URLs{
Prefix: prefix,
URLs: map[string]urls.URL{
"view": {Path: "/{note}/", Protocol: "GET", Handler: view},
"edit": {Path: "/{note}/edit/", Protocol: "GET", Handler: edit},
"save": {Path: "/{note}/edit/save/", Protocol: "POST", Handler: save},
"list": {Path: "/", Protocol: "GET", Handler: list},
},
}
return myurls.GetRouter()
}
func view(w http.ResponseWriter, r *http.Request) {
title := r.PathValue("note")
note, err := notes.LoadNote(title)
if err != nil {
http.Redirect(w, r, myurls.Reverse("edit", map[string]string{"note": title}), http.StatusFound)
return
}
note.Render()
err = renderTemplate(w, "view.html", note)
if err != nil {
log.Print(err.Error())
http.Error(w, "Couldn't load template", http.StatusInternalServerError)
return
}
}
func edit(w http.ResponseWriter, r *http.Request) {
title := r.PathValue("note")
note, err := notes.LoadNote(title)
if err != nil {
note = &notes.Note{Title: title}
}
err = renderTemplate(w, "edit.html", note)
if err != nil {
log.Print(err.Error())
http.Error(w, "Couldn't load template", http.StatusInternalServerError)
return
}
}
func save(w http.ResponseWriter, r *http.Request) {
title := r.PathValue("note")
body := r.FormValue("body")
note := &notes.Note{Title: title, Body: []byte(body)}
note.Save()
http.Redirect(w, r, myurls.Reverse("view", map[string]string{"note": title}), http.StatusFound)
}
func list(w http.ResponseWriter, r *http.Request) {
files, err := os.ReadDir(conf.Conf.NotesDir)
if err != nil {
log.Print(err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
titles := make([]string, 0)
for _, f := range files {
if !f.IsDir() {
title := strings.TrimSuffix(f.Name(), filepath.Ext(f.Name()))
titles = append(titles, title)
}
}
err = renderTemplate(w, "list.tmpl.html", map[string]any{"titles": titles})
if err != nil {
log.Print(err.Error())
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
}
func renderTemplate(w http.ResponseWriter, tmpl string, context any) error {
files := []string{
filepath.Join(conf.Conf.TemplatesDir, "base.tmpl.html"),
filepath.Join(conf.Conf.TemplatesDir, tmpl),
}
t, err := template.ParseFiles(files...)
t.ExecuteTemplate(w, "base", context)
return err
}