Skip to content
Gx
GitHub

Routing

Route types, query values, typed links, layouts, errors and navigation.

A route is a Go struct type. It embeds gx.Route, and its tag holds the method and the pattern. The pattern uses the syntax of the Go ServeMux.

A route type lives in the route package of its slice. That package holds only route types, so each slice can link to each other slice with no import cycle.

gx new slice shop

Path and query values

A path variable binds to the field with the same name. A query field has a query tag and can have a default tag.

shop/route/route.go
// Package route holds the route types of the shop slice. A route
// package holds only route types.
package route

import "github.com/alternayte/gx"

// Index is the list of products. Sort and Page come from the query.
type Index struct {
	gx.Route `GET /shop`
	Sort     string `query:"sort" default:"name"`
	Page     int    `query:"page" default:"1"`
}

A query value of the wrong type, such as ?page=two, answers 400. The loader does not run.

A default applies when the request has no value for the field. A value in the request stays, also when it is the zero value: ?page=0 binds 0.

GET / matches each path that no other pattern matches. Write GET /{$} for the root path only, as the home page of a new app does.

Pages

gx.Page(load, view) joins a loader and a view. The loader is func(*gx.Ctx, In) (Props, error). The view is the component function.

shop/shop.go
// Package shop is the shop slice: its pages, actions and views.
package shop

import (
	"github.com/alternayte/gx"
	"acme/shop/route"
)

// IndexPage is the list of products.
var IndexPage = gx.Page(func(c *gx.Ctx, in route.Index) (IndexViewProps, error) {
	if in.Page < 1 {
		return IndexViewProps{}, gx.NotFound()
	}
	return IndexViewProps{Sort: in.Sort, Page: in.Page}, nil
}, IndexView)

// Routes lists every page, action and form of the slice.
var Routes = gx.Collect(IndexPage)

A loader returns gx.NotFound(), gx.Forbidden() or gx.Redirect(route) to stop with a status.

href takes a static string, a value of a GET route type, or a gx.URL value. Gx escapes the path values and encodes the query. It omits a query value that is equal to its default.

active="section" marks a link when the current path starts with the link path. A link to the exact current page gets aria-current="page".

shop/IndexView.gx
package shop

import "acme/shop/route"

props {
  // Sort is the sort key.
  Sort string
  // Page is the page number.
  Page int
}

<gx.Head title="Shop" />
<nav class="flex gap-3 text-sm">
  <a href={route.Index{}}>By name</a>
  <a href={route.Index{Sort: "price"}}>By price</a>
  <a href={route.Index{Sort: "price", Page: 2}}>Page 2</a>
</nav>
<p class="mt-4">Sorted by {p.Sort}, page {p.Page}.</p>
Shop /shop?sort=price The page of the sample app

Mount

Mounting is explicit. gx.Collect lists the pages, actions and forms of a slice. Group mounts lists under a prefix, with layouts and middleware. A value that no gx.Collect holds is the diagnostic GX3003.

Middleware is func(http.Handler) http.Handler. It applies to the lists that follow it in the same call.

cmd/app/main.go
// Command app serves the acme app.
package main

import (
	"log"
	"net/http"
	"os"

	"github.com/alternayte/gx"
	"github.com/alternayte/gx/adapters/datastar"
	"acme/app"
	"acme/gxislands"
	"acme/gxstyles"
	"acme/home"
	"acme/shop"
)

// noStore is plain net/http middleware.
func noStore(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Cache-Control", "no-store")
		next.ServeHTTP(w, r)
	})
}

func main() {
	setupGallery()
	gx.SetStylesheet(gxstyles.CSS())
	gx.SetIslands(gxislands.Bundle())
	server := gx.New(gx.Config{Adapter: datastar.Adapter()})
	server.Group("/", app.Layout, gx.Nav(gx.MorphNavigation), noStore, home.Routes, shop.Routes)

	addr := os.Getenv("GX_DEV_ADDR")
	if addr == "" {
		addr = "127.0.0.1:8080"
	}
	log.Printf("acme listens on http://%s", addr)
	log.Fatal(http.ListenAndServe(addr, server))
}

Layouts

A layout is a component with a Children prop, plus an optional loader. The layout loader and the page loader run at the same time. gx.Once(c, fn) runs fn one time for each request, so a layout and a page can share one query.

app/layout.go
// Package app holds the layout and the theme of the app.
package app

import "github.com/alternayte/gx"

// Layout wraps every page in the shell. The loader gets the name of the
// reader.
var Layout = gx.Layout(func(c *gx.Ctx) (string, error) {
	return gx.Once(c, func() (string, error) { return "Ada", nil })
}, func(user string, children gx.Node) gx.Node {
	return Shell(ShellProps{User: user, Children: children})
})
app/Shell.gx
package app

import (
  homeroute "acme/home/route"
  shoproute "acme/shop/route"
)

props {
  // User is the name of the reader.
  User string
  // Children is the page.
  Children gx.Node
}

<gx.Head title="Acme" bodyClass="bg-background text-foreground" />
<header class="border-b border-border">
  <nav class="mx-auto flex max-w-3xl items-center gap-4 p-4 text-sm">
    <a href={homeroute.Home{}} class="font-semibold">Acme</a>
    <a href={shoproute.Index{}} active="section">Shop</a>
    <span class="ml-auto text-muted-foreground">{p.User}</span>
  </nav>
</header>
<main class="mx-auto max-w-3xl p-4">{p.Children}</main>

<gx.Head> sets the title, the meta tags and the link tags. The title of the page replaces the title of the layout.

A link of a page and a link of a layout merge when they have the same rel and href. A canonical link and a manifest link merge by rel only, because a page has one of each. Thus a layout and a page can each add a preload link.

A gx.Link also has As, Type and CrossOrigin. A font preload is gx.Link{Rel: "preload", Href: "/fonts/a.woff2", As: "font", Type: "font/woff2", CrossOrigin: "anonymous"}. A morph navigation merges the links of the new page with the same rule.

Shop /shop The page of the sample app

With gx.Nav(gx.MorphNavigation), a click between two pages with a shared layout fetches only the part inside that layout. The layout elements stay in the page. The title and the address change, and the back button works.

With no JavaScript, a link is a full load. Between two pages with no shared layout, the server answers with the header Gx-Nav: full and no body. The runtime then loads the page one time.

Each layout slot carries a hash of its layout, with the slot left out. The runtime sends the hashes back with the request. When the data of a kept layout changed, for example a badge in the header, the server answers with one morph of the whole body. The morph keeps the elements that did not change, with their focus and their state. When each kept layout has the same hash, the answer is the patch of the slot only. The hash leaves out the CSP nonce and the active link marks, so equal data gives an equal hash.

A navigation that takes more than 100 ms sets aria-busy="true" on the clicked link and on the html element. The mark goes when the new page is in, or when the navigation fails. A new click takes the mark of the earlier one. Use the mark to show progress with CSS, for example html[aria-busy="true"] { cursor: progress; }.

A new page can have a component that the old page did not have, for example tabs or a dialog. After the navigation, the runtime loads the module of that component, so the component works with no full load. A patch of an action that brings such a component loads its module too.

A page with a layout slot loads the module nav.js after gx.js. Its Link header names the module, so the browser gets it with no extra round trip. A page with no layout slot does not load it.

A new click cancels the navigation in flight. Only the newest navigation changes the page and the address.

When the server redirects a morph navigation, the runtime loads the page that answered in full. That page can have a different layout. The fragment of the link stays.

An error of a loader, such as gx.NotFound(), puts the error component of the status into the slot. The layout stays, and the address changes to the link. The answer has the status of the error. A panic in a loader or in a view of the page does the same with status 500 and the serverError component. The loader runs one time. A status with no error component loads the page in full.

When the network fails, the page stays and an error toast shows. The text is the message of the key gx.nav_failed. A page with no toaster loads the link in full, so the browser shows its error page.

A link to the page of now, with no hash, refreshes the page with one morph navigation. It adds no history entry. A link that differs from the page of now only in its hash keeps the default of the browser.

A GET form of the same site submits as a morph navigation, for example a search form. The address becomes the action of the form with the fields as the query, such as /journal?q=tea. The name and the value of the submit button go into the query too. A form with data-gx-nav="off" submits with a full load. A Gx form, with data-gx-form, submits through the adapter.

Back and Forward

Before a navigation replaces a page, the runtime keeps a copy of it in memory. It keeps the last 10 pages. Back and Forward show the copy at once, at its scroll position. The runtime then loads the page from the server and morphs the answer into the copy.

The runtime keeps no copy of a page whose answer has Cache-Control: no-store. Set the header in the loader, for example c.W.Header().Set("Cache-Control", "no-store"), for a page that must not show old data. Back then waits for the server. A write request, for example a form submit or a POST action, clears all kept copies.

Scroll and focus

A new page shows at the top. When the URL has a hash, for example /docs#install, the page shows at the element with that id. Back and Forward show each page at the scroll position that it had.

After a navigation, focus goes to the element with the attribute data-gx-focus. When the page has no such element, focus goes to the first h1. The runtime gives that element tabindex="-1" when it cannot take focus. A polite live region then reads the title of the new page, so a screen reader user hears the change.

To keep focus where it is, add gx.KeepFocus to the navigation mode: gx.Nav(gx.MorphNavigation, gx.KeepFocus).

With gx.KeepFocus, the live region reads nothing.

Prefetch

A link can load its page before the click. The click then uses that answer and does not wait for the server. Set the mode of the app with gx.Prefetch, for example gx.Nav(gx.MorphNavigation, gx.Prefetch(gx.PrefetchHover)).

  • gx.PrefetchHover loads the page 100 ms after the pointer or the focus comes to the link, or after a touch on the link.
  • gx.PrefetchViewport loads the page when the link comes into the viewport.
  • gx.PrefetchNone loads the page on the click only. It is the default.

The attribute data-gx-prefetch on a link sets the mode of that link. It overrides the mode of the app. Its values are hover, viewport and none, for example <a href={route.Settings{}} data-gx-prefetch="hover">.

A prefetch sends the request of a navigation with the header Gx-Prefetch: 1. Your handler can read the header to skip work or to count prefetches. The runtime keeps each answer for 10 seconds. It uses an answer only when the layouts of the page are the same as at the prefetch. A write request, for example a form submit or a POST action, clears all kept answers.

The runtime does not prefetch when the browser asks to save data. It does not prefetch a link to a different origin, or a link that a morph navigation does not take. A link with target, download or data-gx-nav="off" is such a link.

Error pages

server.Errors(notFound, forbidden, serverError) sets a component for each status. Each one is func(*gx.Ctx) gx.Node.

A panic in a loader or in a view gives status 500 and the serverError component. The server writes the panic and its stack to the log. The browser gets no part of the broken page. In gx dev, the overlay shows the panic.

ETag

A GET page has an ETag header from the bytes of the page. A request with the same tag gets status 304 and no body. The loaders and the render run for each request; the tag saves the transfer.

When your code sets no Cache-Control header, the page has Cache-Control: private, no-cache. The browser then asks each time, and a shared cache keeps no page of a user.

A page with a CSP nonce has no tag. Status 304 pairs the page of before with a new nonce, and the browser then refuses each script. A partial navigation, an answer of an action and a widget have no tag.

Early hints

Each page names its stylesheet and its scripts in Link headers. A CDN can send these headers as early hints. Over HTTP/2, the app also sends status 103 with the Link values of the last answer of the route. The browser then gets the files while the loaders run. You set nothing for this.

A page with a CSP nonce names only its stylesheet, because a strict policy refuses a script preload that has no nonce.

Caching and compression

The app serves the scripts of the runtime below /_gx/v/<hash>/, for example /_gx/v/3f2a9c1d0b7e/gx.js. One hash covers all the scripts of the runtime. The answer has Cache-Control: public, max-age=31536000, immutable, so the browser keeps the file for one year. A new build with a changed script has a new hash, and each page names the new URL.

The app stylesheet is /_gx/app.<hash>.css, with the same cache rule. The stylesheet of a route works the same way.

A hash of a different build gets the file of this build with Cache-Control: no-cache, not status 404. In a rolling deploy, a page of a new replica can ask an old replica for its files. An open page can also load a script below the hash of its first load. The stylesheet of a route with an unknown name gets the app stylesheet.

The old URLs, such as /_gx/gx.js and /_gx/app.css, stay. A widget host can name them, and a page in a cache can name them too. They have Cache-Control: no-cache and an ETag, so the browser asks each time and gets status 304 when it has the file.

A public file of Config.Public has no hash in its name. It has an ETag of its content and Cache-Control: public, no-cache. A request with the same tag gets status 304.

The app compresses HTML, event streams, JavaScript, CSS, JSON and SVG. It uses brotli when the browser accepts it, and gzip in the other case. The scripts of the runtime are compressed one time, when the app starts. An event stream sends each frame at once, so a patch does not wait in the compressor.

The app does not compress an answer under 1 KB, or an answer that has a Content-Encoding header. A compressed page has the weak form of its ETag. Set gx.Config{DisableCompression: true} when a proxy in front of the app compresses.

Use Gx with an existing router

Gx is plain net/http. Adopt it one level at a time.

Level What you write
1. One component gx.Render(w, r, node) in any handler.
2. One route mux.Handle(route.Index{}.Pattern(), shop.IndexPage). Each page, action and form is an http.Handler.
3. One mounted app Mount a gx.App under a prefix and set Config.BasePath. Each link then starts with the prefix.
4. The whole app gx.New and Group, as above.
legacy/legacy.go
// Package legacy shows Gx inside handlers that do not use gx.App.
package legacy

import (
	"net/http"

	"github.com/alternayte/gx"
	"acme/shop"
	"acme/shop/route"
)

// Banner renders one component in a plain handler (level 1).
func Banner(w http.ResponseWriter, r *http.Request) {
	_ = gx.Render(w, r, shop.IndexView(shop.IndexViewProps{Sort: "name", Page: 1}))
}

// Mount adds one Gx page to a standard mux (level 2).
func Mount(mux *http.ServeMux) {
	mux.Handle(route.Index{}.Pattern(), shop.IndexPage)
}

A router that does not fill r.PathValue needs gx.Params, which tells Gx how to read a path value.

List the routes

gx routes
gx routes --json