router

package
v4.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 29, 2026 License: MIT Imports: 9 Imported by: 0

README

GWC | Router Library

GoWebComponents (GWC)

High-Level Overview

The router library provides client-side routing, route matching, navigation, and loader orchestration for GWC single-page apps.

Public APIs

github.com/monstercameron/GoWebComponents/router (package router)
  • Functions: AllowNavigation, BlockNavigation, Bool, Current, DefineRoute, Delete, Encode, Get, GetCurrentPath, GetCurrentRouterPath, GetOutlet, GetRoute, GetRouter, GoGetRoute, GoRegisterRoute, Has, Href, HrefFor, HydrateMount, HydrateMountElement, InspectCurrentRoute, Int, IsLoading, Loading, MetadataNode, Mount, MountElement, MustDefineRoute, MustHref, MustHrefFor, MustPath, MustPathFor, Navigate, NavigateReplace, NewHashRouter, NewHistoryRouter, ParamNames, Path, PathFor, Pattern, PreserveReturnTo, ReadReturnTo, RedirectNavigation, Register, RegisterRoute, Replace, ReplaceAll, Revalidate, RouteWithElement, Set, UseNavigate, UseParams, UseQuery, UseRevalidator, UseRouteData, UseSearchParams, Values
  • Types: AsyncGuardFunc, AsyncLeaveGuardFunc, Attrs, Component, Element, GuardDecision, GuardFunc, GuardResult, LeaveGuardFunc, LoaderFunc, Metadata, Navigator, Options, Params, Query, Revalidator, RouteContext, RouteContract, RouteInspection, RouteLoaderInspection, RouteParamsProvider, RouteQueryProvider, RouteRedirectInspection, RouteStackInspection, Router, RouterOptions, SearchParams
  • Variables: none
  • Constants: ReturnToParam

Subfiles And Purpose

  • browser_router_test.go - Tests for browser_router behavior
  • browser_test_helpers_wasm_test.go - Tests for browser_test_helpers_wasm behavior
  • contracts.go - Core implementation for contracts
  • contracts_additional_test.go - Tests for contracts_additional behavior
  • contracts_test.go - Tests for contracts behavior
  • doc.go - Package-level Go documentation
  • example_test.go - Tests for example behavior
  • metadata.go - Core implementation for metadata
  • metadata_test.go - Tests for metadata behavior
  • README.md - Folder-level documentation
  • router.go - Core implementation for router
  • router_benchmark_test.go - Tests for router_benchmark behavior
  • router_test.go - Tests for router behavior

File Map

router/
|-- browser_router_test.go
|-- browser_test_helpers_wasm_test.go
|-- contracts.go
|-- contracts_additional_test.go
|-- contracts_test.go
|-- doc.go
|-- example_test.go
|-- metadata.go
|-- metadata_test.go
|-- README.md
|-- router.go
|-- router_benchmark_test.go
\-- router_test.go

Documentation

Overview

Package router provides client-side routing for single-page applications built with GoWebComponents.

This package implements hash-based and history-based routing with support for:

  • Multiple router instances
  • Browser history integration
  • Programmatic navigation
  • Nested layout routes with explicit outlets
  • Static node and component route registration
  • Route-level chunk gates for lazy route artifacts

Basic usage with hash routing:

import (
    "github.com/monstercameron/GoWebComponents/v4/html"
    "github.com/monstercameron/GoWebComponents/v4/router"
    "github.com/monstercameron/GoWebComponents/v4/ui"
)

func main() {
    r := router.NewHashRouter()

    r.Register("/", HomePage)
    r.Register("/about", AboutPage)
    r.Register("/contact", ContactPage)
    r.Register("*", NotFoundPage)

    r.Mount("#app")
}

Route components are regular components:

func HomePage(props router.Attrs) *router.Element {
    goAbout := ui.UseEvent(func() {
        router.Navigate("/about")
    })

    return html.Div(html.Props{},
        html.H1(html.Props{}, html.Text("Welcome Home")),
        html.Button(html.Props{OnClick: goAbout}, html.Text("Go to About")),
    )
}

The package supports both hash-based routing (using URL fragments like #/about) and history-based routing (using the HTML5 History API).

Convenience accessors are also available for routed components:

nav := router.UseNavigate()
nav.Navigate("/about")

query := router.UseQuery()
searchTerm := query.Get("q")

params := router.UseParams()
userID := params.Get("id")
id, ok := params.Int("id")

revalidator := router.UseRevalidator()
revalidator.Revalidate()

layout := router.GetOutlet()

Parent layout routes opt in with router.Options{Layout: true} and render the active child route through router.GetOutlet().

Routes can also define async loaders that provide route-scoped data before rendering the final page component:

r.Register("/users/:id", UserProfile, router.Options{
    Loader: func(ctx context.Context, routeCtx router.RouteContext) (router.Attrs, error) {
        return router.Attrs{"userID": routeCtx.Params.Get("id")}, nil
    },
})

Use RegisterLazy with RouteChunk when route code or a route-owned script must load before the route component and loader run.

Index

Examples

Constants

View Source
const (
	ReturnToParam = "return_to"
)

Variables

This section is empty.

Functions

func BuildMetadataNode

func BuildMetadataNode(parseRouterMetadata Metadata) *runtime.Element

BuildMetadataNode renders route-managed metadata as SSR-safe head children.

The generated tags are marked so the client router can reconcile and clean up only framework-owned metadata during hydration and later navigations.

func BuildRouteService

func BuildRouteService() pluginruntime.RouteService

BuildRouteService returns one router-backed route service.

func DecodeQuery

func DecodeQuery[T any](parseValues url.Values) (T, error)

DecodeQuery decodes URL query values into a typed struct T using `query:"name"` tags (falling back to the lowercased field name), then validates the result with the validate package using any `validate:"..."` tags on the same struct. It is the typed-search-params path: read `?page=2&sort=desc` into a struct once, with conversion and validation, instead of scattering `q.Get("page")` + manual strconv + bounds checks across the codebase.

Supported field kinds: string, bool, the sized int/uint kinds, float32/64, and []string (for repeated params). A missing param leaves the field at its zero value — mark it `validate:"required"` to reject that. A malformed value (e.g. page=abc for an int) or an unsupported field kind returns an error; validation failures return the validate.Result (which implements error and carries per-field messages).

type ListQuery struct {
    Page int    `query:"page" validate:"gte=1"`
    Sort string `query:"sort" validate:"omitempty,oneof=asc desc"`
    Tags []string `query:"tag"`
}
q, err := router.DecodeQuery[ListQuery](values) // err is a validate.Result on bad input

func EncodeQuery

func EncodeQuery(parseValue any) url.Values

EncodeQuery renders a typed struct (or a non-nil pointer to one) back into url.Values using the same `query:"name"` tags, skipping zero-valued fields so the resulting URL stays clean. It is the inverse of DecodeQuery, for building links and updating the address bar from typed state. By contract it takes a struct: a non-struct, nil pointer, or other value has no query fields and returns an empty url.Values (it never panics) — DecodeQuery is the validated counterpart, so encoding stays intentionally permissive.

func FragmentHref

func FragmentHref(parseFragment string) string

FragmentHref returns an in-page anchor href (e.g. a "skip to content" link) that is safe under a <base href> (G7). With a <base href> a bare "#main" resolves against the base (navigating to root); embedding the live path keeps the anchor in-page. It returns "<current-path>#<fragment>".

This targets history routers, where the <base href> footgun exists. Hash routers keep the whole route in the URL fragment, so a second in-page fragment cannot be expressed as an href (use programmatic scrolling instead); to avoid a malformed "#path#fragment", FragmentHref does NOT add the hash-router prefix.

The current query string is preserved (e.g. "/list?page=2#main"), so clicking the anchor stays on the exact current location rather than dropping query state.

A(html.Href(router.FragmentHref("main")), "Skip to content")

func GetCurrentPath

func GetCurrentPath() string

GetCurrentPath returns the current route path from the global router.

func Href

func Href(parsePath string) string

Href returns the correct href attribute value for navigating to path under the active router mode (G7). For a hash router it returns "#<path>"; for a history router it returns the normalized path (which the browser resolves against any <base href>). Use it instead of hand-building href strings so links work regardless of router mode or base href.

A(Href(router.Href("/transactions")), "Transactions")
func Navigate(parsePath string)

Navigate updates the URL using the appropriate method for the current router.

Example
package main

import (
	"github.com/monstercameron/GoWebComponents/v4/router"
)

func main() {
	// Navigate to a new path
	// This works with both hash and history routers
	router.Navigate("/about")
}
func NavigateReplace(parsePath string)

NavigateReplace replaces the current history entry using the appropriate method for the current router.

func OnNavigate

func OnNavigate(parseFn func(Location)) func()

OnNavigate registers fn to run after each navigation with the new Location — the seam for SPA scroll-reset, analytics page views, and title side effects (G28). It returns an unsubscribe func.

Firing semantics: fn runs once on the initial render (the first location is a change from "none", so analytics see the landing page view), then once per subsequent navigation. It does NOT fire when the location is unchanged (a re-render at the same path+query is deduped). Register before mounting if you need the initial fire.

stop := router.OnNavigate(func(loc router.Location) { scrollTop() })
defer stop()

func PreserveReturnTo

func PreserveReturnTo(parsePath string, parseQuery url.Values) string

PreserveReturnTo normalizes an internal path plus query values into a bounded return-target payload suitable for auth or re-auth redirects.

func ReadReturnTo

func ReadReturnTo(parseQuery url.Values, parseFallback string) string

ReadReturnTo reads an internal return-target query value and falls back when the value is empty, oversized, or external.

func RegisterElementRoute

func RegisterElementRoute(parsePath string, parseElemRef js.Value)

RegisterElementRoute renders a route directly to a DOM element and sets up hash listening.

func RegisterLazyRoute

func RegisterLazyRoute(parsePath string, parseComponent interface{}, parseChunk RouteChunk, parseOptions ...Options)

RegisterLazyRoute registers a route on the global router with a route chunk.

func RegisterRoute

func RegisterRoute(parsePath string, parseComponent interface{}, parseOptions ...Options)

RegisterRoute registers a route with the global router.

func RegisteredRoutes

func RegisteredRoutes() []string

RegisteredRoutes returns a sorted, de-duplicated slice of all registered route path strings from the global router. It delegates to GetRouter().RegisteredRoutes() and returns a non-nil empty slice when no routes are registered or the global router is nil.

func RetryLoader

func RetryLoader(parseKey string) error

RetryLoader clears one loader entry by key and re-runs the current route render.

func Revalidate

func Revalidate()

Revalidate clears the current route loader result and runs the route again.

Types

type AsyncGuardFunc

type AsyncGuardFunc func(context.Context, RouteContext) GuardDecision

AsyncGuardFunc decides whether navigation into a route should proceed.

type AsyncLeaveGuardFunc

type AsyncLeaveGuardFunc func(context.Context, RouteContext, RouteContext) GuardDecision

AsyncLeaveGuardFunc decides whether navigation away from a route should proceed.

type Attrs

type Attrs = map[string]interface{}

Component is a type alias for component functions used in routing.

func UseRouteData

func UseRouteData() Attrs

UseRouteData returns loader-provided route data for the current matched route.

type Component

type Component = func(Attrs) *Element

type Element

type Element = runtime.Element

func GetOutlet deprecated

func GetOutlet() *Element

GetOutlet returns the child route element for the current layout route, if one exists.

Deprecated: use UseOutlet, which follows the package's Use* accessor convention.

func GetRoute

func GetRoute() *Element

GetRoute returns the component for the current route as an Element.

func UseOutlet

func UseOutlet() *Element

UseOutlet returns the child route element for the current layout route, if one exists. It follows the Use* hook-accessor naming used by the rest of this package.

type GuardDecision

type GuardDecision struct {
	Redirect  string
	Blocked   bool
	Reason    string
	Retryable bool
	Denied    bool
}

GuardDecision describes the outcome of an async navigation guard.

type GuardFunc

type GuardFunc func(RouteContext) GuardResult

GuardFunc decides whether navigation into a route should proceed.

type GuardResult

type GuardResult struct {
	Redirect string
	Blocked  bool
	Reason   string
}

GuardResult describes the outcome of a navigation guard.

func AllowNavigation

func AllowNavigation() GuardResult

AllowNavigation permits the pending navigation.

func BlockNavigation

func BlockNavigation(parseReason string) GuardResult

BlockNavigation blocks the pending navigation with a reason.

func RedirectNavigation

func RedirectNavigation(parsePath string) GuardResult

RedirectNavigation redirects the pending navigation to path.

type LeaveGuardFunc

type LeaveGuardFunc func(current RouteContext, next RouteContext) GuardResult

LeaveGuardFunc decides whether navigation away from a route should proceed.

type LoaderFunc

type LoaderFunc func(context.Context, RouteContext) (Attrs, error)

type Location

type Location struct {
	// Path is the current logical route path (no query string).
	Path string
	// Query is the encoded query string (without the leading '?').
	Query string
	// Params are the params captured by the matched route pattern.
	Params map[string]string
}

Location is a snapshot of the active route used by the reactive UseRoute / UseLocation hooks (G6). Unlike InspectCurrentRoute (a non-reactive read), a component that calls UseRoute subscribes to navigation and re-renders when the location changes — so memoized chrome (active-nav highlight, breadcrumb) stays in sync without threading the path down as a prop.

func UseLocation

func UseLocation() Location

UseLocation is an alias for UseRoute, matching the naming many router users expect.

func UseRoute

func UseRoute() Location

UseRoute subscribes the calling component to navigation and returns the active Location. When the route changes, every component that called UseRoute re-renders — including memoized chrome — so the active-nav highlight and breadcrumb update without prop-drilling the path (G6).

func Sidebar(_ SidebarProps) ui.Node {
    loc := router.UseRoute()
    // highlight the link whose href == loc.Path
}

func (Location) Param

func (parseLoc Location) Param(parseKey string) string

Param returns the captured route param for key, or "" if absent.

type Metadata

type Metadata struct {
	Title        string
	Description  string
	CanonicalURL string
}

Metadata describes the route-owned metadata currently supported by the router.

These fields are intentionally narrow for the first SSR-aware metadata slice: title, description, and canonical URL. Broader head management remains a separate future concern.

type Navigator struct {
	// contains filtered or unexported fields
}

Navigator provides push and replace navigation helpers.

func UseNavigate

func UseNavigate() Navigator

UseNavigate returns a typed navigation handle for the global router.

func (parseN Navigator) Navigate(parsePath string)

Navigate pushes a new route onto the history stack.

func (parseN Navigator) Replace(parsePath string)

Replace replaces the current route entry.

type Options

type Options struct {
	Title            string
	Redirect         string
	Description      string
	CanonicalURL     string
	Layout           bool
	Chunk            RouteChunk
	BeforeEnter      GuardFunc
	BeforeLeave      LeaveGuardFunc
	BeforeEnterAsync AsyncGuardFunc
	BeforeLeaveAsync AsyncLeaveGuardFunc
	GuardPending     interface{}
	Unauthorized     interface{}
	Authorizing      interface{}
	Loader           LoaderFunc
	Loading          interface{}
	Error            interface{}
}

Options represents configuration for individual routes. Placeholder for future per-route settings (e.g., titles, guards).

type Params

type Params struct {
	// contains filtered or unexported fields
}

Params provides read-only access to matched route params.

func UseParams

func UseParams() Params

UseParams returns the params captured by the current matched route pattern.

func (Params) Bool

func (parseP Params) Bool(parseKey string) (bool, bool)

Bool parses the route param for key as a bool.

func (Params) Get

func (parseP Params) Get(parseKey string) string

Get returns the captured route param for key or an empty string.

func (Params) Has

func (parseP Params) Has(parseKey string) bool

Has reports whether the route param key exists.

func (Params) Int

func (parseP Params) Int(parseKey string) (int, bool)

Int parses the route param for key as an int.

func (Params) Values

func (parseP Params) Values() map[string]string

Values returns a copy of the current route params.

type Query

type Query struct {
	// contains filtered or unexported fields
}

Query provides read-only access to parsed query values.

func UseQuery

func UseQuery() Query

UseQuery returns the current URL query values.

For hash routers it reads the `?` portion after the hash path, for example `#/search?q=golang`. For history routers it also supports `window.location.search`.

func (Query) Bool

func (parseQ Query) Bool(parseKey string) (bool, bool)

Bool parses the query value for key as a bool; ok is false when the key is absent or unparseable.

func (Query) Encode

func (parseQ Query) Encode() string

Encode serializes the current query values using net/url encoding.

func (Query) Get

func (parseQ Query) Get(parseKey string) string

Get returns the first value for a query key or an empty string.

func (Query) Has

func (parseQ Query) Has(parseKey string) bool

Has reports whether a query key is present.

func (Query) Int

func (parseQ Query) Int(parseKey string) (int, bool)

Int parses the query value for key as an int; ok is false when the key is absent or unparseable. Mirrors Params.Int so route params and query params read the same way.

func (Query) Values

func (parseQ Query) Values() url.Values

Values returns a copy of the parsed query values.

type Revalidator

type Revalidator struct {
	// contains filtered or unexported fields
}

Revalidator exposes route-loader revalidation and loading state.

func UseRevalidator

func UseRevalidator() Revalidator

UseRevalidator returns a handle for manually revalidating the current route loader.

func (Revalidator) Loading

func (parseR Revalidator) Loading() bool

Loading reports whether the current route loader is still pending.

func (Revalidator) Revalidate

func (parseR Revalidator) Revalidate()

Revalidate forces the current route loader to run again.

type RouteChunk

type RouteChunk struct {
	ID      string
	Scripts []string
	Loader  RouteChunkLoader
	Loading interface{}
	Error   interface{}
}

RouteChunk describes a lazy route artifact. Apps can provide Loader for custom wasm/module bootstrapping, or Scripts for the default browser loader.

type RouteChunkLoader

type RouteChunkLoader func(context.Context, RouteContext) error

RouteChunkLoader loads one route-level code artifact before the route factory is invoked.

type RouteContext

type RouteContext struct {
	Path   string
	Params Params
	Query  Query
}

RouteContext describes the path, params, and query for a route evaluation.

type RouteContract

type RouteContract struct {
	// contains filtered or unexported fields
}

RouteContract stores a validated route pattern together with reverse-routing helpers.

The zero value is NOT valid: Path() and Href() on an uninitialized RouteContract return a "route contract is not initialized" error. Always construct one with DefineRoute (returns an error) or MustDefineRoute (panics on a bad pattern).

func DefineRoute

func DefineRoute(parsePattern string) (RouteContract, error)

DefineRoute validates a route pattern and returns a reusable reverse-routing contract.

Example

ExampleDefineRoute shows declaring a typed route contract, which validates the pattern up front and lets the app build type-safe hrefs for the route.

package main

import (
	"github.com/monstercameron/GoWebComponents/v4/router"
)

func main() {
	parseUserRoute := router.MustDefineRoute("/users/:id")
	// parseUserRoute.Path(...) builds a concrete URL for the :id parameter.
	_ = parseUserRoute
}

func MustDefineRoute

func MustDefineRoute(parsePattern string) RouteContract

MustDefineRoute validates a route pattern and panics if it is invalid.

func (RouteContract) Href

func (parseC RouteContract) Href(parseParams map[string]string, parseQuery url.Values) (string, error)

Href builds a validated navigation target for the contract from raw params and query values.

func (RouteContract) HrefFor

func (parseC RouteContract) HrefFor(parseParams RouteParamsProvider, parseQuery RouteQueryProvider) (string, error)

HrefFor builds a validated navigation target from typed param and query providers.

func (RouteContract) MustHref

func (parseC RouteContract) MustHref(parseParams map[string]string, parseQuery url.Values) string

MustHref builds a navigation target and panics if params do not satisfy the contract.

func (RouteContract) MustHrefFor

func (parseC RouteContract) MustHrefFor(parseParams RouteParamsProvider, parseQuery RouteQueryProvider) string

MustHrefFor builds a navigation target from typed param and query providers and panics on validation failure.

func (RouteContract) MustPath

func (parseC RouteContract) MustPath(parseParams map[string]string) string

MustPath builds a path and panics if params do not satisfy the contract.

func (RouteContract) MustPathFor

func (parseC RouteContract) MustPathFor(parseParams RouteParamsProvider) string

MustPathFor builds a path from a typed param provider and panics if the contract fails validation.

func (RouteContract) ParamNames

func (parseC RouteContract) ParamNames() []string

ParamNames returns the ordered param names required by the contract.

func (RouteContract) Path

func (parseC RouteContract) Path(parseParams map[string]string) (string, error)

Path builds a validated path for the contract from raw param values.

func (RouteContract) PathFor

func (parseC RouteContract) PathFor(parseParams RouteParamsProvider) (string, error)

PathFor builds a validated path from a typed param provider.

func (RouteContract) Pattern

func (parseC RouteContract) Pattern() string

Pattern returns the normalized route pattern used by the contract.

type RouteInspection

type RouteInspection struct {
	Path         string
	Query        url.Values
	Params       map[string]string
	Loading      bool
	Stack        []RouteStackInspection
	Loaders      []RouteLoaderInspection
	LastRedirect RouteRedirectInspection
	Metadata     Metadata
}

RouteInspection summarizes the currently active route.

func InspectCurrentRoute

func InspectCurrentRoute() RouteInspection

InspectCurrentRoute returns the current path, query, params, and loading state.

type RouteLoaderInspection

type RouteLoaderInspection struct {
	Key     string
	Path    string
	Pending bool
	HasData bool
	Error   string
}

type RouteParamsProvider

type RouteParamsProvider interface {
	RouteParams() map[string]string
}

RouteParamsProvider exposes typed route params for reverse routing helpers.

type RouteQueryProvider

type RouteQueryProvider interface {
	RouteQuery() url.Values
}

RouteQueryProvider exposes typed query values for reverse routing helpers.

type RouteRedirectInspection

type RouteRedirectInspection struct {
	Cause string
	From  string
	To    string
}

type RouteStackInspection

type RouteStackInspection struct {
	ID             string
	Path           string
	Params         map[string]string
	HasLoader      bool
	HasBeforeEnter bool
	HasBeforeLeave bool
	Metadata       Metadata
}

type Router

type Router struct {
	// contains filtered or unexported fields
}

Router manages routes and navigation for single-page applications.

func GetRouter

func GetRouter() *Router

GetRouter returns the global router instance.

func NewHashRouter

func NewHashRouter(parseOptions ...RouterOptions) *Router

NewHashRouter creates a hash-based router that reads from window.location.hash.

Example
package main

import (
	"github.com/monstercameron/GoWebComponents/v4/html"
	"github.com/monstercameron/GoWebComponents/v4/router"
)

func main() {
	// Create a new hash-based router
	parseR := router.NewHashRouter()

	// Define page components
	parseHomePage := func(parseProps router.Attrs) *router.Element {
		return html.Div(html.Props{}, html.H1(html.Props{}, html.Text("Home")))
	}

	parseAboutPage := func(parseProps2 router.Attrs) *router.Element {
		return html.Div(html.Props{}, html.H1(html.Props{}, html.Text("About")))
	}

	// Register routes
	parseR.GoRegisterRoute("/", parseHomePage)
	parseR.GoRegisterRoute("/about", parseAboutPage)

	// In a real app, you would mount the router to the DOM
	// r.Mount("#app")
}

func NewHistoryRouter

func NewHistoryRouter(parseOptions ...RouterOptions) *Router

NewHistoryRouter creates a history-based router using the HTML5 History API. This router uses window.location.pathname instead of hash fragments. Requires server to redirect all routes to the app's entry point.

func (*Router) Current

func (parseR *Router) Current() *Element

Current returns the current route element.

func (*Router) GetCurrentPath

func (parseR *Router) GetCurrentPath() string

GetCurrentPath returns the current route path from this router instance. It mirrors the package-level GetCurrentPath and is the preferred name over GetCurrentRouterPath.

func (*Router) GetCurrentRouterPath deprecated

func (parseR *Router) GetCurrentRouterPath() string

GetCurrentRouterPath returns the current path from a router instance based on its type.

Deprecated: use GetCurrentPath, which mirrors the package-level GetCurrentPath name.

func (*Router) GoGetRoute deprecated

func (parseR *Router) GoGetRoute() *Element

GoGetRoute returns the element for the current route.

Deprecated: Use Current instead. GoGetRoute exists for compatibility with earlier API consumers and delegates directly to Current.

func (*Router) GoRegisterRoute deprecated

func (parseR *Router) GoRegisterRoute(parsePath string, parseComponent interface{}, parseOptions ...Options)

GoRegisterRoute registers a route on the router instance.

Deprecated: Use Register instead. GoRegisterRoute exists for compatibility with earlier API consumers and delegates directly to Register.

func (*Router) HydrateMount

func (parseR *Router) HydrateMount(parseSelector string)

HydrateMount binds the router to an already-hydrated DOM target and only wires future route updates/listeners without forcing an immediate rerender.

func (*Router) HydrateMountElement

func (parseR *Router) HydrateMountElement(parseElem js.Value)

HydrateMountElement binds the router to an already-hydrated DOM element and only wires future route updates/listeners without forcing an immediate rerender.

func (*Router) IsLoading

func (parseR *Router) IsLoading() bool

IsLoading reports whether the current route loader is pending.

func (*Router) Mount

func (parseR *Router) Mount(parseSelector string)

Mount renders the router into a DOM node selected by CSS selector and wires hashchange listeners.

func (*Router) MountElement

func (parseR *Router) MountElement(parseElem js.Value)

MountElement renders the router into an existing DOM element reference.

func (*Router) Navigate

func (parseR *Router) Navigate(parsePath string)

Navigate navigates to a path using the appropriate method for this router type.

func (*Router) NavigateReplace

func (parseR *Router) NavigateReplace(parsePath string)

NavigateReplace replaces the current history entry using the appropriate method for this router type.

func (*Router) Register

func (parseR *Router) Register(parsePath string, parseComponent interface{}, parseOptions ...Options)

Register registers a route using either a component function or a static node.

func (*Router) RegisterLazy

func (parseR *Router) RegisterLazy(parsePath string, parseComponent interface{}, parseChunk RouteChunk, parseOptions ...Options)

RegisterLazy registers a route that loads chunk before rendering component.

func (*Router) RegisteredRoutes

func (parseR *Router) RegisteredRoutes() []string

RegisteredRoutes returns a sorted, de-duplicated slice of all registered route path strings for the given Router. Only exact-path routes stored in the routes map are included; catch-all ("*") and dynamic-pattern routes (those stored in patterns) are excluded because they are not discrete navigable paths. A nil receiver returns a non-nil empty slice.

func (*Router) RetryLoader

func (parseR *Router) RetryLoader(parseKey string) error

RetryLoader clears one active loader entry by key and renders the current route again.

func (*Router) Revalidate

func (parseR *Router) Revalidate()

Revalidate clears the cached result for the current route loader and runs it again.

func (*Router) SetFocusManagement

func (parseR *Router) SetFocusManagement(parseEnabled bool)

SetFocusManagement enables or disables automatic focus movement to the new route's content after navigation. It is on by default; disable it only if the app manages focus itself.

func (*Router) SetViewTransitions

func (parseR *Router) SetViewTransitions(parseEnabled bool)

SetViewTransitions enables or disables the automatic View Transitions animation on navigation. It is on by default; disable it to opt a router out of route-change animation.

type RouterOptions

type RouterOptions struct {
	DefaultRoute string
}

RouterOptions configures router defaults.

type SearchParams

type SearchParams struct {
	// contains filtered or unexported fields
}

SearchParams provides query values plus navigation helpers that preserve the current path.

func UseSearchParams

func UseSearchParams() SearchParams

UseSearchParams returns the current query values together with update helpers that preserve the active route path while changing the query string.

func (SearchParams) Bool

func (parseS SearchParams) Bool(parseKey string) (bool, bool)

Bool parses the search-param value for key as a bool; ok is false when absent or unparseable.

func (SearchParams) Delete

func (parseS SearchParams) Delete(parseKey string)

Delete pushes a navigation update with key removed.

func (SearchParams) Encode

func (parseS SearchParams) Encode() string

Encode serializes the current search params using net/url encoding.

func (SearchParams) Get

func (parseS SearchParams) Get(parseKey string) string

Get returns the first value for a query key or an empty string.

func (SearchParams) Has

func (parseS SearchParams) Has(parseKey string) bool

Has reports whether a query key is present.

func (SearchParams) Int

func (parseS SearchParams) Int(parseKey string) (int, bool)

Int parses the search-param value for key as an int; ok is false when absent or unparseable.

func (SearchParams) Navigate

func (parseS SearchParams) Navigate(parseValues url.Values)

Navigate applies the provided query values as a pushed navigation update.

func (SearchParams) Replace

func (parseS SearchParams) Replace(parseKey, parseValue string)

Replace updates the current history entry with key assigned to value.

func (SearchParams) ReplaceAll

func (parseS SearchParams) ReplaceAll(parseValues url.Values)

ReplaceAll replaces the current history entry with the provided query values.

func (SearchParams) Set

func (parseS SearchParams) Set(parseKey, parseValue string)

Set pushes a navigation update with key assigned to value.

func (SearchParams) Values

func (parseS SearchParams) Values() url.Values

Values returns a copy of the current search params.

Jump to

Keyboard shortcuts

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