server

package
v0.134.6 Latest Latest
Warning

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

Go to latest
Published: Nov 17, 2026 License: Apache-2.0 Imports: 50 Imported by: 0 modules, 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.

Documentation

Overview

Package server provides the canonical fleet HTTP server bootstrap.

A minimal service main:

func main() {
    cfg := config.Load("go_myservice", "v1.0.0")
    srv := server.New(cfg,
        server.WithKeystoreAuth(),
        server.WithDependencies(deps),
        server.WithMaxBodyBytes(4<<20),
    )
    srv.Mux.HandleFunc("/api/v1/items", itemsHandler)
    log.Fatal(srv.Start())
}

server.New wires the full fleet middleware stack (graph, requestID, logging, body limit, metrics, promx), /health, /version, /capabilities, /schema, /metrics, and /selftest default endpoints automatically. Every response names the service: X-Service-Name (Config.AppName) and X-Service-Version (Config.Version), set by the server and not replaceable by a handler. Start() performs a graceful SIGTERM drain. New also gives the process's plain http.Clients the fleet-direct proxy rule (egress.InstallDefaultTransport), so a call to a sibling service never goes through the egress proxy.

mcp.go bridges a service's agent contract (see agent/agent.go and WithAgent/WithAgentFromEmbed) onto a real Model Context Protocol Streamable HTTP endpoint at GET/POST /mcp, using the official github.com/modelcontextprotocol/go-sdk.

Why the bridge dispatches through s.Mux instead of re-implementing each tool: a service already has exactly one correct implementation of its behaviour — its HTTP handler. Building a second implementation for MCP would drift from the first the moment either one changes. Instead, a tools/call synthesises an *http.Request from the tool's declared Method/Path/InputSchema and replays it against s.Mux directly (httptest.NewRecorder, no network hop), so the MCP surface can never disagree with the HTTP surface.

Auth is not re-implemented either. /mcp is just another route on s.Mux, so it sits behind the same middleware chain (WithKeystoreAuth et al.) as every other route — the same Authorization: Bearer <key> the fleet keystore already issues. Because the in-process replay happens after that chain has already authorized the inbound request, the synthetic request does not need to carry credentials of its own.

Index

Examples

Constants

View Source
const (
	DefaultDrainPeriod     = 15 * time.Second
	DefaultShutdownTimeout = 25 * time.Second
)

Default drain budget when WithGracefulDrain is enabled but the caller passes zero (or a negative value). 15s drain + 25s shutdown total matches the recommended docker-compose stop_grace_period of 45s.

View Source
const (
	DefaultReadTimeout  = 10 * time.Second
	DefaultWriteTimeout = 30 * time.Second
	DefaultIdleTimeout  = 120 * time.Second
)

Default http.Server timeouts applied by Start. WriteTimeout is overridable per-service via WithWriteTimeout for services that legitimately produce slow responses (e.g. a cold JS render).

View Source
const CancelPathPrefix = "/cancel/"

CancelPathPrefix is the URL prefix the cancel handler is mounted at. DELETE <CancelPathPrefix><id> cancels the in-flight request whose X-Request-Id equals <id>.

View Source
const CancellationHeader = "X-Request-Id"

CancellationHeader is the canonical request-correlation header. The fleet already uses X-Request-Id for log correlation (see middleware.RequestID); the cancellation registry piggybacks on that header so callers don't have to attach two different IDs to the same request.

View Source
const DefaultDrainTimeout = 30 * time.Second

DefaultDrainTimeout is how long Start waits for in-flight requests after receiving SIGTERM before forcing closure.

View Source
const DefaultMaxBodyBytes = 4 << 20

DefaultMaxBodyBytes is the default request body size limit applied by server.New unless overridden with WithMaxBodyBytes. 4 MiB matches the validate.Bind default and common reverse-proxy limits.

View Source
const DefaultMaxInFlight = 10000

DefaultMaxInFlight bounds the in-memory registry. New requests that arrive when the registry is full run normally — they just don't get registered for cancellation. Graceful degradation, not a 503.

View Source
const DefaultMaxMCPResponseBytes int64 = 4 << 20

DefaultMaxMCPResponseBytes bounds a tool's buffered HTTP response to 4 MiB.

View Source
const DefaultSchemaVersion = 1

DefaultSchemaVersion is what services advertise if they don't register a version explicitly. 1 is the "I exist but never bumped" signal — distinguishable from 0 (which Envelope omits).

Variables

This section is empty.

Functions

func CurrentSchemaVersion

func CurrentSchemaVersion() int

CurrentSchemaVersion returns the schema version registered for the currently-running service (DefaultSchemaVersion when unset). Safe to call from any goroutine.

func HealthHandler

func HealthHandler(serviceID, version string) http.Handler

HealthHandler returns an http.Handler for GET /health. Response: {"status":"ok","service":"<id>","version":"<ver>"}

func KebabAlias

func KebabAlias(serviceName string) string

KebabAlias derives the public kebab-case slug from a Go service name. "go_email_extractor" → "email-extractor". Returns "" if the input has no go_ prefix and no underscores (no transform produced).

Exported so callers that don't use Run can still mount the same alias the gateway expects.

func Run

func Run(serviceName, version string, handler http.HandlerFunc, opts ...Option)

Run is the canonical 0crawl service entrypoint. It bundles the four things every fleet service does identically: config load, keystore- backed auth, the standard route mounts (/, /<serviceName>, and the kebab alias if different), and Start.

A 5-line main.go is the goal:

package main

const version = "1.0.0"

func main() {
    server.Run("go_email_extractor", version, Handler)
}

What it does, in order:

  1. config.Load(serviceName, version) — same as today
  2. WithKeystoreAuth() prepended — keystore-only fleet auth
  3. server.New(cfg, opts...) — /health, /version, /metrics + base mw
  4. srv.Mux.HandleFunc("/", handler) — catchall (post-gateway strip lands here)
  5. srv.Mux.HandleFunc("/"+serviceName, handler) — direct/internal entry
  6. srv.Mux.HandleFunc("/"+kebab, handler) — public kebab alias (only if different)
  7. srv.Start() — listen forever; if it returns an error (the port is taken, a drain timed out) Run logs it and exits with status 1

Callers that need extra routes or custom middleware should use server.New(cfg, opts...) + manual srv.Mux.HandleFunc(...) + srv.Start() instead of Run. Run is for the 90% of services with no quirks.

func RunTier

func RunTier(serviceName, version string, handler http.HandlerFunc, requiredTier string, enforce bool, opts ...Option)

RunTier is Run with the prepended auth swapped from WithKeystoreAuth to WithKeystoreAuthTier — for services whose access_tier registry override needs enforcing on their own direct entrypoint, not just via the gateway. Same 5-line-main.go shape as Run; use this instead of Run + a redundant WithKeystoreAuthTier in opts (which would stack two keystore verifies).

func main() {
    server.RunTier("go-pentest-nuclei", version, Handler, "vetted-pentest", true)
}

func VersionHandler

func VersionHandler(version string) http.Handler

VersionHandler returns an http.Handler for GET /version. Response: {"version":"<ver>"}

Types

type AdminGate

type AdminGate func(r *http.Request) error

AdminGate decides whether an inbound request to DELETE /cancel/<id> is permitted. Return nil to allow, or an error to deny (in which case the handler responds 401). Pass a nil AdminGate (the zero CancellationConfig default) to disable auth on the cancel endpoint entirely — appropriate for services on a private mesh where the upstream gateway already gates admin scope.

A typical implementation checks a header against a shared secret:

gate := func(r *http.Request) error {
    if r.Header.Get(header.AdminToken) != os.Getenv("ADMIN_TOKEN") {
        return errors.New("forbidden")
    }
    return nil
}

type CancellationConfig

type CancellationConfig struct {
	// MaxInFlight bounds the in-memory registry. <=0 means
	// DefaultMaxInFlight.
	MaxInFlight int

	// AdminGate, when non-nil, is invoked on every DELETE /cancel/<id>
	// request. Returning an error responds 401 and skips the
	// cancellation. Default nil (no auth) — see decision rationale in
	// the PR body.
	AdminGate AdminGate
}

CancellationConfig tunes the cancellation registry. Zero value is safe: MaxInFlight defaults to DefaultMaxInFlight; AdminGate nil means no auth (see WithCancellationRegistry doc for the rationale).

type Option

type Option func(*Server)

func WithAgent

func WithAgent(c agent.Contract) Option

WithAgent registers a GET /agent.json handler that serves an agent-facing contract — the machine-readable "how to call me" document for AI agents (MCP servers, Claude, Codex, the catalog hub). It is the agentic counterpart to /capabilities (query-flag dials) and /schema (envelope version).

The contract is serialised once at startup, so mutations after this call are not reflected — build it with agent.DefaultContract or agent.LoadEmbed before passing it here.

srv := server.New(cfg, server.WithAgent(agent.DefaultContract(cfg.AppName, cfg.Version)))

Most services should prefer WithAgentFromEmbed with a shipped agent.json so the contract carries a precise input schema and examples.

func WithAgentFromEmbed

func WithAgentFromEmbed(fsys embed.FS, name string) Option

WithAgentFromEmbed reads agent.json from an embedded filesystem and serves it at GET /agent.json. This is the recommended service pattern:

//go:embed agent.json
var agentFS embed.FS
srv := server.New(cfg, server.WithAgentFromEmbed(agentFS, "agent.json"))

service/version are taken from cfg when the embedded file omits them, so a service ships only the fields that differ from the default. A missing or invalid embed fails fast rather than silently serving a wrong contract.

func WithCancellationRegistry

func WithCancellationRegistry(cfg CancellationConfig) Option

WithCancellationRegistry installs the cancellation primitive on the server:

  1. A handler at DELETE /cancel/<id> that cancels the in-flight request whose X-Request-Id matches <id>.
  2. A middleware that intercepts incoming requests, registers them in an in-memory map keyed by X-Request-Id, and replaces r.Context with a cancellable one. On handler return the entry is removed.

If the incoming request has no X-Request-Id header the middleware generates one and writes it to the response so callers can later issue a cancel against it.

The registry is process-local. Cross-replica cancellation is out of scope — callers that need it should target the specific replica (e.g. via a sticky session) or use a shared store (Redis pub/sub), neither of which lives in go-common.

Typical use:

srv := server.New(cfg,
    server.WithCancellationRegistry(server.CancellationConfig{
        MaxInFlight: 5000,
        AdminGate:   myAdminGate,
    }),
)

Pass server.CancellationConfig{} for defaults (10k entries, no admin gate — fine on a private mesh where the gateway already gates admin scope).

func WithCapability

func WithCapability(c ...client.Capability) Option

WithCapability appends one or more Capability entries to the service's advertised flag list. Capabilities are returned verbatim on GET /capabilities.

func WithDependencies

func WithDependencies(r *depcheck.Registry) Option

WithDependencies attaches a dep registry whose probes are run on every /health request. Health JSON gains a "dependencies":[…] array and the top-level "status" flips to "degraded" if any probe fails (HTTP stays 200 so a soft-dep blip doesn't tear the container down). See depcheck package doc for the JSON contract.

Pass exactly one registry — calling WithDependencies twice replaces the previous registry.

func WithDrainTimeout

func WithDrainTimeout(d time.Duration) Option

WithDrainTimeout sets how long Start() waits for in-flight requests to complete after receiving SIGTERM before forcing closure. Default: DefaultDrainTimeout (30 s).

func WithGracefulDrain

func WithGracefulDrain(drainPeriod, shutdownTimeout time.Duration) Option

WithGracefulDrain enables a drain period on SIGTERM/SIGINT. When a signal arrives, the readiness probe (/readyz) starts returning 503 immediately so the load balancer drains traffic away from this instance. After drainPeriod (default 15s), the server initiates an http.Server.Shutdown(ctx) bounded by shutdownTimeout (default 25s).

/health remains 200 throughout — it's the liveness probe; the kill signal comes from the process supervisor, not from /health flipping.

Without this option the server uses Go's default signal handling (immediate shutdown, in-flight requests get a connection reset).

The recommended drain + shutdown budget must be SMALLER than docker-compose's stop_grace_period (10s default; bump it to 45s in docker-compose.yml: `stop_grace_period: 45s` to give this room).

Pass zero for either argument to use the default value.

func WithIdempotencyKey

func WithIdempotencyKey(cfg middleware.IdempotencyConfig) Option

WithIdempotencyKey mounts the canonical idempotency-key middleware on the server. Clients retrying a mutating request (POST/PUT/PATCH/ DELETE by default) with the same Idempotency-Key header receive the cached response instead of re-executing the handler.

Typical use:

srv := server.New(cfg,
    server.WithKeystoreAuth(),
    server.WithIdempotencyKey(middleware.IdempotencyConfig{
        TTL:        15 * time.Minute,
        MaxEntries: 50_000,
    }),
)

Pass middleware.IdempotencyConfig{} to accept defaults (1h TTL, 10k entry LRU, POST/PUT/PATCH/DELETE methods). See the middleware package for the full contract and caveats — notably, the cache is process-local; multi-replica services need an external store.

func WithKeystoreAuth

func WithKeystoreAuth(localTokens ...string) Option

WithKeystoreAuth mounts the canonical fleet auth middleware (middleware.TokenAuthKeystore) wired up to the keystore via apikey.New() + apikey.Cache. Suitable for every 0exec service — gateway X-Auth-User is trusted on the hot path, the keystore is only called when the gateway is bypassed.

localTokens are optional service-owned credentials accepted without a keystore lookup. Avoid public or shared fallback values; use a real keystore-issued credential for callers and pass none for keystore-only auth. The staging runner's COMMONCRAWL_STAGE_API_KEY is a narrowly gated test key: it is considered only when FLEET_ENVIRONMENT=staging and FLEET_FETCH_SOURCE=commoncrawl. Never configure that key in production.

Reads APIKEY_SERVICE_URL + APIKEY_SERVICE_ADMIN_TOKEN from env (with sane defaults). Failures are deferred to first /verify call — the service starts even if the keystore is unreachable, and per-request behavior falls through to the local-token fast path or fails closed with 503. /health, /version, /_gw_health are always exempt.

func WithKeystoreAuthMesh

func WithKeystoreAuthMesh(localTokens ...string) Option

WithKeystoreAuthMesh is WithKeystoreAuth plus middleware.TrustPrivateMesh: a request whose actual TCP peer is a private/loopback/mesh IP and that carries no gateway trust header is treated as already-authenticated. Use for an internal-only, expensive-to-call service (e.g. the chromedp js-proxy) so sibling containers on the docker mesh can reach it no-auth — mirroring the fetch cache — while its PUBLIC gateway URL stays fully keystore-gated (public clients only ever arrive via nginx, which sets the gateway header). localTokens behave exactly as in WithKeystoreAuth.

func WithKeystoreAuthPublicPrefixes

func WithKeystoreAuthPublicPrefixes(publicPrefixes []string, localTokens ...string) Option

WithKeystoreAuthPublicPrefixes is WithKeystoreAuth plus a set of request path prefixes that bypass the keystore gate entirely — for a handler whose own unguessable value is its access control (go-pentest-oob-collector's GET /c/<token> catch endpoint: the random token in the path is the secret, not a keystore key, and the caller is a scanned target that can never hold this service's credential). "/c/" also exempts "/c/<token>/<id>" (a prefix match, not exact); "" and "/" are ignored rather than honored, so neither can turn the whole service public by mistake. localTokens behave exactly as in WithKeystoreAuth.

A request under a prefix is exempt only if its path is canonical (no dot segments, no "//", no encoded dot or slash: see middleware.KeystoreOpts.PublicPathPrefixes); any other path that starts with one is answered 400 by the gate.

Never declare a prefix that also serves a keystore-gated route under it. Start enforces that for the routes registered through Handle, HandleFunc and the server's own mounts: it returns an error, and does not listen, if one of them lies under a declared prefix. A route meant to be public is registered with HandlePublic. Routes registered directly on s.Mux are not checked.

func WithKeystoreAuthTier

func WithKeystoreAuthTier(requiredTier string, enforce bool, localTokens ...string) Option

WithKeystoreAuthTier is WithKeystoreAuth plus an access_tier gate: the caller's key must carry a tier matching requiredTier (apikey.TierSatisfies, exact-string equality, fail-closed) or the request is denied. localTokens locally configured credentials are NOT exempt from the tier check — they resolve to an empty callerTier, which never satisfies a non-empty requiredTier. This is the direct-service-path counterpart to the gateway's own tier enforcement (go-fleet-mcp-gateway's toolHandler); wire it into any service whose access_tier override in services-registry needs enforcing on its own /mcp endpoint, not just when called through the gateway.

enforce mirrors this fleet's shadow-then-enforce convention (LEDGER_OVERFLOW_ENABLED/ENFORCE): false observes and logs a would-deny without actually denying; true denies with 403. requiredTier == "" makes this behave exactly like WithKeystoreAuth (no tier gate at all).

srv := server.New(cfg, server.WithKeystoreAuthTier("vetted-pentest", true))

func WithKeystoreAuthTierTrustedProxy

func WithKeystoreAuthTierTrustedProxy(requiredTier string, enforce bool, trustedGatewayCIDRs []string, localTokens ...string) Option

WithKeystoreAuthTierTrustedProxy is WithKeystoreAuthTier with an explicit source-IP allowlist for gateway-injected identity headers. Use it for security-sensitive services that expose a direct private-network listener: callers outside the supplied CIDRs must present a real API key and cannot impersonate a principal by supplying X-Auth-User/X-Auth-Tier themselves.

Passing a non-empty but invalid CIDR list fails closed for the header path. Existing WithKeystoreAuthTier behavior is intentionally unchanged.

func WithKeystoreAuthTierTrustedProxyNoCache

func WithKeystoreAuthTierTrustedProxyNoCache(requiredTier string, enforce bool, trustedGatewayCIDRs []string, localTokens ...string) Option

WithKeystoreAuthTierTrustedProxyNoCache is the same narrow trusted-proxy tier gate as WithKeystoreAuthTierTrustedProxy, but every direct-key request is verified by go-apikey-service. Use it only for consumable credentials such as one-time writers: a positive-result cache would otherwise admit a replay without giving the keystore a chance to atomically claim the use.

Gateway-injected requests from trusted CIDRs retain the established gateway trust path; the gateway is responsible for its own authoritative /verify. Existing cached options are deliberately unchanged.

func WithMCP

func WithMCP() Option

WithMCP mounts a Model Context Protocol Streamable HTTP endpoint at /mcp. It requires an agent contract — WithAgent or WithAgentFromEmbed, in either order relative to this option, since both are resolved into s.AgentContract before /mcp is mounted (see New()). A service with no contract has nothing to expose as MCP tools; New panics in that case rather than silently serving an empty tool list.

func WithMCPResponseLimit added in v0.133.0

func WithMCPResponseLimit(maxBytes int64) Option

WithMCPResponseLimit sets the maximum bytes buffered for a tool result. Exceeding the limit returns an MCP error instead of a truncated success. The limit must be positive; applications serving larger tool results can explicitly raise it.

func WithMaxBodyBytes

func WithMaxBodyBytes(n int64) Option

WithMaxBodyBytes sets the maximum request body size. Requests that exceed this limit are rejected with HTTP 413 Request Entity Too Large before reaching any handler. Default: DefaultMaxBodyBytes (4 MiB). Pass 0 to disable the limit (not recommended in production).

func WithMiddleware

func WithMiddleware(mws ...middleware.Middleware) Option

WithMiddleware adds middlewares to the server

func WithOpenAPI

func WithOpenAPI(spec *openapipkg.Spec) Option

WithOpenAPI registers a GET /openapi.json handler that serves spec as JSON. The spec is serialised once at startup — mutations to spec after this call are not reflected. Build the spec with openapi.New() and optionally enrich it with openapi.ScanDir() before passing it here.

spec := openapi.New(cfg.AppName, cfg.Version)
srv := server.New(cfg, server.WithOpenAPI(spec))

The canonical fleet endpoints (/health, /version, /selftest) are already included by openapi.New() — services do not need to add them manually.

func WithPromRoute

func WithPromRoute(fn func(*http.Request) string, limit int) Option

WithPromRoute sets what the Prometheus HTTP collectors (http_requests_total, http_request_duration_seconds, http_response_size_bytes) put in their "route" label, and how many distinct values they keep.

fn maps a request to its route label; nil keeps the default, the raw r.URL.Path. limit is how many distinct route values are kept: the first ones seen keep their own series, and every later one is folded into "_other" for the life of the process. limit <= 0 keeps the default, 512. Either argument may be left at its zero value to change only the other.

The default is unchanged, so a dashboard that selects on today's route label keeps working until a service opts in. A service with parameterised paths should opt in: with the default, the first 512 distinct paths each get their own series and everything after that is "_other", so the label stops being useful on a busy or probed service. A router that knows the pattern can supply it (for a http.ServeMux, the pattern that its Handler method returns; it is empty for a request no route matches, and an empty route is labelled "_unknown"); otherwise return a template such as "/things/{id}" yourself.

Two things to know before choosing fn:

  • GET /metrics is unauthenticated on every server.New service, so whatever fn returns is readable by anyone who can reach the port. Under the default, a token, id or user name embedded in a path becomes a readable label value there (and an untemplated path is an unbounded stream of them); return the template, not the path.
  • graph templates paths before it records them (/{id}, /{uuid}, /{token}) and promx does not, so the two views of one request can disagree on what "the route" is. That is why this option exists; there is no shared helper, so fn has to do its own templating.

The new labelling covers requests recorded after New returns; it applies to this server only. Two server.New calls in one process share the collectors and the series, but each keeps its own route function and its own limit.

func WithReadTimeout

func WithReadTimeout(d time.Duration) Option

WithReadTimeout overrides the http.Server ReadTimeout (the deadline for reading the entire request, headers + body). Default: DefaultReadTimeout (10 s). Raise this for services that accept slow or large request bodies (e.g. streamed uploads). d <= 0 is ignored (keeps the default).

func WithSchemaVersion

func WithSchemaVersion(v int) Option

WithSchemaVersion stamps the service's current envelope schema version. Bump this monotonically whenever any response shape changes in a breaking way (field rename, removal, type change, semantic change). Additive new fields do not require a bump. See response/SCHEMA_VERSIONING.md.

func WithServerTimeouts

func WithServerTimeouts(read, write, idle time.Duration) Option

WithServerTimeouts sets all three http.Server timeouts in one call: ReadTimeout, WriteTimeout, and IdleTimeout. Any argument <= 0 is ignored, leaving that timeout at its default (DefaultReadTimeout / DefaultWriteTimeout / DefaultIdleTimeout) — so callers can raise just one or two by passing 0 for the rest:

// raise only the write deadline, keep read + idle at defaults
server.WithServerTimeouts(0, 70*time.Second, 0)

Equivalent to applying WithReadTimeout, WithWriteTimeout, and a matching idle override together.

func WithStructuredLogs

func WithStructuredLogs() Option

WithStructuredLogs switches the process to structured JSON logs (logx) when the server is created, whatever LOG_FORMAT says. It affects the whole process: the access log, slog's default logger and the standard log package.

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) Option

WithWriteTimeout overrides the http.Server WriteTimeout (the per-connection deadline for writing a response, measured from the end of the request-header read). Default: DefaultWriteTimeout (30 s).

Raise this for services that legitimately produce slow responses — e.g. a JS-render escalation through the fleet fetch-cache, where a cold chromedp render of a heavy SPA can take ~30-60 s. Without it the Go HTTP server closes the connection at 30 s mid-response and the gateway returns a spurious 502 even though the handler completed. Pass a value comfortably above the handler's own context budget. d <= 0 is ignored (keeps the default).

func WithoutRequestStats

func WithoutRequestStats() Option

WithoutRequestStats disables the default per-request reqstats middleware (Server-Timing + X-Request-Stats headers). Enabled by default for every service; opt out only if the extra headers or the cheap getrusage sample are genuinely unwanted.

type Server

type Server struct {
	Config       *config.Config
	Mux          *http.ServeMux
	Middlewares  []middleware.Middleware
	Stats        *metrics.Stats
	Deps         *depcheck.Registry
	Capabilities []client.Capability
	// SchemaVersion is the integer that monotonically increases on every
	// breaking JSON-shape change. Set via WithSchemaVersion(N); defaults
	// to DefaultSchemaVersion. Exposed at GET /schema, embedded in
	// GET /capabilities, and stamped on response.Envelope outputs.
	SchemaVersion int

	// PromHTTPCollectors is the inbound HTTP collector set, auto-
	// registered into the shared promx registry. Exposed so callers can
	// inspect it. To change the "route" label or its cap use WithPromRoute:
	// replacing this field after New has no effect, because the middleware
	// is built from the collectors New wired.
	PromHTTPCollectors *promx.HTTPCollectors
	// PromAuthCollectors is the keystore-auth collector set. Passed to
	// WithKeystoreAuth automatically so apikey_auth_total and friends
	// populate without per-service wiring.
	PromAuthCollectors *promx.AuthCollectors

	// AgentContract is the resolved contract from WithAgent /
	// WithAgentFromEmbed, stashed here (regardless of option order) so
	// WithMCP can build its MCP tool list from the same source of truth
	// that serves GET /agent.json. Zero value if neither option was used.
	AgentContract agent.Contract
	// contains filtered or unexported fields
}

func New

func New(cfg *config.Config, opts ...Option) *Server

New creates a new Server with optional configuration

Example

New wires the whole fleet stack (request id, logging, body limit, metrics, /health, /version, /selftest, ...). Start blocks until SIGTERM and then drains, so this example is compiled but not run.

package main

import (
	"net/http"

	"github.com/baditaflorin/go-common/config"
	"github.com/baditaflorin/go-common/server"
)

func main() {
	cfg := config.Load("go_example", "v0.1.0")
	srv := server.New(cfg)
	srv.Mux.HandleFunc("/api/v1/hello", func(w http.ResponseWriter, r *http.Request) {
		_, _ = w.Write([]byte("hello"))
	})
	// log.Fatal(srv.Start())
}

func (*Server) BeginDrain

func (s *Server) BeginDrain()

BeginDrain triggers the graceful-drain sequence. Returns immediately after flipping the readiness flag; the drain period and shutdown run in a background goroutine. Calling BeginDrain a second time signals "impatience" — the drain-period sleep is aborted and shutdown begins immediately. Safe to call from any goroutine.

If WithGracefulDrain was not configured this is a no-op (the server will shut down via the default os.Interrupt handling instead). Tests can configure the drain explicitly and exercise this method to verify behavior without sending real signals.

func (*Server) DrainDone

func (s *Server) DrainDone() <-chan struct{}

DrainDone returns a channel that closes once the drain goroutine has finished its shutdown call. Returns nil when drain is not configured (callers must guard the nil receive — a nil channel blocks forever). Mainly useful in tests to assert the drain ran to completion without racing on internal state.

func (*Server) Handle

func (s *Server) Handle(pattern string, handler http.Handler)

Handle registers handler for pattern on s.Mux, as s.Mux.Handle does, and records the pattern so that Start can check it against the public path prefixes declared with WithKeystoreAuthPublicPrefixes. The route is meant to be protected by the keystore gate: if a declared prefix covers it, requests to it skip the gate, and Start returns an error instead of serving it without a key.

Routes registered directly on s.Mux are not recorded and not checked. Use HandlePublic for a route that is meant to be served without a key.

func (*Server) HandleFunc

func (s *Server) HandleFunc(pattern string, handler func(http.ResponseWriter, *http.Request))

HandleFunc is Handle for a handler function.

func (*Server) HandlePublic

func (s *Server) HandlePublic(pattern string, handler http.Handler)

HandlePublic registers handler for pattern on s.Mux, like Handle, for a route that is meant to be served without a key: it is what sits under a prefix declared with WithKeystoreAuthPublicPrefixes. Start does not count it against the declared prefixes. It does not make the route public by itself: declare the prefix that covers it.

func (*Server) HandlePublicFunc

func (s *Server) HandlePublicFunc(pattern string, handler func(http.ResponseWriter, *http.Request))

HandlePublicFunc is HandlePublic for a handler function.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the fully-wrapped HTTP handler — middleware chain applied to s.Mux, plus the fleet-default /metrics and /selftest shims. Useful for tests (httptest.NewServer(srv.Handler())) and for callers that want to embed the server in a non-stdlib listener. Start() uses this internally.

Every response it sends carries X-Service-Name (Config.AppName) and X-Service-Version (Config.Version), whatever answered it; a handler cannot replace them (identity.go).

func (*Server) IsDrainingForTest

func (s *Server) IsDrainingForTest() bool

IsDrainingForTest reports whether BeginDrain has flipped the readiness flag. Test-only helper that avoids exposing the internal atomic.

func (*Server) SetShutdownFnForTest

func (s *Server) SetShutdownFnForTest(fn func(ctx context.Context) error) bool

SetShutdownFnForTest wires a custom shutdown closure into the drain state without going through Start(). Tests use this to attach an httptest.Server's shutdown, exercise BeginDrain, and assert the closure ran with the expected timeout budget. Returns false if drain was not configured. Not for production use.

func (*Server) Start

func (s *Server) Start() error

Start listens on PORT, serves requests, and performs a graceful shutdown when SIGTERM or SIGINT is received. It blocks until the server has drained all in-flight requests or the drain timeout elapses, then returns. A listen failure (the port is taken, for example) is returned as an error, so handle it:

if err := srv.Start(); err != nil {
    log.Fatal(err)
}

Listen failures are returned with or without WithGracefulDrain, after deferred cleanup runs. Run and RunTier log any error Start returns and exit with status 1, so callers that use Start directly must handle its result too.

Before it listens, Start checks the routes registered through Handle, HandleFunc and the server's own mounts against the prefixes declared with WithKeystoreAuthPublicPrefixes, and returns an error, without listening, if a keystore-gated route lies under one: the gate would let requests to it through without a key.

Jump to

Keyboard shortcuts

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