Everyone who signs in should see the rooms. List them on the home page,
each linking to a page of its own, where messages go in the next step.
go test ./... fails after this change, as it should: the scaffold's
test of the home page still checks for the old Hello heading. Update
it to check for the empty room list instead.
Check it worked
You see the rooms listed on the home page, and each one opens a page with its name.
🤖 These pages were written by an LLM, on the ideas, instruction, and editing of humans. AI-written text here is always marked, visibly — that's factor X.
package chat
import (
"embed""html/template""maps""net/http""amadan.net/rastrillo/rastrillo""amadan.net/rastrillo/rastrillo/flash""amadan.net/rastrillo/rastrillo/live""amadan.net/rastrillo/rastrillo/locales""amadan.net/rastrillo/rastrillo/ui" genlocales "chat/gen/locales""chat/internal/chat/icons")
//go:embed templates staticvar appFS embed.FS
// assets fingerprints static/: {{asset "static/core.css"}} is a URL// with the content's hash in it, so it is cached for a year.var assets = rastrillo.NewAssets(appFS)
var pages, pagesErr = newPages()
func newPages() (*ui.Pages, error) {
config, err := locales.CheckConfig(
genlocales.DefaultLocale, genlocales.Locales)
if err != nil {
returnnil, err
}
files := map[string]ui.PageFile{}
for _, name := range []string{"index", "errors", "tokens", "admin_rooms",
"admin_room", "admin_room_delete", "room"} {
files[name] = ui.PageFile{Path: "templates/" + name + ".html"}
}
return ui.NewPages(ui.PagesConfig{
App: appFS, Layout: "templates/layout.html",
Pages: files, Locale: config, Assets: assets,
// Both icon seams, always: icon alone breaks cdn and js icons. Funcs: template.FuncMap{"icon": icons.Icon, "iconAssets": icons.Assets,
"asset": assets.Path},
})
}
// contextFor is each request's Ctx. Its Render draws through the request// it was built for, so a page has that request's language and base path.func (app *App) contextFor(request *http.Request) (*rastrillo.Ctx, error) {
return &rastrillo.Ctx{
DB: app.database.Writer(), Logger: app.logger, Assets: assets,
Authorize: authorize, ErrorPage: ErrorPage,
Render: func(_ *rastrillo.Ctx, response http.ResponseWriter,
page string, status int, data any) {
renderPage(response, request, app.live, page, status, data)
},
}, nil}
func renderPage(
response http.ResponseWriter, request *http.Request, hub *live.Hub,
page string, status int, data any,
) {
ok := status == http.StatusOK
if ok {
status = 0 // writes no 200, so a status already sent stands }
err := pages.Render(response, request, status, page,
func(takeFlash bool) (any, error) {
values, isMap := data.(map[string]any)
if !isMap && data != nil {
return data, nil }
values = withRequest(request, values)
values["Live"] = hub.View(request)
if takeFlash && ok { // a flash follows a 303 notice, _ := flash.Take(response, request)
values["Notice"] = notice.Message
}
return values, nil })
if err != nil {
http.Error(response, "Something went wrong.",
http.StatusInternalServerError)
}
}
// withRequest copies data, so a map the caller reuses never carries one// request's language into the next.func withRequest(request *http.Request, data map[string]any) map[string]any {
values := map[string]any{}
maps.Copy(values, data)
localized := ui.ForRequest(request)
values["L"] = pages.LocalizerFor(request)
values["Locales"], values["Return"] = localized.Locales, localized.Return
values["Scheme"], values["Base"] = localized.Scheme, localized.Base
values["SignedIn"], _ = request.Context().Value(signedInKey{}).(bool)
return values
}
// ErrorPage draws templates/errors.html for a refusal and, through// Options.ErrorPage, for a panic.func ErrorPage(
response http.ResponseWriter, request *http.Request, status int,
ref string,
) {
if pagesErr != nil {
http.Error(response, "Something went wrong.",
http.StatusInternalServerError)
return }
renderPage(response, request, nil, "errors", status,
map[string]any{"Status": status, "Ref": ref})
}
routes.go Edit
internal/chat/routes.go
package chat
import (
"net/http""amadan.net/rastrillo/rastrillo/action""amadan.net/rastrillo/rastrillo/csrf")
const homePage action.Path = "/"const accountPage action.Path = "/account"const livePage action.Path = "/live"// Routes registers everything the app serves. The API and MCP are outside// the page group: a bearer token is their only credential, so they get no// CSRF check and no page middleware.func Routes(routes *action.Routes, app *App) {
routes.Mount("/static", assets.Handler(), "static")
routes.Mount("/api/v1/mcp", app.mcp, "mcp")
routes.Mount("/api/v1", app.api, "api")
// Every page and form goes in this group: it is what checks CSRF. routes.Group(func(guarded *action.Routes) {
guarded.Guard("csrf", csrf.Protect(app.origin))
guarded.Guard("pages", pages.Middleware)
guarded.Guard("signedIn", app.signedIn)
// After a first link, the offer of a faster way in, once. guarded.Guard("signinGate", app.signins.Gate)
app.mountAuth(guarded)
guarded.Get(homePage, app.home)
// Owned pages and the stream: a visitor signs in first. guarded.Group(func(owned *action.Routes) {
owned.Guard("session", app.auth.RequireSession)
owned.Get(accountPage, app.account)
owned.Get(roomPage, app.room)
owned.Group(func(admin *action.Routes) {
admin.Guard("admin", app.requireAdmin)
admin.Get(adminRoomsPage, app.adminRooms)
admin.Post(adminRoomsPage, app.addRoom)
admin.Get(adminRoomPage, app.adminRoom)
admin.Post(adminRoomPage, app.renameRoomAt)
admin.Get(adminRoomDeletePage, app.confirmDeleteRoom)
admin.Post(adminRoomDeletePage, app.deleteRoomAt)
})
owned.Handle(http.MethodGet, livePage, app.live.Handler(),
"live")
})
})
}
index_test.go Edit
internal/chat/index_test.go
package chat_test
import (
"html/template""net/http""net/http/httptest""regexp""strings""testing""amadan.net/rastrillo/rastrillo" genlocales "chat/gen/locales""chat/internal/chat")
var hashedStylesheet = regexp.MustCompile(`/static/core\.[0-9a-f]{16}\.css`)
// The home page lists the rooms, and there are none in a new database.func TestIndexRenders(t *testing.T) {
t.Parallel()
recorder := get(t, newApp(t), "/")
if recorder.Code != http.StatusOK {
t.Fatalf("GET /: status %d, want 200. Behind sign-in this "+
"placeholder test fails: repoint or delete it", recorder.Code)
}
body := recorder.Body.String()
if !strings.Contains(body, "No rooms yet") {
t.Errorf("GET /: no empty room list:\n%s", body)
}
catalog := rastrillo.BaseCatalogs()[genlocales.DefaultLocale]
skip := template.HTMLEscapeString(catalog["rastrillo.ui.shell_skip"])
if !strings.Contains(body, skip) {
t.Errorf("GET /: no skip link in %s, the default language:\n%s",
genlocales.DefaultLocale, body)
}
}
func TestIndexLinksFingerprintedStylesheet(t *testing.T) {
t.Parallel()
handler := newApp(t)
href := hashedStylesheet.FindString(get(t, handler, "/").Body.String())
if href == "" {
t.Fatal("the index page links no fingerprinted stylesheet. Behind " +
"sign-in it redirects: point this test at a public page")
}
recorder := get(t, handler, href)
if recorder.Code != http.StatusOK {
t.Fatalf("GET %s: status %d, want 200", href, recorder.Code)
}
const year = "public, max-age=31536000, immutable"if got := recorder.Header().Get("Cache-Control"); got != year {
t.Errorf("GET %s: Cache-Control = %q, want immutable year", href, got)
}
}
// The bare name is never cached long, so a changed file shows on reload.func TestBareAssetNameStaysFresh(t *testing.T) {
t.Parallel()
recorder := get(t, newApp(t), "/static/core.css")
if recorder.Code != http.StatusOK {
t.Fatalf("GET /static/core.css: status %d, want 200",
recorder.Code)
}
if got := recorder.Header().Get("Cache-Control"); got != "no-cache" {
t.Errorf("Cache-Control = %q, want no-cache", got)
}
}
// A panic's page is the framework's error-page partial, not net/http's.func TestErrorPageRendersFrameworkPartial(t *testing.T) {
t.Parallel()
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodGet, "/", nil)
chat.ErrorPage(recorder, request,
http.StatusInternalServerError, "abc123")
if recorder.Code != http.StatusInternalServerError {
t.Fatalf("ErrorPage: status %d, want %d", recorder.Code,
http.StatusInternalServerError)
}
catalog := rastrillo.BaseCatalogs()[genlocales.DefaultLocale]
title := template.HTMLEscapeString(catalog["rastrillo.ui.error_500_title"])
body := recorder.Body.String()
if !strings.Contains(body, title) || !strings.Contains(body, "abc123") {
t.Errorf("ErrorPage: no 500 title or ref:\n%s", body)
}
}