package main import ( "crypto/sha256" "encoding/hex" "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. // // Both GET and POST carry an ETag (a content hash) so the widget can poll for // external edits: it revalidates GET with If-None-Match and reloads only when // another device actually changed the bytes. The POST response echoes the new // ETag so a device's own save comes back 304 rather than reloading itself. func (h *handler) todoPath() string { return filepath.Join(h.root, "todo.txt") } // todoETag is a strong validator derived from the file content — not mtime, so // a save of identical bytes (or a touch) does not look like a change. func todoETag(data []byte) string { sum := sha256.Sum256(data) return `"` + hex.EncodeToString(sum[:])[:16] + `"` } 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 and polls for external edits; a // heuristically cached copy would show stale todos. Revalidation is driven // by the ETag (If-None-Match) rather than the browser's own HTTP cache. etag := todoETag(data) w.Header().Set("ETag", etag) w.Header().Set("Cache-Control", "no-store") if r.Header.Get("If-None-Match") == etag { w.WriteHeader(http.StatusNotModified) return } 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 } // Echo the new ETag so the saving client can adopt it and skip reloading // its own write on the next poll. w.Header().Set("ETag", todoETag([]byte(content))) w.WriteHeader(http.StatusNoContent) }