Add page for single entry

TODO: need to handle id that doesn't exist
server
nagee 2 years ago
parent 4c6342bc7c
commit fdedf1e7b8

@ -12,6 +12,7 @@ import (
"os/exec"
"path"
"runtime"
"strconv"
"git.nagee.dev/isthisnagee/diary/model"
)
@ -23,6 +24,11 @@ var templates map[string]*template.Template
type App struct{ *model.App }
type DiaryEntryTemplateData struct {
Entry model.DiaryEntry
Notes []*model.DiaryEntryNote
}
func LoadTemplates() error {
if templates == nil {
templates = make(map[string]*template.Template)
@ -90,6 +96,33 @@ func (app *App) ListDiaryEntries(w http.ResponseWriter, r *http.Request) {
}
}
func (app *App) DiaryEntry(w http.ResponseWriter, r *http.Request) {
var tmpl, ok = templates["entry.html"]
if !ok {
http.Error(w, "could not find template index", http.StatusInternalServerError)
return
}
var base = path.Base(r.URL.Path)
var id, err = strconv.Atoi(base)
if err != nil {
http.Error(w, "Cannot convert base to int: "+base, http.StatusBadRequest)
}
entry, err := app.GetDiaryEntry(int64(id))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
var notes = app.GetDiaryEntryNotes(int64(id))
var templateData = DiaryEntryTemplateData{*entry, notes}
if err := tmpl.Execute(w, templateData); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
func setup() *App {
home, err := os.UserHomeDir()
if err != nil {
@ -111,6 +144,7 @@ func Run(openBrowserAtUrl bool, defaultPort int) {
app := setup()
http.HandleFunc("/", app.ListDiaryEntries)
http.HandleFunc("/entry/", app.DiaryEntry)
var port int
if defaultPort <= 0 {

@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Entry {{ .Entry.Id }}</title>
</head>
<body>
<h1>{{ .Entry.Title }}</h1>
{{ range .Notes }}
<div>
<pre>
{{ .Body }}
</pre>
</div>
{{ end }}
</body>
</html>

@ -9,7 +9,7 @@
<h1>diary</h1>
<ul>
{{ range . }}
<li>{{ .Title }}</li>
<li><a href="/entry/{{ .Id }}">{{ .Title }}</a></li>
{{ end }}
</ul>
</body>

Loading…
Cancel
Save