encore

package module
v2.0.0-beta.15 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: MPL-2.0 Imports: 13 Imported by: 1 module, 1 package

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.

README

Encore Infra SDK

This is the Encore runtime module that provides APIs and internal runtime components for running Encore applications.

Running a service

encore.Run runs a service from main until Encore shuts it down, then exits the process:

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("GET /orders/{id}", getOrder)
    encore.Run(mux)
}

It listens where Encore assigns the service (ENCORE_LISTEN_ADDR; outside Encore PORT, or 8080) over HTTP/1.1 and h2c, starts the Pub/Sub subscriptions as encore.Start does, and traces every request with tracing.Middleware: a server span named after the ServeMux pattern the request matched, or the route a handler named with tracing.SetRoute. On SIGTERM or SIGINT the server drains its in-flight requests before Encore closes the infrastructure, and the process exits with 0 if the shutdown completed in time, else 1. encore.Run(nil) runs a service with no HTTP, such as one that only handles Pub/Sub messages. encore.WithServer configures the http.Server; encore.WithoutTracing leaves tracing to the handler.

encore.Serve does the same but returns once the shutdown is complete, leaving the exit to main: nil if it completed in time, else shutdown.ErrTimeout or shutdown.ErrFailed. Use it when main has work to do after the service stops, or deferred calls that must run.

Telemetry

Ordinary Go services need no OpenTelemetry setup:

ctx, span := tracing.Start(ctx, "place_order")
defer span.End()
span.SetAttributes(tracing.String("order.id", id))
if err := save(ctx); err != nil {
    span.RecordError(err) // Exception event and error status.
    slog.ErrorContext(ctx, "Order failed", "err", err)
    return err
}

Import sdk.encore.dev/v2/tracing and log/slog. Pass the returned context to infrastructure calls, nested work and slog's context methods. The default slog handler records active trace/span IDs; env.NewLogHandler configures custom loggers. Native counters and histograms remain in sdk.encore.dev/v2/metrics.

For net/http, encore.Run and encore.Serve trace every request with tracing.Middleware. A main that serves otherwise wraps its router once:

srv := &http.Server{Handler: tracing.Middleware(mux)}

It extracts W3C and Encore request context, records server spans and response status, and names each span by method and the ServeMux pattern the request matched, its method and host left out: the pattern GET example.com/orders/{id} names the span GET /orders/{id}. A request no pattern matched, such as a 404 or 405, is named by its method only. With another router, call tracing.SetRoute(ctx, "/orders/{id}") from its middleware once it has matched; that route wins over the pattern. Spans never use raw paths or queries: the URL path, query and User-Agent are recorded only as deployed policy redacts them. 5xx responses, write errors and panics mark errors; panics propagate. An uncommitted panic has no recorded HTTP status.

Use http.ResponseController for flush, hijack, deadlines and full-duplex operations. It follows the original writer's unwrap chain and returns http.ErrNotSupported when unavailable. The adapter has a fixed method set: optional-interface assertions do not detect underlying capabilities. Direct Flush, FlushError, Hijack, Push, ReadFrom and WriteString remain available. Flush calls the original Flusher when directly available, otherwise uses controller resolution; it ignores errors. FlushError and controller flush prefer the original FlushError over Flush. Unsupported flush, hijack and push return http.ErrNotSupported where the signature allows. ReadFrom and WriteString delegate to the original methods when present, otherwise copy through writes. Uncommitted ReadFrom sources are wrapped: nonempty reads count as write attempts even if rejected, which can disable zero-copy paths. Deprecated CloseNotifier is not exposed; use Request.Context() for cancellation.

Advanced instrumentation can pass tracing.TracerProvider(), tracing.Propagator() and metrics.MeterProvider() explicitly to OTel libraries, or explicitly install them as globals. Encore changes no OTel globals. Native and explicit spans share parents in either direction; do not double-wrap HTTP handlers with native and OTel server instrumentation. Propagator injects only trace context; service transports forward Encore Request Context.

Paired runnable examples serve the same orders workload with native APIs and explicit OTel providers.

Public API generation

Using the Public API generator tool the encore.dev Public API is generated from this package. However, the following are not included in the public API:

  • The runtime package, as that is considered to be an internal implementation detail of Encore and it's API is considered unstable.
  • Any internal packages, such as pubsub/internal, as those can't be accessed outside the Encore runtime.
  • Any files with the suffix of _internal.go as those are implementation details and not expected to be called from outside an Encore application
  • Any files with the suffix of _test.go as those simply form the testsuite for the runtime's implementation
  • Any functions, types or variables which are not exported from the package (unless the comment //publicapigen:keep is present)
  • The body of any functions, each body is replaced with a panic() call.

Telemetry redaction

redaction.New() applies deployed policy to telemetry copies, never live traffic. Import sdk.encore.dev/v2/redaction:

view := redaction.New().HTTP(r.Method, r.URL.RequestURI())
url, err := view.RequestURL() // Route, Path, Query are independently nullable.
if err != nil {
    return err
}
_ = url
safe, err := view.Request(redaction.HTTPInput{Headers: r.Header, Body: body})
if err != nil {
    return err
}
_ = safe // Record only safe.Headers and safe.Body.

Response(HTTPInput) handles response headers and body together. Nil input body skips capture and returns nil Body; a non-nil empty slice captures an empty body. A captured Payload is recorded, withheld, or omit. Never substitute original values for absent results or errors.

GRPC(methodDescriptor).Request(GRPCInput{Metadata: metadata, Message: message}) returns safe metadata and an optional message payload. Response(GRPCResponseInput{Metadata: metadata, Message: message, Trailers: trailers}) also returns safe trailers. Metadata and trailers use http.Header in HTTP wire form, including base64 for binary entries. Messages are unframed protobuf bytes; nil skips capture, while an empty non-nil slice captures an empty message. Descriptors supply service, method and streaming direction. Streaming messages are withheld by policy. Topic(name).Publish(bytes) and Topic(name).Delivery(subscription, bytes) return a Payload.

Documentation

Overview

Package encore is the root of Encore's Go SDK, which Encore applications are built against. It holds Run and Serve, which run a service from main until Encore shuts it down, serving its net/http handler, and Start, which starts the runtime and its subscriptions for a main that serves some other way; the rest of the SDK is its packages.

Encore's API framework, a service's typed endpoints declared with an //encore:api directive, is a module of its own built on this one: framework.encore.dev.

For more information visit https://encore.dev/docs.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(h http.Handler, opts ...ServeOption)

Run runs the service until Encore shuts it down, serving h as Serve does, and then exits the process: with code 0 if the shutdown completed in time, else 1, having written why to stderr. It never returns, so main's deferred calls don't run; a main with work to do once the service has stopped calls Serve instead.

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("GET /orders/{id}", getOrder)
	encore.Run(mux)
}

func Serve

func Serve(h http.Handler, opts ...ServeOption) error

Serve runs the service until Encore shuts it down, and returns once the shutdown is complete: nil if it completed in time, else why not. The process's exit is main's, as Run makes it for a main with nothing more to do:

if err := encore.Serve(mux); err != nil {
	log.Fatal(err)
}

With a handler, it serves h where Encore assigns the service, ENCORE_LISTEN_ADDR (outside Encore on the port PORT names, or 8080), over HTTP/1.1 and unencrypted HTTP/2 (h2c). Each request has its trace and Request Context in its context, and a server span named after the route it matched, as tracing.Middleware records it. With nil, as for a service that only handles Pub/Sub messages, it runs the rest.

It listens, starts the runtime and the service's subscriptions as Start does, and serves. On SIGTERM or SIGINT, or shutdown.Begin, the server takes no new requests, and Encore closes the infrastructure only once the requests in flight are answered and the app's other drains have returned (see sdk.encore.dev/v2/shutdown), or the time to drain is over. A second signal stops waiting for them. Serve then returns shutdown.ErrTimeout or shutdown.ErrFailed if the shutdown did not complete in time or its cleanup failed.

It returns at once if it cannot listen, as when the address is taken. If serving fails later, it shuts down as on a signal and returns the failure.

Outside Encore, as under a plain go run, it records no spans, and handles SIGTERM and SIGINT itself: the server answers the requests in flight, and the drains registered with shutdown.OnShutdown run.

func Start

func Start()

Start starts the Encore runtime and the app's Pub/Sub subscriptions. Call it in main, once the app is ready to handle messages:

func main() {
	encore.Start()
	// …serve the app's API…
}

Other infrastructure starts on first use, so a database or bucket needs no Start. A subscription is never used, only handed messages: it handles none until Start is called, and Encore logs a warning when an app that declares subscriptions has not called it. Shortly after Start, the runtime warns of each subscription the service hosts that has no handler, such as one declared in a package the program does not import.

Serve and Run call Start, for a service they serve.

Later calls do nothing. Outside Encore, as under a plain go run, there is nothing to start.

Types

type ServeOption

type ServeOption func(*runConfig)

ServeOption configures Serve and Run.

func WithServer

func WithServer(fn func(*http.Server)) ServeOption

WithServer has fn configure the http.Server Serve serves, before it serves: its timeouts, ErrorLog or ConnContext, say. Its Addr and Handler are Serve's, and are set after fn.

func WithoutTracing

func WithoutTracing() ServeOption

WithoutTracing serves the handler without a server span for its requests: for one that traces them itself, as with otelhttp. Requests then have no trace or Request Context in their context unless the handler extracts them, as otelhttp does with tracing.Propagator.

Directories

Path Synopsis
Package appruntime provides internal functionality for use by Encore to run Encore applications.
Package appruntime provides internal functionality for use by Encore to run Encore applications.
clients
Package clients sends the calls of the service clients Encore generates, which fail with a *services.CallError and take services.CallOption values and services.ClientSettings: see sdk.encore.dev/v2/services.
Package clients sends the calls of the service clients Encore generates, which fail with a *services.CallError and take services.CallOption values and services.ClientSettings: see sdk.encore.dev/v2/services.
exported/stack
Package stack collects stack traces.
Package stack collects stack traces.
infrasdk/sdkcore
Package sdkcore links the Encore SDK core Rust library (crates/encore_sdk_core) over its C ABI and exposes its infrastructure integrations — secrets, SQL, Pub/Sub, object storage, and metrics — to the Go SDK.
Package sdkcore links the Encore SDK core Rust library (crates/encore_sdk_core) over its C ABI and exposes its infrastructure integrations — secrets, SQL, Pub/Sub, object storage, and metrics — to the Go SDK.
shared/appconf
Package appconf answers whether the process runs under Encore.
Package appconf answers whether the process runs under Encore.
shared/cloud
Package cloud contains some helpers for referring to different cloud implementations
Package cloud contains some helpers for referring to different cloud implementations
shared/drain
Package drain holds the app's shutdown drains, registered with sdk.encore.dev/v2/shutdown.OnShutdown and run when the shutdown begins.
Package drain holds the app's shutdown drains, registered with sdk.encore.dev/v2/shutdown.OnShutdown and run when the shutdown begins.
shared/serverspan
Package serverspan is how the handlers a request reaches tell the server span Encore started for it, as encore.Serve does for every request, what they know of it: the route it matched, and whether it is sensitive.
Package serverspan is how the handlers a request reaches tell the server span Encore started for it, as encore.Serve does for every request, what they know of it: the route it matched, and whether it is sensitive.
Package config provides typed application config: values a service reads, written in TOML or JSON files beside the code, and changed while the app runs.
Package config provides typed application config: values a service reads, written in TOML or JSON files beside the code, and changed while the app runs.
Package cron provides support for cron jobs: recurring tasks that run on a schedule.
Package cron provides support for cron jobs: recurring tasks that run on a schedule.
Package encoretest gives each test infrastructure of its own: databases, Redis databases and buckets no other test sees, and a record of what it published.
Package encoretest gives each test infrastructure of its own: databases, Redis databases and buckets no other test sees, and a record of what it published.
system
Package system is what only a system test does: wait for the app to settle, reach it with a client of the test's own, and read what it did.
Package system is what only a system test does: wait for the app to settle, reach it with a client of the test's own, and read what it did.
system/chromedp
Package encorechromedp drives a system test's browser with chromedp.
Package encorechromedp drives a system test's browser with chromedp.
Package env describes the running Encore application: its environment, build and deployment, and its gateways and frontends.
Package env describes the running Encore application: its environment, build and deployment, and its gateways and frontends.
Package frontends says where the app's frontends are reached.
Package frontends says where the app's frontends are reached.
Package gateway runs code in an application's gateway: Middleware that authenticates, authorizes, limits, logs or meters the public requests the gateway serves, before they reach a service and after they return.
Package gateway runs code in an application's gateway: Middleware that authenticates, authorizes, limits, logs or meters the public requests the gateway serves, before they reach a service and after they return.
Package gateways says where the app's gateways are reached.
Package gateways says where the app's gateways are reached.
internal
clientcall
Package clientcall prepares the calls of the service clients Encore generates, for sdk.encore.dev/v2/appruntime/clients and its gRPC package alike: where a call goes, with which headers, through which transport and by when.
Package clientcall prepares the calls of the service clients Encore generates, for sdk.encore.dev/v2/appruntime/clients and its gRPC package alike: where a call goes, with which headers, through which transport and by when.
reqfields
Package reqfields holds the Request Context of a context in its wire form, and the configs of the fields declared in this process: what package reqctx keeps typed, and what tracing, pubsub and services move.
Package reqfields holds the Request Context of a context in its wire form, and the configs of the fields declared in this process: what package reqctx keeps typed, and what tracing, pubsub and services move.
secretplaceholder
Package secretplaceholder marks the secret placeholders in a config's value as the runtime's, so that a secrets.Secret decoded from JSON names a secret only when config decodes it.
Package secretplaceholder marks the secret placeholders in a config's value as the runtime's, so that a secrets.Secret decoded from JSON names a secret only when config decodes it.
svclookup
Package svclookup lets the generated service clients reach the app's services as sdk.encore.dev/v2/services does, which sets its variables when it is initialized: the generated clients import services, so they are set before any client is used.
Package svclookup lets the generated service clients reach the app's services as sdk.encore.dev/v2/services does, which sets its variables when it is initialized: the generated clients import services, so they are set before any client is used.
systest
Package systest is what encoretest and encoretest/system share of system tests: how a test that ended says so to its test session.
Package systest is what encoretest and encoretest/system share of system tests: how a test that ended says so to its test session.
testruntime
Package testruntime hands the SDK core a runtime config in tests.
Package testruntime hands the SDK core a runtime config in tests.
testscope
Package testscope is which test a resource call belongs to, for the resource packages to use the test's own instances: the scope encoretest.Begin puts on the context, or, for a call whose context has none, the test whose goroutine makes it (see Scope.ClaimGoroutine), or else the one test that is running.
Package testscope is which test a resource call belongs to, for the resource packages to use the test's own instances: the scope encoretest.Begin puts on the context, or, for a call whose context has none, the test whose goroutine makes it (see Scope.ClaimGoroutine), or else the one test that is running.
teststop
Package teststop stops a test's child process as a shutdown signal does: SIGTERM on Unix, and on Windows, which has no SIGTERM, Ctrl-Break, which Go delivers as os.Interrupt (SIGINT) and the SDK shuts down on as it does on SIGTERM.
Package teststop stops a test's child process as a shutdown signal does: SIGTERM on Unix, and on Windows, which has no SIGTERM, Ctrl-Break, which Go delivers as os.Interrupt (SIGINT) and the SDK shuts down on as it does on SIGTERM.
Package metrics records metrics: counters, gauges and histograms of what an app does.
Package metrics records metrics: counters, gauges and histograms of what an app does.
Package pubsub provides Pub/Sub topics and subscriptions.
Package pubsub provides Pub/Sub topics and subscriptions.
Package redaction applies deployed policy to telemetry copies, not live data.
Package redaction applies deployed policy to telemetry copies, not live data.
Package reqctx provides Request Context: typed fields that travel with a request to every service it reaches, such as the user it is made for.
Package reqctx provides Request Context: typed fields that travel with a request to every service it reaches, such as the user it is made for.
Package secrets provides access to an application's secrets.
Package secrets provides access to an application's secrets.
Package services calls the app's other services: it resolves their base URLs, and sends them the trace and Request Context of the calls made to them.
Package services calls the app's other services: it resolves their base URLs, and sends them the trace and Request Context of the calls made to them.
grpcclient
Package grpcclient holds the streams of the gRPC clients Encore generates, and sends their calls: in the gRPC protocol, over HTTP/2, through sdk.encore.dev/v2/services, so that they carry the trace and Request Context to the app's services.
Package grpcclient holds the streams of the gRPC clients Encore generates, and sends their calls: in the gRPC protocol, over HTTP/2, through sdk.encore.dev/v2/services, so that they carry the trace and Request Context to the app's services.
Package shutdown lets an app take part in Encore's graceful shutdown, with the app's main in charge of the process.
Package shutdown lets an app take part in Encore's graceful shutdown, with the app's main in charge of the process.
storage
clickhouse
Package clickhouse provides Encore services access to their ClickHouse databases.
Package clickhouse provides Encore services access to their ClickHouse databases.
objects
Package objects provides Encore applications with the ability to create and use Object Storage buckets (like for example Amazon S3) for storing and retrieving files in a cloud-agnostic manner.
Package objects provides Encore applications with the ability to create and use Object Storage buckets (like for example Amazon S3) for storing and retrieving files in a cloud-agnostic manner.
postgres
Package postgres provides Encore services direct access to their Postgres databases.
Package postgres provides Encore services direct access to their Postgres databases.
postgres/sqlerr
Package sqlerr provides a set of common error codes for SQL datbaases.
Package sqlerr provides a set of common error codes for SQL datbaases.
redis
Package redis provides Redis databases.
Package redis provides Redis databases.
redis/internal/gencommands command
Command gencommands writes the redis package's command groups, commands_gen.go, from the table in table.go.
Command gencommands writes the redis package's command groups, commands_gen.go, from the table in table.go.
Package tracing records spans through Encore's telemetry pipeline.
Package tracing records spans through Encore's telemetry pipeline.
internal/testhook
Package testhook holds the tracer provider tracing.TracerProvider returns in place of the runtime's while one is set: tracingtest records Encore's own spans with it.
Package testhook holds the tracer provider tracing.TracerProvider returns in place of the runtime's while one is set: tracingtest records Encore's own spans with it.
tracingtest
Package tracingtest records spans without the Encore runtime, for tests of code that traces.
Package tracingtest records spans without the Encore runtime, for tests of code that traces.

Jump to

Keyboard shortcuts

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