Skip to content

EN Routing and Middleware

Andrewkydev edited this page Aug 26, 2026 · 3 revisions

Routing and Middleware

Русский: RU-Routing-and-Middleware

app.Command("start", start)
app.Callback("menu.*", menu)
app.Text("help", help)
app.Match(regexp.MustCompile(`(?i)^find\s+(.+)$`), search)
app.Message(anyMessage)
app.On(event.TypeJoin, welcome)
app.Fallback(unhandled)

Processing order

  1. All On(ctx.Event.Type) handlers run in registration order.
  2. Commands are matched against a Command handler.
  3. Callback payloads are decoded and matched against a Callback handler.
  4. Text is checked against Text, then Match.
  5. All Message handlers run.
  6. Fallback is used only when there are no Message handlers.

Commands are case-insensitive. Do not include the leading / when registering one. Configure prefixes once before startup:

app.CommandPrefixes("/", "!")

Callback routes

kb := keyboard.Inline().Row().
	Callback("Profile", payload.New("menu", "profile", nil)).
	Build()

app.Command("menu", func(ctx *botctx.Context) error {
	return ctx.Send("Choose an action", &kb)
})

app.Callback("menu.profile", func(ctx *botctx.Context) error {
	if err := ctx.AnswerCallback("Opening"); err != nil {
		ctx.Log().Warn("callback answer failed", "error", err)
	}
	return ctx.EditText("Profile")
})

Exact routes and globs such as menu.* are supported. Exact routes always win; overlapping glob patterns are checked in registration order. Re-registering the same pattern replaces its handler without changing its position.

Middleware and groups

app.Use(loggingMiddleware)
private := app.Group(authMiddleware)
private.Command("profile", profile)

The first global middleware is the outermost one. Group middleware is appended after the global chain. Registering the same command again replaces its previous handler.

For persisted localization, order the middleware explicitly:

app.Use(state.SessionMiddleware(store.Sessions(), 24*time.Hour))
app.Use(i18n.Middleware(bundle))
app.Use(fsm.Middleware())

This lets localization resolve saved session locale before the platform locale and bundle default. See Localization.

Clone this wiki locally