Auto refresh todo editor.

This commit is contained in:
2026-07-03 12:02:16 +02:00
parent 5e72b073b8
commit 75d6c4d430
2 changed files with 95 additions and 12 deletions
+26 -2
View File
@@ -1,6 +1,8 @@
package main
import (
"crypto/sha256"
"encoding/hex"
"net/http"
"os"
"path/filepath"
@@ -12,11 +14,23 @@ import (
// 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
@@ -41,9 +55,16 @@ func (h *handler) handleTodoGet(w http.ResponseWriter, r *http.Request) {
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.
// 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)
}
@@ -58,5 +79,8 @@ func (h *handler) handleTodoPost(w http.ResponseWriter, r *http.Request) {
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)
}