tifa

package module
v0.9.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 30, 2026 License: MIT Imports: 13 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Tifa

Full-stack Go web framework with React pages.

简体中文 · Writing an app · Build and run · Dev server · Example app

Go reference Go version CGO off License Not backed by Y Combinator Users unknown

Write the backend in Go and the pages in React. Tifa renders React inside the Go process and compiles the whole site into one executable, which you copy to one server and run, or put there with tifa deploy. No Node in production, no process manager, no reverse proxy, no Redis.

It is for Go developers whose business logic and data already live in Go, and for indie hackers and startup teams who want a real React app without running a stack beside it.

Tifa is very early. APIs will change, and many compiler optimizations are not done yet.

Why it exists

I wanted to ship a small product on TanStack Start. My other VPSes were full, Black Friday was still weeks away and I did not feel like buying another one, so I dug out an old box with 1 CPU and 1 GB of RAM. I had Codex set up the usual stack in one go: nginx, Node.js, PM2, TanStack Start, Redis, BullMQ, cron and SQLite.

It did not really run. It crawled.

So I started hacking on Tifa. Once it is done, deploying should mean copying one Go binary to the VPS, and that is it.

On a 1 CPU / 1 GB VPS The usual stack With Tifa
Reverse proxy and certificates nginx + certbot The Go HTTP server in the binary, which gets its own Let's Encrypt certificate and speaks HTTP/2
Runtime and process manager Node.js + PM2 One Go executable
React SSR TanStack Start TanStack Router, rendered inside the Go process by beastjs, the fastest pure Go JavaScript engine for rendering React
Cache Redis An in-process render memo for pages, a CDN in front if you want one, plus whatever you keep in Go memory
Queues and scheduled jobs BullMQ + cron Goroutines you start in OnStart
Database SQLite SQLite, with the fastest pure Go SQLite driver, so CGO stays off
Backups Litestream, or a cron job that copies the file Every commit copied to Cloudflare R2 about a second later, from inside the app, and restored on a new machine at its first start (db.backup)

I still do not know what to call it. A React SSR framework with no Node runtime? A React SSR framework with a Go backend? Both sound a little unhinged. Under the hood it is Go, beastjs (a pure Go JavaScript engine), and TanStack Router.

Go + React SSR has been tried before: go-starter-kit is archived, and go-react-ssr stopped in 2024 and renders through C QuickJS with CGO. Tifa is a finished framework around the same idea: Go routing, data loading, caching and background jobs, React rendered by a pure Go engine with CGO off, TanStack Router in the browser, and tifa deploy, all in one executable.

What it looks like

One folder per page. Go loads the data, React shows it:

// app/projects/project+/orders/order+/route.go  →  /projects/{project}/orders/{order}
func Load(c *tifa.Ctx) (orders.Order, error) {
	return orders.GetOrder(c.Param("project"), c.Param("order"))
}
// app/projects/project+/orders/order+/page.tsx
import { page, type PageData } from './route.gen'

export default function OrderPage() {
  const order = page.useLoaderData() // typed from the Go return value
  return <h2>{order.id}</h2>
}

// title and meta tags are written into the HTML on the server
export const head = ({ loaderData }: { loaderData?: PageData }) => ({
  meta: [{ title: `Order ${loaderData?.id}` }],
})
go get -tool github.com/liustack/tifa/cmd/tifa
go tool tifa dev     # hot-reloads components, restarts on Go changes
go tool tifa build   # bin/<app>, with the frontend embedded
go tool tifa check   # analysis, vet, tests and the TypeScript check in one go

Highlights

  • One file to deploy. Pure Go, CGO_ENABLED=0, cross-compiles like any Go program. The browser bundle, styles and server renderer are embedded in the executable.
  • Live on every push. tifa deploy setup sets up the server, Cloudflare and GitHub Actions in one command. After that every push is checked and goes live, and a release that fails its health check rolls back by itself. See Deploying.
  • Real HTML on the first request. Go runs the page's Load and every Layout function first, then renders React to complete HTML inside the process with beastjs, a pure Go JavaScript engine. Search engines and link previews see the content, title and meta tags. Each page renders whole in one pass: there is no streaming and there are no React Server Components.
  • Your frontend tools keep working. Vite, Tailwind and shadcn work as usual on your machine. The server runs one Go file and never installs Node.
  • Types from Go to React. The TypeScript type of each page's data is generated from what its Go Load returns.
  • Mistakes caught at build time. Duplicate paths, a Layout reading a parameter it does not own, a Load result that cannot become TypeScript: the build stops and names the file and line.
  • Fast after the first page. TanStack Router takes over in the browser. Each navigation is one request for data, and Layouts that are already loaded are not fetched again.

One server is enough

The render memo is on for every page, signed-in ones like a cart or a bill included. Every request fetches fresh data first and reuses the last render only when nothing changed, so a page is never stale. A render is reused only for the same data and the same session, so one person's page never reaches another. The app writes no caching code.

Whole visits, played back from real browsers on the example shop: shoppers, staff and crawlers on one server at once, every server as shipped and warmed up with the same visits first (2026-11-18).

Throughput at 8 concurrent sessions with no pause between pages, the median of 3 rounds:

Page views/s Full loads/s Client navigations/s
Tifa 118.8 38.3 80.5
Next.js 28.3 9.1 19.2
TanStack Start, uncompressed 94.7 30.5 64.2
For reference: Tifa with the render memo off 78.0 25.1 52.8
For reference: TanStack Start with gzip 64.5 20.8 43.7
For reference: Next.js with prefetch off 61.7 19.9 41.8

A full load is a request the server answers with a whole page: the landing of a visit, and a search or another action that loads a page. A client navigation is one the router answers with data alone. Every server plays the same visits, so about a third of the page views of every row are full loads.

Latency at 2.75 visits a second, half of what Next.js sustains, one round:

Full load P50 / P99 Client navigation P50 / P99
Tifa 31.3 / 65 ms 2.3 / 30 ms
Next.js 45.1 / 125 ms 18.0 / 118 ms
TanStack Start, uncompressed 27.5 / 62 ms 3.4 / 31 ms
For reference: Tifa with the render memo off 36.5 / 69 ms 2.6 / 37 ms
For reference: TanStack Start with gzip 40.7 / 107 ms 4.3 / 37 ms
For reference: Next.js with prefetch off 36.2 / 108 ms 7.7 / 59 ms

The first three rows are the frameworks as shipped. Each reference row changes one setting, to show what that default costs or buys. Versions: Tifa v0.1.0, slowjs v0.31.6, Next.js 16.4.6, TanStack Start 1.169.3, Node 24.13.0. Each server on one core of a Google Cloud t2d-standard-4 VM (AMD EPYC 7B13). Whole visits has the mix, what each default costs and what the numbers mean.

Start an app

You need Go 1.27, Node 20.19 or 22.12 and later (what Vite 8 asks for) and pnpm 10.16 or later (npm install -g pnpm). Pages need React 19.3 or later, which tifa new installs. Node only builds the front end: the program you deploy never needs it. tifa new, tifa dev, tifa check and tifa build run on Windows (10 1809 and later), and the program they build is bin\<app>.exe.

go run github.com/liustack/tifa/cmd/tifa@latest new myapp
cd myapp
go tool tifa dev     # http://127.0.0.1:9527

tifa new runs go mod tidy and pnpm install itself, which download the Go and npm packages and write the types your editor reads, and makes the first git commit. On a machine that has never built a Tifa app, that and the first tifa dev can take a few minutes. The compile itself takes about 7 seconds on an Apple M4 (an empty build cache, the whole app). Later builds use the caches.

tifa new writes a small todo list stored in SQLite to replace with your own domain: a home page with a Go Load, a POST the page calls from the browser, a page per todo, sessions kept in the database, tests, and a GitHub Actions workflow that runs go tool tifa check. Pass --empty to start without the todo list. The module path is the folder name unless you pass --module example.com/myapp.

Try the example

examples/shop is a small shop in two halves: an order workbench for the owner (order list, order details, a shipping form, sales stats with charts) and a storefront for customers in Chinese and English (product search and filters, product pages, a cart, a checkout form and a journal in Markdown). You need Go 1.27, Node 20.19 or 22.12 and later, and pnpm:

cd examples/shop
pnpm install --frozen-lockfile
go tool tifa build
./bin/shop           # http://127.0.0.1:9527

Use it with a coding agent

tifa new gives every app two things for coding agents, both from the Tifa version the app uses:

  • AGENTS.md, notes most coding agents read on their own: the conventions, the commands, and where the docs of this version are.
  • The Tifa skill (skills/tifa) in .claude/skills/tifa/, with more detail and links to the docs. Claude Code, Cursor and GitHub Copilot find it there. Codex and Gemini CLI look in .agents/skills/: copy the folder there, and again after an upgrade.

go tool tifa upgrade writes both again when it moves the app to a newer Tifa. go tool tifa agents does it without an upgrade, also in an app that has neither yet:

go tool tifa agents

More in Use Tifa with a coding agent.

Documentation

Doc Read it when
Tutorial You are new to Tifa and want to build a small app from the first folder to a running program
Guides: forms, uploads, sign-in, database, background work, email, languages, search engines and language models, streaming, values from the environment, logs Adding a common feature and you want a tested way to do it
Philosophy You want to know why a Tifa app is organized the way it is
Structuring an app Deciding where domain code, storage and shared resources go, and which way packages may import each other
Use Tifa with a coding agent Working on an app with Claude Code, Codex, Cursor or another coding agent
Writing an app Laying out folders, how they become URLs, and which doc to read next
The parts of an app: routing, layouts, loading data, method handlers, links and navigation, head, errors, render switches and caches, server render, styles, hooks, testing, testing pages Writing the Go and React code of a route, Layouts, 404 pages, head tags, Cache for CDNs, what the server render has, CSS, startup code, Go tests and tests of pages
Sessions Signing users in and out, keeping sessions in Redis or SQL, or showing who is signed in
Content Keeping a blog or docs as Markdown files and reading them in Go
Build and run Building the program with tifa build, building it for another system, or checking what to ship with it
Generated files and app setup You want to know what tifa build generates and how the program answers requests
Dev server Running tifa dev locally, or a change did not reload
Deploying Putting the program on a server or in a container, or behind a CDN or proxy
Configuration Where settings come from: tifa.yaml, flags, the environment and .env, and the options of your app
Settings Deploying: the port, HTTPS, body limit, VMs, render timeout, the render memo and the Cache-Control of pages with Cache
Architecture You want to know how a request, tifa build, tifa dev, the VM pool and the render memo work inside
Conventions You want every file, folder and name Tifa reads on one page: page.tsx, route.go, Load, Cache, hooks and the generated files
Render memo You want to know why pages, signed-in ones included, are reused safely with nothing to set up
Compatibility You want to know whether a Tifa upgrade can break your app, and what stays stable
Performance You want to know whether one server can carry your traffic
Research studies You want the full method and data behind a number, or to see whether an idea was already tried
Testing Contributing to Tifa itself

Talk to us

Issues are welcome any time: open one. Tell us what you built, where it hurt, and what should come next. Follow the liustack WeChat official account, and come find me on X: @liustack. What changes in Tifa and what comes next are shared on WeChat and X.

The liustack WeChat official account: AI startup opportunities, indie-dev insights, and hands-on AI tooling, delivered as they happen. Scan the QR code in WeChat, or search for "liustack":

liustack WeChat official account

Contributing

Tifa does not accept pull requests. A framework like this touches the compiler, the bundler, server rendering and developer experience at once, and a change in one pulls on the others. Getting that right takes a lot of context, so every line is written and reviewed by one author. Two ways to help:

  • Open an issue. Bugs, ideas, confusing errors, unclear docs. A clear issue with steps to reproduce helps more than a patch, and issues shape what gets built next.
  • Fork it. Under MIT your copy is yours to change and publish. CONTRIBUTING.md has the notes for working on a fork.

Star History

Star History Chart

License

MIT. A program built with Tifa embeds locale data and time zones from Unicode CLDR, ICU and go-intl, whose notices go with the program when you distribute it, see docs/build-and-deploy/build.md.

The gopher in the banner is a redrawn Go gopher, originally designed by Renee French and used under CC BY 4.0.

Documentation

Overview

Package tifa is the API of Tifa, the full-stack Go framework, that application code imports: the request context, errors and Layout data reuse.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotFound = core.ErrNotFound

ErrNotFound makes the server answer 404 without calling OnError.

View Source
var ErrSSRBusy = core.ErrSSRBusy

ErrSSRBusy means SSR was rejected because its queue was full or its wait expired. OnRequest can match it with errors.Is. The default response is 503 with Retry-After.

Functions

func Bool

func Bool(key string, def bool, help string) bool

Bool defines an option of the app that is true or false, see String. Its flag alone, such as --shop-open, is true, and takes a value only after =: --shop-open=false.

func ClearSession

func ClearSession(c *Ctx) error

ClearSession signs the request out: it deletes the record, drops the cookie, and Session returns nil from now on. It does nothing when the request has no session. When the record cannot be deleted the cookie is still dropped, and the error says the record stays valid until it expires. Where it may be called is the same as for SetSession.

func Duration

func Duration(key string, def time.Duration, help string) time.Duration

Duration defines an option of the app that is a duration in Go's format, such as 3s or 1m30s, see String.

func Int

func Int(key string, def int, help string) int

Int defines an option of the app that is a whole number, see String.

func Languages added in v0.0.5

func Languages() []string

Languages returns the languages of the site, the default language first and then the others in byte order, nil for an app without languages. They are the names of the <language>.json files of every _locales folder under app/ (a draft does not count), and the default language is i18n.default of tifa.yaml. Use it where the app lists its languages, such as the Languages of a content collection:

var Journal = content.Define[Post](content.Source{Dir: "journal", Languages: tifa.Languages()})

It works while the package initializes, so a package-level var may call it. tifa build and tifa dev build it into the program. Anywhere else, such as go test and go run, it reads those files and tifa.yaml in the module of the current folder, once.

func Redirect

func Redirect(url string, status int) error

Redirect returns an error that makes the server redirect to url with status, such as http.StatusSeeOther. Return it from Load, a method handler or OnRequest. It panics when status is not 3xx, which is a mistake in the code and not a condition at run time.

func Secret added in v0.0.4

func Secret(key, help string) string

Secret defines an option of the app that is a secret, such as a password or an API token, and returns its value, empty when no source sets it. It comes from the environment variable, the .env file of the working directory or the file of -c, see String. A flag would show it in the process list to every user of the machine, so the program refuses one and says where to put it. config prints where a secret came from and never its value.

var SMTPPassword = tifa.Secret("smtp.password", "SMTP password")

func Session

func Session[S any](c *Ctx) *S

Session returns the session of the request, nil when nobody is signed in. The server reads it before OnRequest runs, so every hook, Load and method handler can call it, and the Loads that run at once share the one value: treat it as read-only. The record is decoded into S on the first call. A record that does not fit S is deleted and its cookie dropped, and the request is signed out. On a page with Cache in its route.go, GET and HEAD requests are anonymous and Session is nil.

func SetHTTPHandler

func SetHTTPHandler(wrap func(app http.Handler) http.Handler)

SetHTTPHandler wraps the handler of the whole server with wrap, which gets tifa's handler and returns the handler to serve. Use it for plain net/http middleware, such as pprof or OpenTelemetry. The wrapper sees every request, static files and the 403 of a cross-site write included, with the original http.ResponseWriter, and does not go through OnRequest, OnError or the cross-site check. A shutdown waits for the requests it wraps. Call it in OnStart: it panics once the server listens. nil removes the wrapper. It runs outside the anonymous request of a page with Cache: the values it puts into the context of the request reach OnRequest and Load of such a page, so do not recognize visitors in it, do it in OnRequest.

func SetSession

func SetSession[S any](c *Ctx, s *S) error

SetSession signs the request in. It stores s as the session under a new random token, deletes the session the request came with, and sets the session cookie, which lasts 30 days (session.max_age) from now and is not renewed. Session[S](c) returns the new value for the rest of the request. Every call makes a new token, so calling it again after a sign-in changes the token again.

s is encoded as JSON, and the record, with the framework's envelope, must not pass 4 KiB: keep an ID and a few display fields in it, and the rest in your database. The record is trusted: a store that others can write to can sign anyone in.

It returns an error, and changes nothing, when the store cannot be written. When the old session cannot be deleted the sign-in is not done either, so the old session is not left behind next to the new one. It also returns an error in a Load, a Layout and OnError, in OnRequest once next returned, and after the response is sent. Call it in OnRequest before next, or in a method handler.

S must be the same type in every call of SetSession and Session, or the call panics.

A page with Cache in its route.go is served anonymously: its GET and HEAD requests have no session and SetSession returns an error there. Put sign-in and OAuth callbacks on routes without Cache.

func SetSessionStore

func SetSessionStore(s SessionStore)

SetSessionStore sets where sessions are kept, for example a store on Redis or SQL, in place of the in-memory one. Call it in OnStart: it panics once the server listens. nil restores the in-memory store.

func SetSitemap added in v0.1.5

func SetSitemap(f func(c *Ctx) (Sitemap, error))

SetSitemap sets the function that lists the pages of the site. With site.url set, the program answers /sitemap.xml, /robots.txt, /llms.txt and /llms-full.txt, and the Markdown version of a page whose SitemapPage has Content at its path with .md (/index.md for the home page). The pages without parameters are in the sitemap without it. The function runs on each request for those files, so pages that a date publishes show up at that date. An error it returns, a Path that matches no page and a page with parameters that is neither listed nor excluded answer 500. Call it in OnStart: it panics once the server listens. nil removes it.

func ShuttingDown added in v0.0.2

func ShuttingDown(ctx context.Context) <-chan struct{}

ShuttingDown returns a channel that is closed when the server that took the request starts to shut down: it has stopped taking new connections, and gives the requests in flight server.shutdown_timeout to finish. ctx is the context of the request, c.Context(), or one made from it. A handler that streams with no end of its own, such as server-sent events, returns when the channel is closed, so the program can stop at once. A request that ends by itself, such as a long upload or an answer still being written, can ignore it and finish.

For a context that no server made, as in a test, it returns nil, which never fires in a select.

func Size

func Size(key string, def int64, help string) int64

Size defines an option of the app that is a number of bytes, see String. It is written as a whole number with an optional unit B, KiB, MiB or GiB, such as 512KiB.

func String

func String(key, def, help string) string

String defines an option of the app and returns its value. Write it in a package-level var of options.go in the root of the app, where tifa build looks for it:

var DBURL = tifa.String("db.url", "app.db", "Database file")

The key is lower case letters, digits and underscores, in at least two parts joined with dots. Its flag is --db-url and its environment variable DB_URL. The value comes from the first of these that sets it: the flag, the environment variable, the .env file of the working directory, the file of -c, and then def. An invalid value gives def, and the program lists it with the other invalid settings and stops before OnStart. In a test binary the value is def, and a test sets the variable itself.

func Strings

func Strings(key string, def []string, help string) []string

Strings defines an option of the app whose value is a list, written as comma-separated text such as a.example,b.example, see String. Spaces around each item are dropped, empty text is no items, and an empty item between commas is invalid.

func Use

func Use[T any](c *Ctx, load func(*Ctx) (T, error)) (T, error)

Use returns the result of a Layout function for this request, the Layout of the caller's directory or of a directory above it: tifa.Use(c, project.Layout). Each function runs at most once per request, a second caller waits for the first run.

func WithRenderClock

func WithRenderClock(ctx context.Context, now func() time.Time) context.Context

WithRenderClock returns a context whose server render reads now for Date, Temporal.Now and Intl's current time. nil restores the live clock. Set it before rendering, for example in OnRequest with c.WithContext. The clock runs on the rendering goroutine and must not block. If requests share it, it must be safe for concurrent calls. It does not change Go's time.Now, deadlines, or module initialization during VM prewarming. A request with a render clock skips the render memo, so it always renders and never shares a render with another request.

Types

type Alternate added in v0.0.5

type Alternate struct {
	Language string
	Path     string
}

Alternate is one version of a page in a language, see Ctx.SetAlternates. Path is the URL path of that version as a visitor sees it, escaped, with no query and no language prefix: tifa adds the prefix of the language.

type Ctx

type Ctx core.Ctx

Ctx is one request and its response. Load, Layout, the method handlers, Validate, OnRequest and OnError receive it.

It is a type of its own, not an alias of the type that holds the request inside Tifa, so that go doc and pkg.go.dev show its methods: they show none for an alias.

func (*Ctx) Bind added in v0.9.2

func (c *Ctx) Bind(v any) error

Bind decodes the request body into v by Content-Type: JSON, URL-encoded form or multipart form. A multipart form also fills the fields of type *multipart.FileHeader and []*multipart.FileHeader with its files. Client mistakes come back as Error with status 400, 408, 413 or 415. A method handler with an input gets it decoded this way, so call Bind only in a handler that takes the Ctx alone. It fails the build in a Load or a Layout.

func (*Ctx) BindQuery added in v0.9.2

func (c *Ctx) BindQuery(v any) error

BindQuery decodes the query string into the struct v, with the names and value types of a form body. Query parameters that name no field are ignored. A query string that does not parse, or a value that does not, comes back as Error with status 400. Every exported field of v must be one a form fills, or BindQuery returns an error whatever the query holds. It is for method handlers: a Load or a Layout takes its query parameters as a second parameter, and calling BindQuery there fails the build.

func (*Ctx) Context added in v0.9.2

func (c *Ctx) Context() context.Context

Context returns the context of the request, which is canceled when the client goes away or the request ends. Pass it to the database and to outgoing requests, so they stop when nobody waits for the answer. WithContext gives a Ctx that carries another one.

func (*Ctx) Cookie added in v0.9.2

func (c *Ctx) Cookie(name string) (*http.Cookie, error)

Cookie returns the request cookie name, and http.ErrNoCookie when the request has none. A GET of a page with Cache in its route.go is anonymous and has no cookies.

func (*Ctx) Header added in v0.9.2

func (c *Ctx) Header(name string) string

Header returns the first value of the request header name, "" when the request has none. The name is not case-sensitive. A GET of a page with Cache in its route.go is anonymous, and the app sees none of the headers that tell visitors apart.

func (*Ctx) IsDataRequest added in v0.9.2

func (c *Ctx) IsDataRequest() bool

IsDataRequest reports whether this is the data request of a navigation in the browser router, rather than a page load.

func (*Ctx) JSON added in v0.9.2

func (c *Ctx) JSON(code int, v any) error

JSON writes v as the JSON answer with status code, and Content-Type application/json. Map keys are sorted, a nil slice is [] and a nil map is {}. A method handler that returns a value needs no call: Tifa writes the value. It fails the build in a Load or a Layout, and returns an error there without writing, since the page writes the answer.

func (*Ctx) Language added in v0.9.2

func (c *Ctx) Language() string

Language returns the language of the route the request is for: the language in the URL, the default language when the URL has none, and so for a route outside every area of a site with languages. It is empty on a site without languages.

func (*Ctx) NoContent added in v0.9.2

func (c *Ctx) NoContent(code int) error

NoContent writes status code with no body, such as http.StatusNoContent after a write that returns nothing. Like JSON, it is not for a Load or a Layout.

func (*Ctx) Param added in v0.9.2

func (c *Ctx) Param(name string) string

Param returns the value of the path parameter name, decoded, such as c.Param("order") for the folder order+. In a Layout function it is "" for a parameter of a folder below the Layout, as in the copy Request returns there.

func (*Ctx) Path added in v0.9.2

func (c *Ctx) Path() string

Path is the path of the page as the visitor sees it in the address bar: escaped the way the browser writes it, with the language prefix and without the query. The page load and the data request of a client navigation give the same path, and a handler gets its own path. Calling it in a Layout fails the build: a Layout is shared by the pages below it.

func (*Ctx) Pattern added in v0.9.2

func (c *Ctx) Pattern() string

Pattern is the path of the matched route, such as "/projects/{project}", empty when the URL matched no route.

func (*Ctx) Query added in v0.9.2

func (c *Ctx) Query(name string) string

Query returns the first value of the query parameter name, "" when there is none, from the request Request returns. It is for method handlers, Validate and OnRequest: a Load or a Layout takes its query parameters as a second parameter, and calling Query there fails the build.

func (*Ctx) QueryValues added in v0.9.2

func (c *Ctx) QueryValues(name string) []string

QueryValues returns every value of the query parameter name, in order, and nil when there is none. Query returns only the first. Like Query, it fails the build in a Load or a Layout.

func (*Ctx) Request added in v0.9.2

func (c *Ctx) Request() *http.Request

Request returns the request. In a Load or Layout function, and the functions it calls, it is a copy made on the first call of the run, which holds what the function may depend on: the query parameters it declared, the path parameters of its own folder for a Layout, and no body. Each run has its own copy, so a function that changes it changes nothing of another.

func (*Ctx) SetAlternates added in v0.9.2

func (c *Ctx) SetAlternates(list []Alternate)

SetAlternates replaces the versions of the page in other languages. Without it a page exists in every language of its area, at the same path under another prefix. Call it in a Load of a page where that is wrong: a content entry whose slug differs in another language, or that is missing in one. Include the page itself. The last call wins, and an empty list says the page has one version.

func (*Ctx) SetBodyLimit added in v0.9.2

func (c *Ctx) SetBodyLimit(n int64) error

SetBodyLimit changes the request body limit, server.body_limit by default. Call it before anything reads the body, on the goroutine that handles the request, usually in OnRequest. Once reading has started it returns an error and the limit stays as it was.

func (*Ctx) SetCookie added in v0.9.2

func (c *Ctx) SetCookie(cookie *http.Cookie)

SetCookie adds a Set-Cookie header for cookie to the response. It may be called in a Load or a Layout too. The cookie goes out as written: set HttpOnly, Secure and SameSite yourself.

func (*Ctx) SetHeader added in v0.9.2

func (c *Ctx) SetHeader(key, value string)

SetHeader sets the response header key to value, replacing any value it had. It may be called in a Load or a Layout too, also from Loads that run at once: the page sends the header with its answer.

func (*Ctx) SetReadTimeout added in v0.9.2

func (c *Ctx) SetReadTimeout(d time.Duration) error

SetReadTimeout gives the body of this request d to arrive, in place of server.read_timeout, and the answer server.write_timeout after that. Call it before anything reads the body, on the goroutine that handles the request, usually in OnRequest. Once reading has started it returns an error and the deadline stays as it was. It also returns an error when d is not over 0 or when the response cannot reach the connection, such as behind a middleware of SetHTTPHandler that does not unwrap it. A request with no body, such as a GET, keeps its deadlines and the call does nothing. A Ctx a test made with tifatest.NewCtx has no connection, and the call does nothing either.

func (*Ctx) Text added in v0.9.2

func (c *Ctx) Text(code int, s string) error

Text writes s as the answer with status code, and Content-Type text/plain in UTF-8. Like JSON, it is not for a Load or a Layout.

func (*Ctx) WithContext added in v0.9.2

func (c *Ctx) WithContext(ctx context.Context) *Ctx

WithContext returns a shallow copy of c whose request carries ctx, as http.Request.WithContext does. c is not changed. Both share the response and the state of the request: Loads run once for either, and the multipart files of the copy are removed when the request ends.

func (*Ctx) Writer added in v0.9.2

func (c *Ctx) Writer() http.ResponseWriter

Writer returns the http.ResponseWriter of the request, for an answer JSON, Text and NoContent do not write, such as a file, a stream or server-sent events. Write the headers first, then the body. Writing to it from a Load or a Layout breaks the page, which Tifa writes once they return.

type Error

type Error struct {
	Status  int
	Message string
}

Error is a failure that is safe to show to the client. Returned from Load, a method handler or OnRequest, it is answered with its own status and message without calling OnError. OnError also returns it. Bind, BindQuery and the decoding of an input or a query struct return one for a mistake of the client, such as a body that is not JSON.

func (Error) Error added in v0.9.2

func (e Error) Error() string

type Fields

type Fields map[string]string

Fields is a message per input field, by its json name. Returned from Validate or a handler, it is answered with 422 and the messages as "fields" in the JSON, without calling OnError. It is a separate type so that Error stays comparable.

func (Fields) Err added in v0.9.2

func (f Fields) Err() error

Err returns f, or nil when f has no entries. An empty Fields is still a non-nil error, so a validator that fills a Fields ends with it:

return fields.Err()

func (Fields) Error added in v0.9.2

func (f Fields) Error() string

type HTML

type HTML string

HTML is markup the app trusts, such as an article the build turned from Markdown into HTML or HTML a CMS returns, which a page shows as it is with <HTML value={...}> of tifa/client. It may be in the data of Load and Layout and in the result of a method handler, and is written as a JSON string, but it cannot be a map key or part of an input or the session. Only put markup you trust into it: sanitize HTML a user wrote before converting it, as with template.HTML of html/template.

A page the server renders carries such a value once, in its markup: its hydration data holds a marker in place of the value, and <HTML> reads the markup back from the page when the browser hydrates it. Navigation data and a page with SSR = false carry the string.

type MemoStats added in v0.0.5

type MemoStats struct {
	Entries   int    // entries kept now
	Hits      uint64 // answered from an entry
	Misses    uint64 // rendered by the request
	Shared    uint64 // waited for the same page another request was rendering at the time
	Evictions uint64 // entries dropped to make room for another, those hit only once first
}

MemoStats is the render memo in ServerStats.

type RedirectError

type RedirectError struct {
	URL    string
	Status int
}

RedirectError is what Redirect returns. OnRequest and tests can match it with errors.As.

func (*RedirectError) Error added in v0.9.2

func (e *RedirectError) Error() string

type SSRStats added in v0.0.2

type SSRStats struct {
	VMs    int // VMs loaded now: ssr.vms, one more while a VM that grew is replaced, one fewer while a failed one is
	Busy   int // VMs rendering now
	Queued int // renders waiting for a VM now, at most ssr.queue_limit
	// Renders counts the renders that ran in a VM, and Failed those of them that failed: an
	// exception, ssr.timeout or ssr.vm_memory.
	Renders, Failed uint64
	// RenderTime is how long the renders took, together. RenderTime / Renders is the mean.
	RenderTime time.Duration
	// Rejected counts the renders refused with ErrSSRBusy and answered 503: the queue was full, or
	// the wait passed ssr.wait_timeout.
	Rejected uint64
	// Replaced counts the VMs replaced because they grew: after a collection one held more than
	// half of ssr.vm_memory.
	Replaced uint64
	// Memory is what the VMs hold now, in bytes: the sum of the size each had after its last
	// collection.
	Memory int64
}

SSRStats is the VM pool in ServerStats.

type ServerStats added in v0.0.2

type ServerStats struct {
	SSR SSRStats // the VM pool
	// Memo counts the renders of pages, whose Hits skip the VM, and the answers for the files of
	// the site (sitemap.xml, llms.txt and the Markdown of a page).
	Memo      MemoStats
	MemoBytes int64 // what the render memo holds now, in bytes
	MemoSize  int64 // what it may hold, ssr.memo_size
}

ServerStats is what Stats returns: the VM pool that renders pages and the render memo. Counts run from the start of the program, the other fields are the state now. Under tifa dev the counts of SSR start again when the front end is rebuilt.

func Stats added in v0.0.2

func Stats() ServerStats

Stats returns the state of the server now. It is cheap and safe to call from many requests at once, such as from a route that a monitoring system reads. Before the server starts and after it stops it returns the zero ServerStats. An app without pages has a zero SSR.

type SessionStore

type SessionStore interface {
	Get(ctx context.Context, key string) (data []byte, found bool, err error)
	Put(ctx context.Context, key string, data []byte, expiry time.Time) error
	Delete(ctx context.Context, key string) error
}

SessionStore keeps the records of sessions. The framework stores one record per session under the SHA-256 of the session token (base64url), not under the token the browser holds. Get, Put and Delete are called from many requests at once and must be safe for that.

Get returns the record. A key that is missing, expired or not valid is found == false with a nil error. err is only for a failure of the store itself, such as a lost connection: the request then fails, it is not treated as signed out. Put creates or replaces the record, and Get does not return it after expiry. It must not keep the data slice it is given, and Get must not return a slice the store still uses. Delete returns nil for a key that does not exist. All three return an error when ctx is done.

type Sitemap added in v0.1.5

type Sitemap struct {
	// Name is the name of the site, the title of llms.txt. Empty, it is the host of site.url.
	Name string
	// Summary is one or two sentences about the site, the summary of llms.txt.
	Summary string
	// Exclude lists route patterns, as c.Pattern() writes them, such as "/projects/{project}" or
	// "/login". Each leaves out its pages and the pages below it.
	Exclude []string
	// Pages lists the pages of the routes with parameters, and the pages without parameters that
	// need a title, a date or a Markdown version.
	Pages []SitemapPage
}

Sitemap is what the app says about its pages, which sitemap.xml, llms.txt, llms-full.txt and the Markdown versions of the pages are made from. See SetSitemap. The pages without parameters are in it without being listed.

type SitemapPage added in v0.1.5

type SitemapPage struct {
	// Language is the language of the page: one of the languages of its area, "" on a site without
	// languages and for a page outside every area.
	Language string
	// Path is the path of the page as a visitor sees it, escaped, without the language prefix and
	// the query, as in Alternate: "/blog/hello-world".
	Path string
	// Modified is when the page last changed, the lastmod of the sitemap. Zero leaves it out.
	Modified time.Time
	// Title and Description name and describe the page in llms.txt. Without a Title the home page
	// is named after the site (Sitemap.Name, else the host of site.url), and any other page by its path.
	Title       string
	Description string
	// Content is the entry of a content collection the page shows, such as a post read from
	// Blog.Get: any value of a type that embeds content.Entry. With it the page has a Markdown
	// version at its path with .md, and its text is in llms-full.txt.
	Content icontent.Entry
	// Alternates lists the versions of the page in each language, itself included, as
	// c.SetAlternates takes them. Empty, the page is in every language of its area at the same path.
	Alternates []Alternate
}

SitemapPage is one page of a Sitemap.

Directories

Path Synopsis
cmd
tifa command
Command tifa builds and inspects tifa applications.
Command tifa builds and inspects tifa applications.
Package content reads the Markdown files of an app as typed collections.
Package content reads the Markdown files of an app as typed collections.
Package docs carries the English docs for writing an app, so tifa agents can index the docs of the Tifa version it was built from in the AGENTS.md of an app.
Package docs carries the English docs for writing an app, so tifa agents can index the docs of the Tifa version it was built from in the AGENTS.md of an app.
internal
analyze
Package analyze reads a tifa application with go/packages and go/types, checks its routing conventions and produces the route manifest.
Package analyze reads a tifa application with go/packages and go/types, checks its routing conventions and produces the route manifest.
bundle
Package bundle builds the front end of an application with the application's own Vite, which runs on Node: the browser bundle, and the SSR bundle that QuickJS evaluates.
Package bundle builds the front end of an application with the application's own Vite, which runs on Node: the browser bundle, and the SSR bundle that QuickJS evaluates.
bundle/hostgen command
Command hostgen writes js/runtime/host.js from js/host.
Command hostgen writes js/runtime/host.js from js/host.
codegen
Package codegen writes the generated part of a tifa application into its .tifa directory: the Go main with the route registration, and the TypeScript route tree, the route.gen modules, the two entries, the tsconfig and the JavaScript runtime, and the profile go build optimizes with.
Package codegen writes the generated part of a tifa application into its .tifa directory: the Go main with the route registration, and the TypeScript route tree, the route.gen modules, the two entries, the tsconfig and the JavaScript runtime, and the profile go build optimizes with.
config
Package config holds the settings of tifa and of the app, and reads them from their sources.
Package config holds the settings of tifa and of the app, and reads them from their sources.
content
Package content connects the content collections an app declares with the package github.com/liustack/tifa/content to the server, the build and tifatest.
Package content connects the content collections an app declares with the package github.com/liustack/tifa/content to the server, the build and tifatest.
content/scan
Package scan reads the content/ folder of an app as tifa build does: which files are entries, their IDs, slugs and paths, the front matter checked against the schema and turned into JSON, translations, drafts and word counts.
Package scan reads the content/ folder of an app as tifa build does: which files are entries, their IDs, slugs and paths, the front matter checked against the schema and turned into JSON, translations, drafts and word counts.
content/scan/internal/schemas
Package schemas holds schema types for the test that compares the field trees reflect and go/types give.
Package schemas holds schema types for the test that compares the field trees reflect and go/types give.
core
Package core holds the request context behind the public tifa package.
Package core holds the request context behind the public tifa package.
deverrors
Package deverrors holds the errors tifa dev keeps for `tifa errors`: their kinds, their JSON form, and the lists that keep the latest of each kind and count repeats.
Package deverrors holds the errors tifa dev keeps for `tifa errors`: their kinds, their JSON form, and the lists that keep the latest of each kind and count repeats.
devserver
Package devserver is the core of tifa dev.
Package devserver is the core of tifa dev.
foreign
Package foreign recognizes code written for another framework in a Tifa app: the imports, directives, exports and file names of Next.js, Remix and React Router, TanStack Start and SvelteKit, and the handlers of other Go web frameworks.
Package foreign recognizes code written for another framework in a Tifa app: the imports, directives, exports and file names of Next.js, Remix and React Router, TanStack Start and SvelteKit, and the handlers of other Go web frameworks.
langs
Package langs reads the languages of an app from its _locales folders.
Package langs reads the languages of an app from its _locales folders.
realpath
Package realpath finds the real name of a file or folder.
Package realpath finds the real name of a file or folder.
ssr
Package ssr renders pages to HTML in a pool of prewarmed QuickJS VMs.
Package ssr renders pages to HTML in a pool of prewarmed QuickJS VMs.
symwalk
Package symwalk walks a directory tree like filepath.WalkDir, but follows symbolic links.
Package symwalk walks a directory tree like filepath.WalkDir, but follows symbolic links.
testproc
Package testproc starts the programs that tests run in the background, such as the program tifa build makes or a Node server, so that the system ends them when the test process ends, however it ends.
Package testproc starts the programs that tests run in the background, such as the program tifa build makes or a Node server, so that the system ends them when the test process ends, however it ends.
testproc/orphantest
Package orphantest checks that a program a test starts does not outlive the test process.
Package orphantest checks that a program a test starts does not outlive the test process.
Package js holds the JavaScript runtime sources of tifa.
Package js holds the JavaScript runtime sources of tifa.
Package server is the tifa runtime.
Package server is the tifa runtime.
Package skills holds the agent skill that Tifa ships, so `tifa agents` can write the copy that belongs to the Tifa version it was built from.
Package skills holds the agent skill that Tifa ships, so `tifa agents` can write the copy that belongs to the Tifa version it was built from.
test
compare
Package compare builds the workbench pages of examples/shop three ways, as tifa, as a Next.js app and as a TanStack Start app, checks that the three show the same text, and measures how many whole page requests each answers.
Package compare builds the workbench pages of examples/shop three ways, as tifa, as a Next.js app and as a TanStack Start app, checks that the three show the same text, and measures how many whole page requests each answers.
compare/cmd/compare command
Command compare builds, measures and reports the comparison of Tifa with Next.js, TanStack Start, on the six workbench pages of examples/shop.
Command compare builds, measures and reports the comparison of Tifa with Next.js, TanStack Start, on the six workbench pages of examples/shop.
ssr/cg
Package cg lets a program tell callgrind where to count: it zeroes the counters and writes a dump on request, so one process can count each stage of its work apart.
Package cg lets a program tell callgrind where to count: it zeroes the counters and writes a dump on request, so one process can count each stage of its work apart.
Package tifatest tests a tifa app in go test, in two ways.
Package tifatest tests a tifa app in go test, in two ways.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL