dev

package
v2.33.7 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2026 License: MIT Imports: 27 Imported by: 0

Documentation

Overview

Package dev is what an app sees of `nexus dev`: whether it runs under it, and the state it can carry across the rebuilds the dev loop makes.

templ: version: v0.3.1020

Index

Constants

View Source
const Env = "NEXUS_DEV"

Env is the variable `nexus dev` sets to "1" on the app it runs. Production binaries never see it: `nexus build` doesn't set it and operator-launched units don't either.

View Source
const HeaderName = "X-Nexus-Toolbar"

HeaderName is the response header carrying a request's toolbar ID, which the toolbar reads off fetch and XHR responses to list them.

View Source
const RootEnv = "NEXUS_DEV_ROOT"

RootEnv overrides the directory a dev-mode app reads its frontend bundle and other embedded trees from (default: the working directory, which is how //go:embed paths are declared). nexus dev sets it to the project dir, so an app started from elsewhere still resolves them.

Variables

This section is empty.

Functions

func AddPanel added in v2.33.0

func AddPanel(p Panel)

AddPanel adds a tab to the debug toolbar, after the built-in ones; a panel of the same name replaces it. Call it from init or main: it costs nothing outside nexus dev.

func Enabled

func Enabled() bool

Enabled reports whether the app runs under `nexus dev`.

func MountToolbar added in v2.33.0

func MountToolbar(r httpx.Router)

MountToolbar serves the toolbar's script and its view of each request.

func Note added in v2.33.0

func Note(ctx context.Context, panel string, v any)

Note records v for panel on the request ctx belongs to — what a panel's Render reads back with Request.Notes. A no-op outside nexus dev, so it may stay in production code:

dev.Note(ctx, "Cache", CacheHit{Key: key, Hit: ok})

func Preserve

func Preserve(name string, v State)

Preserve registers v under name so `nexus dev` carries its state across rebuilds, and immediately restores the state a previous build left behind.

Call it wherever the value is created — a constructor is the natural place. Outside `nexus dev` it does nothing at all. Names are per-app identifiers; registering the same name twice replaces the earlier value (the later one wins, which is what a re-created singleton wants).

func PreserveJSON

func PreserveJSON[T any](name string, get func() T, set func(T))

PreserveJSON is the zero-ceremony form for state you can marshal directly, without writing the DevState methods:

nexus.PreserveJSON("counters",
    func() map[string]int { return s.snapshot() },
    func(m map[string]int) { s.load(m) })

get is called on shutdown, set on startup when a snapshot exists. Both must be safe to call from another goroutine — take the value's own lock inside them, as the store's regular methods do.

func RequestLogEnabled

func RequestLogEnabled() bool

RequestLogEnabled reports whether the per-request dev console logger should be installed. It's a DEV-ONLY convenience: nexus dev sets NEXUS_DEV=1 on the child, and the app then logs one line per HTTP request to stdout so navigations show up in the terminal (Django/Spring style) — by default they only reach the dashboard's trace stream, leaving the console quiet. Off entirely outside `nexus dev` (no NEXUS_DEV), so production binaries never log requests to the console. Opt out within dev via nexus.toml:

[runtime.logging]
requests = false

func RequestLogger

func RequestLogger(out io.Writer) httpx.HandlerFunc

RequestLogger is a whole-mux middleware that emits one structured (zap-JSON) line per completed request to out. The JSON shape matches what `nexus dev`'s Dev Server Logs view parses, so requests render in the same columnar layout as the app's own logs:

{"level":"info","ts":1.78e9,"caller":"http","msg":"GET /users","status":200,"dur":"12ms"}

Status drives the level — 5xx→error, 4xx→warn, else info — so failures stand out in red/amber. Dashboard traffic (/__nexus*) is skipped: the dashboard is WebSocket-driven and self-referential, so logging it would be noise.

func SaveState

func SaveState() error

SaveState writes every preserved value to the file `nexus dev` hands over to the next build. Boot calls it on a graceful shutdown; outside nexus dev it does nothing.

func StateDir

func StateDir() string

StateDir returns the directory `nexus dev` set aside for state that should outlive a rebuild, or "" when the process isn't running under `nexus dev`.

PreserveDev is the right tool for state you can hand over as bytes. This is the escape hatch for state that already has its own on-disk format — an embedded key/value store, a SQLite file — where the whole fix for "my session dies on every save" is pointing it at a real path instead of ":memory:". Same lifetime either way: the directory is per dev session, so what you write survives rebuilds but not a Ctrl-C.

func Toolbar added in v2.33.0

func Toolbar(spans SpanSource) httpx.HandlerFunc

Toolbar is the whole-mux middleware of the debug toolbar: it records each request, and puts the toolbar on every HTML page it answers.

func ToolbarEnabled added in v2.33.0

func ToolbarEnabled() bool

ToolbarEnabled reports whether the debug toolbar is on: under nexus dev only, unless nexus.toml turns it off:

[runtime.toolbar]
enabled = false

func ToolbarLogs added in v2.33.0

func ToolbarLogs(h slog.Handler) slog.Handler

ToolbarLogs wraps h so the records written under a request also reach the toolbar's Logs panel.

func Track added in v2.33.2

func Track(ctx context.Context, page, method, label string) (context.Context, func(status int, err error))

Track records work a page started outside an HTTP request — a live view's socket event — as an entry of that page's toolbar list: page is the page load's toolbar ID, method and label how the entry reads ("LIVE", "Dashboard.Search"). The work runs under the returned context; finish ends the entry. A no-op when the page isn't kept, or outside nexus dev.

ctx, finish := dev.Track(ctx, page, "LIVE", "Dashboard.Search")
err := run(ctx)
finish(200, err)

func TrackPage added in v2.33.4

func TrackPage(ctx context.Context, page, method, path string) (context.Context, func(status int, err error))

TrackPage is Track for a page the browser moved to without a page load — a live view navigated to over its socket: path is the page's URL path, and the toolbar pins the entry when the browser shows that page.

Types

type Build added in v2.33.3

type Build struct {
	State  string    `json:"state"`
	Since  time.Time `json:"since"`
	Output string    `json:"output,omitempty"`
}

Build is where nexus dev's rebuild stands while this process serves: State "building" (Since it started), "failed" (Output is the compiler's) or "ok". The zero Build outside nexus dev, or before its first rebuild.

func BuildState added in v2.33.3

func BuildState() Build

BuildState reads the dev loop's build state.

type Column added in v2.33.0

type Column struct {
	Title string `json:"title"`
	Code  bool   `json:"code,omitempty"`
	Lang  string `json:"lang,omitempty"`
	Num   bool   `json:"num,omitempty"`
	Bar   bool   `json:"bar,omitempty"`
}

Column is a table column: Code shows its cells in a monospace block (JSON, stacks), Lang "sql" also highlights SQL, Num aligns them right, and Bar draws each number as a bar against the column's largest.

type LogRecord added in v2.33.0

type LogRecord struct {
	Time    time.Time
	Level   slog.Level
	Message string
	Attrs   map[string]any
}

LogRecord is a log record written while a request ran.

type Panel added in v2.33.0

type Panel struct {
	Name   string
	Render func(r *Request) Section
}

Panel is a tab of the debug toolbar. Render runs when the toolbar shows a request, and returns what the tab displays; Name is its title.

dev.AddPanel(dev.Panel{Name: "Cache", Render: func(r *dev.Request) dev.Section {
	hits := r.Notes("Cache")
	return dev.Section{Summary: fmt.Sprintf("%d lookups", len(hits)), …}
}})

type Request added in v2.33.0

type Request struct {
	ID       string
	Method   string
	Path     string
	Query    url.Values
	Header   http.Header
	Status   int
	Start    time.Time
	Duration time.Duration
	// Spans are the request's trace spans, root first, filled when the
	// request ends.
	Spans []*trace.SpanNode
	// contains filtered or unexported fields
}

Request is one HTTP request as the debug toolbar shows it: what the browser asked, what the app answered, the spans its traces recorded (SQL statements among them), the log records written under it, and what panels noted while it ran.

func RequestFrom added in v2.33.0

func RequestFrom(ctx context.Context) *Request

RequestFrom is the toolbar's record of the request ctx belongs to; nil outside nexus dev, or when the toolbar is off.

func (*Request) Logs added in v2.33.0

func (r *Request) Logs() []LogRecord

Logs is what the app logged under the request: records written with a context (InfoContext, …) that carries it.

func (*Request) Notes added in v2.33.0

func (r *Request) Notes(panel string) []any

Notes is what Note recorded for panel during the request.

func (*Request) TraceIDs added in v2.33.0

func (r *Request) TraceIDs() []string

TraceIDs are the traces the request opened (one per traced route).

type Section added in v2.33.0

type Section struct {
	Summary string `json:"summary,omitempty"`
	// Tone colours the summary: "", "warn" or "error".
	Tone  string `json:"tone,omitempty"`
	Stats []Stat `json:"stats,omitempty"`
	Table *Table `json:"table,omitempty"`
	Text  string `json:"text,omitempty"`
	// View is a templ component the panel renders, styled by the
	// toolbar's stylesheet (the classes of toolbar.css) or its own.
	View templ.Component `json:"-"`
	HTML string          `json:"html,omitempty"`
}

Section is what a panel shows: Summary beside its title in the toolbar's list, Stats as figures at the top, then Text (preformatted), a templ View, HTML (the app's own markup, shown as is) and a Table — whichever are set.

type SpanSource added in v2.33.0

type SpanSource interface {
	Spans(traceID string) []*trace.SpanNode
}

SpanSource is where the toolbar reads a trace's spans: the app's trace bus.

type Stat added in v2.33.0

type Stat struct {
	Label string `json:"label"`
	Value string `json:"value"`
	Tone  string `json:"tone,omitempty"`
}

Stat is a figure at the top of a panel.

type State

type State interface {
	SnapshotDev() ([]byte, error)
	RestoreDev(data []byte) error
}

State is implemented by values that can hand their in-memory contents to the dev loop and take them back after a rebuild. Both halves speak opaque bytes, so the value picks its own encoding (JSON, gob, protobuf, …).

type Table added in v2.33.0

type Table struct {
	Columns []Column `json:"columns"`
	Rows    [][]any  `json:"rows"`
	Tones   []string `json:"tones,omitempty"`
}

Table is a panel's rows. Tones, when set, colours each row ("", "warn" or "error").

Jump to

Keyboard shortcuts

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