Download project at step 11 (.zip)

11 / 14

Step 11 · Build a live chat app

🤖 Make the room live

On a live page, parts of the page update when the data behind them changes. Live-page support is already built into the app; you add the part that is specific to yours.

  • A topic is the name of something that changes: here room/7, for room 7's messages. Declare it in app.go, with who may follow it: anyone signed in.
  • A region is a part of the page tied to a topic. In room.html, the message list becomes region:messages.
  • Notify after the write. When postMessageAt saves a message, it tells the hub that the room's topic moved.

Every browser showing that room then fetches the region again through the same handler, with the permissions of the person viewing it. Only the topic name goes down the live stream, never the messages themselves.

With data-live-form, the form is sent without a page load, and the regions it names are swapped in from the response. The form is in a region of its own, so the box is cleared once a message is sent. With scripts turned off, everything still works as ordinary pages.

Check it worked

With the room open in two windows, a message sent in one appears in the other without a reload, and the box you typed in clears.

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

app.go Edit

internal/chat/app.go
package chat

import (
	"context"
	"log/slog"
	"net/http"
	"time"

	"github.com/go-chi/chi/v5"

	"amadan.net/rastrillo/rastrillo"
	"amadan.net/rastrillo/rastrillo/action"
	"amadan.net/rastrillo/rastrillo/auth"
	"amadan.net/rastrillo/rastrillo/background"
	"amadan.net/rastrillo/rastrillo/db"
	"amadan.net/rastrillo/rastrillo/live"
	"amadan.net/rastrillo/rastrillo/mail"
	"amadan.net/rastrillo/rastrillo/migrate"
	"amadan.net/rastrillo/rastrillo/perf"
	"amadan.net/rastrillo/rastrillo/signin"

	// Here, not in main, so the app's tests link the packs too.
	_ "chat/gen/locales"
)

type App struct {
	database *db.DB
	logger   *slog.Logger
	origin   string
	api      http.Handler
	mcp      http.Handler
	live     *live.Hub
	auth     *auth.Auth
	signins  *signin.Signins
}

// New migrates the database and builds the app, as one router inside the
// ServeMux that rastrillo.Options.Mux takes.
// Stop group before closing the database: sign-in's sweeps run on it.
func New(
	database *db.DB, origin string, group *background.Group,
	mailer mail.Sender, logger *slog.Logger,
) (*http.ServeMux, *live.Hub, error) {
	router, hub, err := Router(database, origin, group, mailer, logger)
	if err != nil {
		return nil, nil, err
	}
	mux := http.NewServeMux()
	mux.Handle("/", router)
	return mux, hub, nil
}

// Router is New's router, apart so that the perf test can walk it.
func Router(
	database *db.DB, origin string, group *background.Group,
	mailer mail.Sender, logger *slog.Logger,
) (chi.Router, *live.Hub, error) {
	if pagesErr != nil {
		return nil, nil, pagesErr
	}
	// BootSchema, not Schema: migrations.go says why.
	migrated, err := migrate.Apply(context.Background(), database, BootSchema)
	if err != nil {
		return nil, nil, err
	}
	logger.Info("migrate", "applied", migrated.Applied,
		"skipped", migrated.Skipped, "adopted", migrated.Adopted)
	api, mcp, err := newDoors(database, logger)
	if err != nil {
		return nil, nil, err
	}
	app := &App{database: database, logger: logger, origin: origin,
		api: api, mcp: mcp}
	if err := app.startAuth(group, mailer); err != nil {
		return nil, nil, err
	}
	app.live, err = live.New(live.Config{
		Path: string(livePage),
		Topics: map[string]live.Allow{
			"room": anyoneSignedIn,
		},
	})
	if err != nil {
		return nil, nil, err
	}
	router := chi.NewRouter()
	// First, so a page never misses a write.
	router.Use(app.live.Middleware)
	Routes(action.NewRoutes(router, app.contextFor), app)
	return router, app.live, nil
}

// Configure sets the serving options for main.go and the perf test, so
// what the perf lane measures is what production serves.
func Configure(
	options *rastrillo.Options, mux *http.ServeMux, hub *live.Hub,
	started time.Time,
) {
	options.Mux = mux
	options.Live = hub
	options.ErrorPage = ErrorPage
	var recorder perf.Recorder
	options.Wrap = perf.Middleware(&recorder,
		perf.Options{Started: started, Logger: options.Logger})
}

live.go New

internal/chat/live.go
package chat

import (
	"net/http"
	"strconv"

	"amadan.net/rastrillo/rastrillo/auth"
)

// anyoneSignedIn may follow any room: every room is open to everyone
// who has signed in.
func anyoneSignedIn(request *http.Request, _ string) bool {
	_, signedIn := auth.From(request)
	return signedIn
}

// roomTopic names one room's messages. The page that shows them follows
// it, and posting a message moves it.
func roomTopic(id int64) string {
	return "room/" + strconv.FormatInt(id, 10)
}

handlers.go Edit

internal/chat/handlers.go
package chat

import (
	"net/http"

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

const (
	roomPage     action.Path = "/rooms/{id}"
	messagesPage action.Path = "/rooms/{id}/messages"
)

func (app *App) home(visit *action.Visit) {
	rooms, err := app.listRooms(visit.Context())
	if visit.Refused(err) {
		return
	}
	visit.Render("index", http.StatusOK, map[string]any{"Rooms": rooms})
}

// roomForm is a room's page: its messages, and the form to post one.
type roomForm struct {
	app    *App
	room   Room
	parsed *form.Parsed
}

func (page roomForm) ShowAgain(
	visit *action.Visit, status int, errors form.Errors,
) {
	messages, err := page.app.recentMessages(visit.Context(), page.room.ID)
	if visit.Refused(err) {
		return
	}
	visit.Render("room", status, map[string]any{
		"Room": page.room, "Messages": messages,
		"Topic": roomTopic(page.room.ID),
		"Echo":  echoOf(page.parsed), "Errors": errors,
	})
}

func (app *App) room(visit *action.Visit) {
	room, err := app.roomAt(visit)
	if visit.Refused(err) {
		return
	}
	roomForm{app: app, room: room}.ShowAgain(visit, http.StatusOK, nil)
}

func (app *App) postMessageAt(visit *action.Visit) {
	room, err := app.roomAt(visit)
	if visit.Refused(err) {
		return
	}
	parsed, err := visit.ReadForm(form.Field{Name: "Text"})
	if visit.RefusedShowing(err, roomForm{app, room, parsed}) {
		return
	}
	err = app.postMessage(visit.Context(), room.ID,
		ownerOf(visit.Request()), parsed.String("Text"))
	if visit.RefusedShowing(err, roomForm{app, room, parsed}) {
		return
	}
	app.live.Notify(roomTopic(room.ID))
	visit.Redirect(roomPage.For(room.ID))
}

room.html Edit

internal/chat/templates/room.html
{{define "title"}}{{.Room.Name}}{{end}}
{{define "content"}}
{{template "back-nav" dict "Href" (path $ "/") "Label" "Rooms"}}
{{template "page-header" dict "Title" .Room.Name}}
{{template "region:messages" .}}
{{template "region:compose" .}}
{{end}}

{{define "region:messages"}}<div id="messages" rst-box {{.Live.Attrs .Topic}}>
{{range .Messages}}<p><strong>{{.Sender}}</strong> {{.Text}}</p>
{{else}}<p>No messages yet. Say hello.</p>
{{end}}</div>{{end}}

{{define "region:compose"}}{{$L := localizer $}}<section id="compose" rst-box {{.Live.Attrs .Topic}}>
  <form rst-form method="post" action="{{path $ (printf "/rooms/%d/messages" .Room.ID)}}" data-live-form="messages">
    {{template "field-text" dict "Name" "Text" "Label" "Message" "Value" (index .Echo "Text") "Error" (index .Errors "Text")}}
    {{template "form-foot" dict "L" $L "Submit" "Send"}}
  </form>
</section>{{end}}