Documentation
¶
Overview ¶
Package ops provides small, standard-library flavored net/http handlers for operational endpoints.
ops is designed to be mounted into your own routing tree. It intentionally:
- does not choose routing paths (mount it anywhere),
- does not do authn/authz decisions (protect it with your own middleware),
- does not start servers or manage process lifecycle.
All handlers are designed to be easy to compose and to have minimal dependencies.
Formats ¶
Many handlers support both text and JSON output. By default they render text. The default can be configured by options, and can be overridden per request by URL query:
- ?format=text
- ?format=json
Text output is line-based and stable/greppable. JSON output is structured and suitable for tooling.
What ops provides ¶
This package includes handlers for:
- health: HealthzHandler (liveness), ReadyzHandler (readiness checks)
- runtime/build: RuntimeHandler, BuildInfoHandler
- tasks: TasksSnapshotHandler, TaskTriggerHandler, TaskTriggerAndWaitHandler (rt/task integration)
- tuning: TuningSnapshotHandler, TuningOverridesHandler, TuningLookupHandler, TuningSetHandler, Reset* (rt/tuning integration)
- logging: LogLevelGetHandler, LogLevelSetHandler (slog.LevelVar)
- injected snapshots: ProvidedSnapshotHandler (render provided data as JSON/text)
Security notes ¶
Operational endpoints often expose sensitive information. Mount these handlers behind your own authentication/authorization middleware, and consider restricting write handlers (trigger/set) with allowlists such as WithTaskAllowNames / WithTuningAllowKeys.
Index ¶
- func BuildInfoHandler(opts ...BuildInfoOption) http.Handler
- func HealthzHandler(opts ...HealthOption) http.Handler
- func LogLevelGetHandler(lv *slog.LevelVar, opts ...LogLevelOption) http.Handler
- func LogLevelSetHandler(lv *slog.LevelVar, opts ...LogLevelOption) http.Handler
- func ProvidedSnapshotHandler(items map[string]any, opts ...ProvidedSnapshotOption) http.Handler
- func ReadyzHandler(checks []ReadyCheck, opts ...HealthOption) http.Handler
- func RuntimeHandler(opts ...RuntimeOption) http.Handler
- func TaskTriggerAndWaitHandler(m *task.Manager, opts ...TaskOption) http.Handler
- func TaskTriggerHandler(m *task.Manager, opts ...TaskOption) http.Handler
- func TasksSnapshotHandler(m *task.Manager, opts ...TaskOption) http.Handler
- func TuningLookup(t *tuning.Tuning, key string) (tuning.Item, bool)
- func TuningLookupHandler(t *tuning.Tuning, opts ...TuningOption) http.Handler
- func TuningOverrides(t *tuning.Tuning) []tuning.OverrideItem
- func TuningOverridesHandler(t *tuning.Tuning, opts ...TuningOption) http.Handler
- func TuningResetToDefaultHandler(t *tuning.Tuning, opts ...TuningOption) http.Handler
- func TuningResetToLastValueHandler(t *tuning.Tuning, opts ...TuningOption) http.Handler
- func TuningSetHandler(t *tuning.Tuning, opts ...TuningOption) http.Handler
- func TuningSnapshot(t *tuning.Tuning) tuning.Snapshot
- func TuningSnapshotHandler(t *tuning.Tuning, opts ...TuningOption) http.Handler
- type BuildInfoModule
- type BuildInfoOption
- type BuildInfoRuntime
- type BuildInfoSetting
- type BuildInfoSnapshot
- type BuildInfoVCS
- type Format
- type HealthOption
- type LogLevelOption
- type LogLevelSnapshot
- type ProvidedSnapshotError
- type ProvidedSnapshotOption
- type ReadyCheck
- type ReadyCheckFunc
- type ReadyCheckResult
- type ReadyzReport
- type RuntimeGCSnapshot
- type RuntimeMemSnapshot
- type RuntimeOption
- type RuntimeSnapshot
- type TaskOption
- type TuningOption
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func BuildInfoHandler ¶
func BuildInfoHandler(opts ...BuildInfoOption) http.Handler
BuildInfoHandler returns a handler that outputs build metadata.
It is read-only and intended for operational inspection. It does not perform authn/authz decisions; protect it with your own middleware.
Behavior:
- GET/HEAD only; other methods return 405.
- By default, it renders text. You can change the default with options.
- The response format can be overridden per request by URL query (?format=json|text).
func HealthzHandler ¶
func HealthzHandler(opts ...HealthOption) http.Handler
HealthzHandler returns a liveness handler.
It is designed to be fast, stable, and side-effect free. By default it always responds 200 OK for GET/HEAD.
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/evan-idocoding/zkit/ops"
)
func main() {
rr := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/", nil)
ops.HealthzHandler().ServeHTTP(rr, req)
fmt.Print(rr.Body.String())
}
Output: ok
func LogLevelGetHandler ¶
func LogLevelGetHandler(lv *slog.LevelVar, opts ...LogLevelOption) http.Handler
LogLevelGetHandler returns a handler that outputs the current slog log level.
Behavior:
- GET/HEAD only; other methods return 405.
- By default, it renders text. You can change the default with options.
- The response format can be overridden per request by URL query (?format=json|text).
func LogLevelSetHandler ¶
func LogLevelSetHandler(lv *slog.LevelVar, opts ...LogLevelOption) http.Handler
LogLevelSetHandler returns a handler that sets slog log level.
Input:
- POST only
- URL query: ?level=debug|info|warn|error (case-insensitive; also supports "warning"->"warn", "err"->"error")
Output:
- Text or JSON (controlled by option or ?format=)
Example ¶
package main
import (
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"github.com/evan-idocoding/zkit/ops"
)
func main() {
lv := new(slog.LevelVar)
lv.Set(slog.LevelInfo)
rr := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodPost, "/?level=warn", nil)
ops.LogLevelSetHandler(lv).ServeHTTP(rr, req)
fmt.Print(rr.Body.String())
}
Output: log old_level info log old_level_value 0 log new_level warn log new_level_value 4
func ProvidedSnapshotHandler ¶
func ProvidedSnapshotHandler(items map[string]any, opts ...ProvidedSnapshotOption) http.Handler
ProvidedSnapshotHandler returns a handler that outputs injected snapshots.
It is read-only and intended for operational inspection (often high-sensitivity). It does not perform authn/authz decisions; protect it with your own middleware.
Input:
- items: name -> any (static values; may include pointers / references)
- items is snapshotted at handler construction time: the map is copied and key ordering is fixed. Mutating the original map after creating the handler does not affect the output.
Behavior:
- GET/HEAD only; other methods return 405.
- By default, it renders text. You can change the default with options.
- The response format can be overridden per request by URL query (?format=json|text).
- Best-effort safety: per-item marshal errors/panics do not crash the handler; they are reported in the response (partial success).
Notes on "live" references:
- Passing pointers/maps/slices may appear "live", but can introduce data races if the underlying object is mutated concurrently.
- Prefer copy-on-write snapshots (e.g. via *atomic.Value) if you need runtime updates.
func ReadyzHandler ¶
func ReadyzHandler(checks []ReadyCheck, opts ...HealthOption) http.Handler
ReadyzHandler returns a readiness handler that runs checks sequentially.
It responds:
- 200 OK if all checks pass
- 503 Service Unavailable if any check fails or times out
GET/HEAD only; other methods return 405.
func RuntimeHandler ¶
func RuntimeHandler(opts ...RuntimeOption) http.Handler
RuntimeHandler returns a handler that outputs a runtime overview snapshot.
It is read-only and intended for operational inspection. It does not perform authn/authz decisions; protect it with your own middleware.
Behavior:
- GET/HEAD only; other methods return 405.
- By default, it renders text. You can change the default with options.
- The response format can be overridden per request by URL query (?format=json|text).
func TaskTriggerAndWaitHandler ¶
func TaskTriggerAndWaitHandler(m *task.Manager, opts ...TaskOption) http.Handler
TaskTriggerAndWaitHandler returns a handler that triggers a task and waits for completion.
Input:
- POST only
- URL query: ?name=<task name>&timeout=<go duration>
timeout is optional; when provided, it must be a positive Go duration (e.g. 5s, 200ms).
func TaskTriggerHandler ¶
func TaskTriggerHandler(m *task.Manager, opts ...TaskOption) http.Handler
TaskTriggerHandler returns a handler that triggers a task once (fire-and-forget).
Input:
- POST only
- URL query: ?name=<task name>
Output:
- 200 if accepted
- 409 if not accepted (busy / not running / closed)
func TasksSnapshotHandler ¶
func TasksSnapshotHandler(m *task.Manager, opts ...TaskOption) http.Handler
TasksSnapshotHandler returns a handler that outputs a task manager snapshot.
Behavior:
- GET/HEAD only; other methods return 405.
- By default, it renders text. You can change the default with options.
- The response format can be overridden per request by URL query (?format=json|text).
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"github.com/evan-idocoding/zkit/ops"
"github.com/evan-idocoding/zkit/rt/task"
)
func main() {
m := task.NewManager()
_ = m.MustAdd(task.Trigger(func(context.Context) error { return nil }), task.WithName("job"))
rr := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/", nil)
ops.TasksSnapshotHandler(m).ServeHTTP(rr, req)
fmt.Print(rr.Body.String())
}
Output: task job state not-started task job running 0 task job pending false task job run_count 0 task job fail_count 0 task job success_count 0 task job canceled_count 0
func TuningLookup ¶
TuningLookup returns a point-in-time view for a single key (redaction rules apply).
func TuningLookupHandler ¶
func TuningLookupHandler(t *tuning.Tuning, opts ...TuningOption) http.Handler
TuningLookupHandler returns a handler that looks up a single key.
Input:
- GET/HEAD only
- URL query: ?key=<tuning key>
func TuningOverrides ¶
func TuningOverrides(t *tuning.Tuning) []tuning.OverrideItem
TuningOverrides returns current overrides (Value != DefaultValue) for ops usage.
func TuningOverridesHandler ¶
func TuningOverridesHandler(t *tuning.Tuning, opts ...TuningOption) http.Handler
TuningOverridesHandler returns a handler that outputs ExportOverrides (Value != DefaultValue).
Behavior:
- GET/HEAD only; other methods return 405.
- By default, it renders text. You can change the default with options.
- The response format can be overridden per request by URL query (?format=json|text).
func TuningResetToDefaultHandler ¶
func TuningResetToDefaultHandler(t *tuning.Tuning, opts ...TuningOption) http.Handler
TuningResetToDefaultHandler returns a handler that resets a key to its default.
Input:
- POST only
- URL query: ?key=<tuning key>
func TuningResetToLastValueHandler ¶
func TuningResetToLastValueHandler(t *tuning.Tuning, opts ...TuningOption) http.Handler
TuningResetToLastValueHandler returns a handler that undoes one step for a key.
Input:
- POST only
- URL query: ?key=<tuning key>
func TuningSetHandler ¶
func TuningSetHandler(t *tuning.Tuning, opts ...TuningOption) http.Handler
TuningSetHandler returns a handler that sets a tuning key from string.
Input:
- POST only
- URL query: ?key=<tuning key>&value=<string representation>
value can be empty string if the underlying variable type allows it.
func TuningSnapshot ¶
TuningSnapshot returns a point-in-time snapshot for ops usage.
func TuningSnapshotHandler ¶
func TuningSnapshotHandler(t *tuning.Tuning, opts ...TuningOption) http.Handler
TuningSnapshotHandler returns a handler that outputs a tuning snapshot.
Behavior:
- GET/HEAD only; other methods return 405.
- By default, it renders text. You can change the default with options.
- The response format can be overridden per request by URL query (?format=json|text).
Example ¶
package main
import (
"fmt"
"net/http"
"net/http/httptest"
"github.com/evan-idocoding/zkit/ops"
"github.com/evan-idocoding/zkit/rt/tuning"
)
func main() {
tu := tuning.New()
_, _ = tu.Bool("feature.x", false)
rr := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/", nil)
ops.TuningSnapshotHandler(tu).ServeHTTP(rr, req)
fmt.Print(rr.Body.String())
}
Output: tuning feature.x type bool tuning feature.x value false tuning feature.x default false tuning feature.x source default
Types ¶
type BuildInfoModule ¶
type BuildInfoModule struct {
Path string `json:"path"`
Version string `json:"version,omitempty"`
Sum string `json:"sum,omitempty"`
Replace *BuildInfoModule `json:"replace,omitempty"`
}
BuildInfoModule describes a module in the build graph.
Replace, when present, indicates that this module was replaced by another module.
type BuildInfoOption ¶
type BuildInfoOption func(*buildInfoConfig)
BuildInfoOption configures BuildInfoHandler.
func WithBuildInfoDefaultFormat ¶
func WithBuildInfoDefaultFormat(f Format) BuildInfoOption
WithBuildInfoDefaultFormat sets the default response format.
This default can be overridden per request by URL query:
- ?format=json
- ?format=text
Default is FormatText.
func WithBuildInfoIncludeDeps ¶
func WithBuildInfoIncludeDeps(v bool) BuildInfoOption
WithBuildInfoIncludeDeps controls whether the response includes dependency modules.
Default is false.
func WithBuildInfoIncludeSettings ¶
func WithBuildInfoIncludeSettings(v bool) BuildInfoOption
WithBuildInfoIncludeSettings controls whether the response includes all build settings.
Default is false.
type BuildInfoRuntime ¶
type BuildInfoRuntime struct {
Version string `json:"version"`
GOOS string `json:"goos"`
GOARCH string `json:"goarch"`
Compiler string `json:"compiler"`
}
BuildInfoRuntime describes the Go runtime/toolchain for the running binary.
type BuildInfoSetting ¶
BuildInfoSetting is a key/value entry from debug.ReadBuildInfo().Settings.
type BuildInfoSnapshot ¶
type BuildInfoSnapshot struct {
Module BuildInfoModule `json:"module"`
VCS *BuildInfoVCS `json:"vcs,omitempty"`
Runtime BuildInfoRuntime `json:"runtime"`
Deps []BuildInfoModule `json:"deps,omitempty"`
Settings []BuildInfoSetting `json:"settings,omitempty"`
}
BuildInfoSnapshot is a structured snapshot of build info.
func BuildInfo ¶
func BuildInfo() (*BuildInfoSnapshot, bool)
BuildInfo returns a structured build info snapshot (compact).
It does not include deps or build settings by default. Use BuildInfoFull if you want a complete snapshot including deps and settings.
func BuildInfoFull ¶
func BuildInfoFull() (*BuildInfoSnapshot, bool)
BuildInfoFull returns a structured build info snapshot including deps and build settings.
type BuildInfoVCS ¶
type BuildInfoVCS struct {
System string `json:"system,omitempty"`
Revision string `json:"revision,omitempty"`
Time string `json:"time,omitempty"`
Modified *bool `json:"modified,omitempty"`
}
BuildInfoVCS describes version control metadata embedded by the Go toolchain.
type Format ¶
type Format int
Format controls the response rendering format.
This is shared across ops handlers that support multiple output formats.
type HealthOption ¶
type HealthOption func(*healthConfig)
HealthOption configures HealthzHandler / ReadyzHandler.
func WithHealthDefaultFormat ¶
func WithHealthDefaultFormat(f Format) HealthOption
WithHealthDefaultFormat sets the default response format for health handlers.
This default can be overridden per request by URL query:
- ?format=json
- ?format=text
Default is FormatText.
type LogLevelOption ¶
type LogLevelOption func(*logLevelConfig)
LogLevelOption configures LogLevelGetHandler / LogLevelSetHandler.
func WithLogLevelDefaultFormat ¶
func WithLogLevelDefaultFormat(f Format) LogLevelOption
WithLogLevelDefaultFormat sets the default response format for log level handlers.
This default can be overridden per request by URL query:
- ?format=json
- ?format=text
Default is FormatText.
type LogLevelSnapshot ¶
type LogLevelSnapshot struct {
// Level is a canonical string derived from LevelValue. It is always one of:
// debug/info/warn/error.
Level string `json:"level"`
// LevelValue is the underlying numeric slog level (e.g. Debug=-4, Info=0, Warn=4, Error=8).
LevelValue int `json:"level_value"`
}
LogLevelSnapshot is a point-in-time snapshot of a slog.LevelVar.
func LogLevel ¶
func LogLevel(lv *slog.LevelVar) LogLevelSnapshot
LogLevel returns a snapshot of lv.
type ProvidedSnapshotError ¶
type ProvidedSnapshotError struct {
Name string `json:"name"`
Error string `json:"error"`
Panicked bool `json:"panicked,omitempty"`
}
ProvidedSnapshotError represents a per-item error.
type ProvidedSnapshotOption ¶
type ProvidedSnapshotOption func(*providedSnapshotConfig)
ProvidedSnapshotOption configures ProvidedSnapshotHandler.
func WithProvidedSnapshotDefaultFormat ¶
func WithProvidedSnapshotDefaultFormat(f Format) ProvidedSnapshotOption
WithProvidedSnapshotDefaultFormat sets the default response format.
This default can be overridden per request by URL query:
- ?format=json
- ?format=text
Default is FormatText.
func WithProvidedSnapshotMaxBytes ¶
func WithProvidedSnapshotMaxBytes(n int) ProvidedSnapshotOption
WithProvidedSnapshotMaxBytes sets an upper bound for the response body size.
This is a safety valve to avoid accidental huge dumps. If the response exceeds this limit, the handler responds with HTTP 413.
Note: this limit is enforced on the final rendered body (JSON/text). It is not a guarantee on serialization CPU/memory cost.
<= 0 means "no limit".
type ReadyCheck ¶
type ReadyCheck struct {
Name string
Func ReadyCheckFunc
Timeout time.Duration // optional per-check timeout; <= 0 means "no extra timeout"
}
ReadyCheck is a named readiness check.
type ReadyCheckFunc ¶
ReadyCheckFunc is a readiness check function.
It should return nil when healthy. Implementations should be fast and must respect ctx cancellation.
type ReadyCheckResult ¶
type ReadyCheckResult struct {
Name string `json:"name"`
OK bool `json:"ok"`
// Duration is encoded as an integer number of nanoseconds in JSON.
Duration time.Duration `json:"duration"`
Error string `json:"error,omitempty"`
TimedOut bool `json:"timed_out,omitempty"`
}
ReadyCheckResult is a single check execution result.
type ReadyzReport ¶
type ReadyzReport struct {
OK bool `json:"ok"`
// Duration is encoded as an integer number of nanoseconds in JSON.
Duration time.Duration `json:"duration"`
Checks []ReadyCheckResult `json:"checks,omitempty"`
}
ReadyzReport is a point-in-time readiness execution report.
func RunReadyzChecks ¶
func RunReadyzChecks(ctx context.Context, checks []ReadyCheck) ReadyzReport
RunReadyzChecks executes checks sequentially and returns a report.
type RuntimeGCSnapshot ¶
type RuntimeGCSnapshot struct {
NumGC uint32 `json:"num_gc"`
LastGCTime *time.Time `json:"last_gc_time,omitempty"`
LastPause time.Duration `json:"last_pause"`
LastPauseEndTime *time.Time `json:"last_pause_end_time,omitempty"`
// PauseTotal is encoded as an integer number of nanoseconds in JSON.
PauseTotal time.Duration `json:"pause_total"`
NextGCBytes uint64 `json:"next_gc_bytes"`
GCCPUFraction float64 `json:"gc_cpu_fraction"`
}
RuntimeGCSnapshot is a compact GC summary.
type RuntimeMemSnapshot ¶
type RuntimeMemSnapshot struct {
AllocBytes uint64 `json:"alloc_bytes"`
TotalAllocBytes uint64 `json:"total_alloc_bytes"`
SysBytes uint64 `json:"sys_bytes"`
HeapAllocBytes uint64 `json:"heap_alloc_bytes"`
HeapSysBytes uint64 `json:"heap_sys_bytes"`
HeapInuseBytes uint64 `json:"heap_inuse_bytes"`
HeapIdleBytes uint64 `json:"heap_idle_bytes"`
HeapReleasedBytes uint64 `json:"heap_released_bytes"`
StackInuseBytes uint64 `json:"stack_inuse_bytes"`
StackSysBytes uint64 `json:"stack_sys_bytes"`
}
RuntimeMemSnapshot is a compact memory summary.
type RuntimeOption ¶
type RuntimeOption func(*runtimeConfig)
RuntimeOption configures RuntimeHandler.
func WithRuntimeDefaultFormat ¶
func WithRuntimeDefaultFormat(f Format) RuntimeOption
WithRuntimeDefaultFormat sets the default response format.
This default can be overridden per request by URL query:
- ?format=json
- ?format=text
Default is FormatText.
type RuntimeSnapshot ¶
type RuntimeSnapshot struct {
Now time.Time `json:"now"`
StartTime time.Time `json:"start_time"`
// Uptime is encoded as an integer number of nanoseconds in JSON.
Uptime time.Duration `json:"uptime"`
PID int `json:"pid"`
Runtime BuildInfoRuntime `json:"runtime"`
NumCPU int `json:"num_cpu"`
GOMAXPROCS int `json:"gomaxprocs"`
Goroutines int `json:"goroutines"`
CGOCalls int64 `json:"cgo_calls"`
Mem RuntimeMemSnapshot `json:"mem"`
GC RuntimeGCSnapshot `json:"gc"`
}
RuntimeSnapshot is a point-in-time runtime snapshot.
func Runtime ¶
func Runtime() RuntimeSnapshot
Runtime returns a structured runtime snapshot (compact).
type TaskOption ¶
type TaskOption func(*taskOpsConfig)
TaskOption configures task ops handlers.
func WithTaskAllowNames ¶
func WithTaskAllowNames(names ...string) TaskOption
WithTaskAllowNames restricts task names to the provided explicit set.
Safety note: if no non-empty name is provided, this option denies all names.
func WithTaskAllowPrefixes ¶
func WithTaskAllowPrefixes(prefixes ...string) TaskOption
WithTaskAllowPrefixes restricts task names to the provided prefixes.
Safety note: if no non-empty prefix is provided, this option denies all names.
func WithTaskDefaultFormat ¶
func WithTaskDefaultFormat(f Format) TaskOption
WithTaskDefaultFormat sets the default response format for task handlers.
This default can be overridden per request by URL query:
- ?format=json
- ?format=text
Default is FormatText.
func WithTaskNameGuard ¶
func WithTaskNameGuard(fn func(name string) bool) TaskOption
WithTaskNameGuard appends a name guard.
All guards are combined with AND: a name is allowed only if all guards allow it. This applies to both read and write handlers.
type TuningOption ¶
type TuningOption func(*tuningConfig)
TuningOption configures tuning handlers.
func WithTuningAllowKeys ¶
func WithTuningAllowKeys(keys ...string) TuningOption
WithTuningAllowKeys restricts keys to the provided explicit set.
Safety note: if no non-empty key is provided, this option denies all keys.
func WithTuningAllowPrefixes ¶
func WithTuningAllowPrefixes(prefixes ...string) TuningOption
WithTuningAllowPrefixes restricts keys to the provided prefixes.
Safety note: if no non-empty prefix is provided, this option denies all keys.
func WithTuningDefaultFormat ¶
func WithTuningDefaultFormat(f Format) TuningOption
WithTuningDefaultFormat sets the default response format for tuning handlers.
This default can be overridden per request by URL query:
- ?format=json
- ?format=text
Default is FormatText.
func WithTuningKeyGuard ¶
func WithTuningKeyGuard(fn func(key string) bool) TuningOption
WithTuningKeyGuard appends a key guard.
All guards are combined with AND: a key is allowed only if all guards allow it. This applies to both read and write handlers.