todo.txt integration
This commit is contained in:
@@ -0,0 +1,62 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// Root todo.txt rail widget (assets/todo-rail.js). /_todo reads and writes the
|
||||
// single wiki-root todo.txt — the path is fixed, so there is no traversal
|
||||
// surface. GET returns the raw text (404 when the file is absent, which the
|
||||
// widget treats as "render nothing"); POST replaces the whole file atomically.
|
||||
// Unlike the index.md save path, empty content does NOT delete the file: the
|
||||
// widget has no in-UI way to recreate it, so an empty save keeps an empty file.
|
||||
|
||||
func (h *handler) todoPath() string {
|
||||
return filepath.Join(h.root, "todo.txt")
|
||||
}
|
||||
|
||||
func (h *handler) handleTodo(w http.ResponseWriter, r *http.Request) {
|
||||
if !h.checkAuth(w, r) {
|
||||
return
|
||||
}
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
h.handleTodoGet(w, r)
|
||||
case http.MethodPost:
|
||||
h.handleTodoPost(w, r)
|
||||
default:
|
||||
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *handler) handleTodoGet(w http.ResponseWriter, r *http.Request) {
|
||||
data, err := os.ReadFile(h.todoPath())
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
http.Error(w, "read failed: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
// The rail re-fetches on every page load; a heuristically cached copy
|
||||
// would show stale todos after an edit.
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
w.Write(data)
|
||||
}
|
||||
|
||||
func (h *handler) handleTodoPost(w http.ResponseWriter, r *http.Request) {
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
content := r.FormValue("content")
|
||||
if err := writeFileAtomic(h.todoPath(), []byte(content), 0644); err != nil {
|
||||
http.Error(w, "write failed: "+err.Error(), http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
Reference in New Issue
Block a user