73 lines
1.9 KiB
Go
73 lines
1.9 KiB
Go
|
|
package views
|
||
|
|
|
||
|
|
import (
|
||
|
|
"html/template"
|
||
|
|
"log"
|
||
|
|
"net/http"
|
||
|
|
"path/filepath"
|
||
|
|
|
||
|
|
"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: viewHandler},
|
||
|
|
"edit": {Path: "/{note}/edit/", Protocol: "GET", Handler: editHandler},
|
||
|
|
"save": {Path: "/{note}/edit/save/", Protocol: "POST", Handler: saveHandler},
|
||
|
|
},
|
||
|
|
}
|
||
|
|
return myurls.GetRouter()
|
||
|
|
}
|
||
|
|
|
||
|
|
func viewHandler(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.Println(err)
|
||
|
|
http.Error(w, "Couldn't load template", http.StatusInternalServerError)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func editHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
|
title := r.PathValue("note")
|
||
|
|
note, err := notes.LoadNote(title)
|
||
|
|
if err != nil {
|
||
|
|
note = ¬es.Note{Title: title}
|
||
|
|
}
|
||
|
|
|
||
|
|
err = renderTemplate(w, "edit.html", note)
|
||
|
|
if err != nil {
|
||
|
|
log.Println(err)
|
||
|
|
http.Error(w, "Couldn't load template", http.StatusInternalServerError)
|
||
|
|
return
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
func saveHandler(w http.ResponseWriter, r *http.Request) {
|
||
|
|
title := r.PathValue("note")
|
||
|
|
body := r.FormValue("body")
|
||
|
|
note := ¬es.Note{Title: title, Body: []byte(body)}
|
||
|
|
note.Save()
|
||
|
|
http.Redirect(w, r, myurls.Reverse("view", map[string]string{"note": title}), http.StatusFound)
|
||
|
|
}
|
||
|
|
|
||
|
|
func renderTemplate(w http.ResponseWriter, tmpl string, note *notes.Note) error {
|
||
|
|
t, err := template.ParseFiles(filepath.Join(conf.Conf.TemplatesDir, tmpl))
|
||
|
|
t.Execute(w, note)
|
||
|
|
return err
|
||
|
|
}
|