Download project at step 6 (.zip)

6 / 14

Step 6 · Build a live chat app

🤖 Add rooms from an admin page

Somebody has to make the rooms. This step adds an admin page with the rooms listed under a form to add one.

The app keeps the rules for rooms apart from the actions that answer web requests:

  • rooms.go holds the rules: a name of 1 to 40 characters, and no two rooms with the same name. There is no HTTP code in it, so a test can call its functions directly. When a rule is broken, the function returns op.Invalid with the field's name and the reason.
  • admin.go holds the actions. Each one reads the form, runs one rule, handles a refusal, and redirects on success. RefusedShowing redisplays the form with the error beside the field.

The page itself is templates/admin_rooms.html. Add its name to the list in render.go, and its two routes to routes.go, inside the group of pages that need sign-in.

Check it worked

Signed in, you see a form at http://localhost:8080/admin/rooms. A room you add appears in the list, and if you add the same name twice, you're told it is taken.

🤖 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.

rooms.go New

internal/chat/rooms.go
package chat

import (
	"context"
	"strings"
	"unicode/utf8"

	"amadan.net/rastrillo/rastrillo/op"
)

// A name longer than this would not fit the room list on a phone.
const roomNameLimit = 40

func (app *App) listRooms(ctx context.Context) ([]Room, error) {
	var rooms []Room
	err := app.database.G.WithContext(ctx).Order("name").Find(&rooms).Error
	return rooms, err
}

func (app *App) createRoom(ctx context.Context, name string) (Room, error) {
	room := Room{Name: strings.TrimSpace(name)}
	if err := checkRoomName(room.Name); err != nil {
		return room, err
	}
	err := app.database.G.WithContext(ctx).Create(&room).Error
	return room, nameTaken(err)
}

func checkRoomName(name string) error {
	if name == "" || utf8.RuneCountInString(name) > roomNameLimit {
		return op.Invalid{Fields: map[string]string{
			"Name": "Give the room a name of 1 to 40 characters.",
		}}
	}
	return nil
}

// nameTaken turns the unique index's refusal into a message the form
// can show beside the name.
func nameTaken(err error) error {
	if err != nil && strings.Contains(err.Error(), "UNIQUE") {
		return op.Invalid{Fields: map[string]string{
			"Name": "There is already a room with that name.",
		}}
	}
	return err
}

admin.go New

internal/chat/admin.go
package chat

import (
	"net/http"

	"amadan.net/rastrillo/rastrillo/action"
	"amadan.net/rastrillo/rastrillo/form"
)

const adminRoomsPage action.Path = "/admin/rooms"

// newRoomForm is the admin page: the rooms, and the form that adds one.
type newRoomForm struct {
	app    *App
	parsed *form.Parsed
}

func (page newRoomForm) ShowAgain(
	visit *action.Visit, status int, errors form.Errors,
) {
	rooms, err := page.app.listRooms(visit.Context())
	if visit.Refused(err) {
		return
	}
	visit.Render("admin_rooms", status, map[string]any{
		"Rooms": rooms, "Echo": echoOf(page.parsed), "Errors": errors,
	})
}

func (app *App) adminRooms(visit *action.Visit) {
	newRoomForm{app: app}.ShowAgain(visit, http.StatusOK, nil)
}

func (app *App) addRoom(visit *action.Visit) {
	parsed, err := visit.ReadForm(form.Field{Name: "Name"})
	if visit.RefusedShowing(err, newRoomForm{app, parsed}) {
		return
	}
	room, err := app.createRoom(visit.Context(), parsed.String("Name"))
	if visit.RefusedShowing(err, newRoomForm{app, parsed}) {
		return
	}
	visit.Flash("Added " + room.Name + ".")
	visit.Redirect(string(adminRoomsPage))
}

// echoOf is what the person typed, to fill the form in again.
func echoOf(parsed *form.Parsed) map[string]string {
	if parsed == nil {
		return map[string]string{}
	}
	return parsed.Echo()
}

admin_rooms.html New

internal/chat/templates/admin_rooms.html
{{define "title"}}Rooms · Admin{{end}}
{{define "content"}}{{$L := localizer $}}
{{template "page-header" dict "Title" "Rooms" "Sub" "Only admins see this page."}}
<section rst-box>
  <form rst-form method="post" action="{{path $ "/admin/rooms"}}">
    {{template "field-text" dict "Name" "Name" "Label" "New room" "Value" (index .Echo "Name") "Error" (index .Errors "Name") "Required" true}}
    {{template "form-foot" dict "L" $L "Submit" "Add room"}}
  </form>
</section>
{{if .Rooms}}<div rst-list>
{{range .Rooms}}{{template "list-row-action" dict "L" $L "Href" (path $ (printf "/admin/rooms/%d" .ID)) "Main" .Name}}
{{end}}</div>{{end}}
{{end}}

render.go Edit

internal/chat/render.go
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 static
var 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 {
		return nil, err
	}
	files := map[string]ui.PageFile{}
	for _, name := range []string{"index", "errors", "tokens", "admin_rooms"} {
		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(adminRoomsPage, app.adminRooms)
			owned.Post(adminRoomsPage, app.addRoom)
			owned.Handle(http.MethodGet, livePage, app.live.Handler(),
				"live")
		})
	})
}