98 lines
2.6 KiB
Go
98 lines
2.6 KiB
Go
package views
|
|
|
|
import (
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
urls "forgejo.gwairfelin.com/max/gispatcho"
|
|
"forgejo.gwairfelin.com/max/gonotes/internal/conf"
|
|
"forgejo.gwairfelin.com/max/gonotes/internal/notes"
|
|
"forgejo.gwairfelin.com/max/gonotes/internal/templ"
|
|
)
|
|
|
|
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)
|
|
urlEdit := myurls.Reverse("edit", urls.Repl{"note": title})
|
|
if err != nil {
|
|
http.Redirect(w, r, urlEdit, http.StatusFound)
|
|
return
|
|
}
|
|
|
|
context := templ.Ctx{"note": note, "urlEdit": urlEdit}
|
|
note.Render()
|
|
err = templ.RenderTemplate(w, "view.tmpl.html", context)
|
|
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 = ¬es.Note{Title: title}
|
|
}
|
|
|
|
urlSave := myurls.Reverse("save", urls.Repl{"note": title})
|
|
context := templ.Ctx{"note": note, "urlSave": urlSave, "text": string(note.Body)}
|
|
err = templ.RenderTemplate(w, "edit.tmpl.html", context)
|
|
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 := ¬es.Note{Title: title, Body: []byte(body)}
|
|
note.Save()
|
|
http.Redirect(w, r, myurls.Reverse("view", urls.Repl{"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 = templ.RenderTemplate(w, "list.tmpl.html", templ.Ctx{"titles": titles})
|
|
if err != nil {
|
|
log.Print(err.Error())
|
|
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
|
|
return
|
|
}
|
|
}
|