Download project at step 10 (.zip)

10 / 14

Step 10 · Build a live chat app

🤖 Post messages

Each message belongs to a room and has a sender. Add Message to models.go, then generate its migration as you did for rooms.

Declare messages in migrations.go as Personal. Erasing the sender deletes their messages.

messages.go holds the rules: 1 to 500 characters, in a room that exists. The room page has the newest 100 messages, with the oldest at the top.

Deleting a room now means deleting its messages too. deleteRoom removes them in the same transaction as the room, so no message is left pointing at a room that is gone.

Open the room in two windows and send a message from one. The other window doesn't change until you reload it. The next step fixes that.

Check it worked

In a room, a message you send appears in the list, and an empty one is refused with a reason.

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

models.go Edit

internal/chat/models.go
package chat

import "time"

// Models is every model rastrillo migration generate manages; migration
// check fails the gate when it and migrations/ disagree.
var Models = []any{
	&Note{},
	&Room{},
	&Message{},
}

// Note is an example model: rename it, replace it, add more beside it.
// Query it through owned (auth.go), and never bind a request
// body onto a model; AGENTS.md says why.
type Note struct {
	ID        int64
	Owner     string `gorm:"index"`
	Title     string
	Body      string
	CreatedAt time.Time
	UpdatedAt time.Time
}

// Room is a place to talk. Admins make, rename and delete rooms.
type Room struct {
	ID        int64
	Name      string `gorm:"uniqueIndex"`
	CreatedAt time.Time
	UpdatedAt time.Time
}

// Message is one line somebody posted in a room.
type Message struct {
	ID        int64
	RoomID    int64 `gorm:"index"`
	Sender    string
	Text      string
	CreatedAt time.Time
}

migrations.go Edit

internal/chat/migrations.go
package chat

import (
	"embed"

	"amadan.net/rastrillo/rastrillo/apitoken"
	"amadan.net/rastrillo/rastrillo/auth"
	"amadan.net/rastrillo/rastrillo/migrate"
	"amadan.net/rastrillo/rastrillo/passkey"
	"amadan.net/rastrillo/rastrillo/pow"
	"amadan.net/rastrillo/rastrillo/sessions"
	"amadan.net/rastrillo/rastrillo/signin"
	"amadan.net/rastrillo/rastrillo/totp"
)

//go:embed migrations/*.sql
var migrationFS embed.FS

// Schema is this app's own migrations, which migration generate and
// check diff against Models. Never edit one that has shipped.
var Schema = migrate.MustFromFS(migrationFS, "chat").
	Declare(migrate.Data{Name: "notes", Key: []string{"id"},
		Kind: migrate.Personal, Owner: migrate.Subject("owner"),
		Erase: migrate.EraseRow, Export: true}).
	Declare(migrate.Data{Name: "rooms", Key: []string{"id"},
		Kind: migrate.Shared}).
	Declare(migrate.Data{Name: "messages", Key: []string{"id"},
		Kind: migrate.Personal, Owner: migrate.Subject("sender"),
		Erase: migrate.EraseRow, Export: true})

// BootSchema is what boot applies. A subsystem's schema goes here, in the
// order it applies, and never in Schema: check would drop its tables.
var BootSchema = migrate.Merge(sessions.Schema, auth.Schema,
	pow.Schema, passkey.Schema, totp.Schema, signin.Schema,
	apitoken.Schema, Schema)

messages.go New

internal/chat/messages.go
package chat

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

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

// A message is one line of chat, not a letter.
const messageLimit = 500

// The room page shows this many of the newest messages.
const messagesShown = 100

func (app *App) recentMessages(
	ctx context.Context, roomID int64,
) ([]Message, error) {
	var messages []Message
	err := app.database.G.WithContext(ctx).Where("room_id = ?", roomID).
		Order("id desc").Limit(messagesShown).Find(&messages).Error
	slices.Reverse(messages) // oldest first, as a chat reads
	return messages, err
}

func (app *App) postMessage(
	ctx context.Context, roomID int64, sender, text string,
) error {
	text = strings.TrimSpace(text)
	if text == "" || utf8.RuneCountInString(text) > messageLimit {
		return op.Invalid{Fields: map[string]string{
			"Text": "Write a message of 1 to 500 characters.",
		}}
	}
	if _, err := app.findRoom(ctx, roomID); err != nil {
		return err
	}
	message := Message{RoomID: roomID, Sender: sender, Text: text}
	return app.database.G.WithContext(ctx).Create(&message).Error
}

rooms.go Edit

internal/chat/rooms.go
package chat

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

	"gorm.io/gorm"

	"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) findRoom(ctx context.Context, id int64) (Room, error) {
	var room Room
	err := app.database.G.WithContext(ctx).First(&room, id).Error
	if errors.Is(err, gorm.ErrRecordNotFound) {
		return room, op.NotFound{}
	}
	return room, 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 (app *App) renameRoom(ctx context.Context, id int64, name string) error {
	name = strings.TrimSpace(name)
	if err := checkRoomName(name); err != nil {
		return err
	}
	renamed := app.database.G.WithContext(ctx).Model(&Room{}).
		Where("id = ?", id).Update("name", name)
	if renamed.Error == nil && renamed.RowsAffected == 0 {
		return op.NotFound{}
	}
	return nameTaken(renamed.Error)
}

// deleteRoom takes the room's messages with it, in one transaction, so
// no message is left pointing at a room that is gone.
func (app *App) deleteRoom(ctx context.Context, id int64) error {
	return app.database.G.WithContext(ctx).Transaction(
		func(transaction *gorm.DB) error {
			err := transaction.Where("room_id = ?", id).
				Delete(&Message{}).Error
			if err != nil {
				return err
			}
			deleted := transaction.Delete(&Room{}, id)
			if deleted.Error == nil && deleted.RowsAffected == 0 {
				return op.NotFound{}
			}
			return deleted.Error
		})
}

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
}

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,
		"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
	}
	visit.Redirect(roomPage.For(room.ID))
}

room.html Edit

internal/chat/templates/room.html
{{define "title"}}{{.Room.Name}}{{end}}
{{define "content"}}{{$L := localizer $}}
{{template "back-nav" dict "Href" (path $ "/") "Label" "Rooms"}}
{{template "page-header" dict "Title" .Room.Name}}
<div rst-box>
{{range .Messages}}<p><strong>{{.Sender}}</strong> {{.Text}}</p>
{{else}}<p>No messages yet. Say hello.</p>
{{end}}</div>
<section rst-box>
  <form rst-form method="post" action="{{path $ (printf "/rooms/%d/messages" .Room.ID)}}">
    {{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}}

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.Post(messagesPage, app.postMessageAt)
			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")
		})
	})
}
Terminal
rastrillo migration generate