Watch Aspire live streamsDocsTry Aspire

Set up Go apps in the AppHost

Go logo

This article is the reference for the Aspire Go hosting integration. It enumerates the AppHost APIs that you use to orchestrate Go applications in your AppHost project, with examples for AppHost.cs, apphost.mts, and apphost.go.

If you’re new to the Go integration, start with the Get started with the Go integration guide.

To start building an Aspire app that uses Go, install the 📦 Aspire.Hosting.Go NuGet package:

Terminal
aspire add go

Learn more about aspire add in the command reference.

This updates your aspire.config.json with the Go hosting integration package:

aspire.config.json
{
"packages": {
"Aspire.Hosting.Go": "17.0.0"
}
}

Migrate from the Community Toolkit package

Section titled “Migrate from the Community Toolkit package”

For Aspire 13.4 and later, use the official package as the recommended approach for Go hosting:

  1. Remove CommunityToolkit.Aspire.Hosting.Golang from the AppHost.
  2. Add Aspire.Hosting.Go.
  3. Keep Go resources on AddGoApp / addGoApp and review the official parameters for appDirectory, packagePath, build tags, linker flags, compiler flags, and the race detector.

The deprecated Toolkit package shouldn’t be added to new AppHosts. The examples in this article use only the official Aspire.Hosting.Go APIs.

Use AddGoApp / addGoApp to add a Go application to your AppHost. By default, Aspire runs go run . from the application directory.

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const api = await builder.addGoApp('api', './api');
await api.withHttpEndpoint({ port: 8080, env: 'PORT' });
await api.withExternalHttpEndpoints();
await builder.build().run();

The other Go examples on this page show only the lines that go between aspire.CreateBuilder() and builder.Build().

The method accepts the following common parameters:

  • name: The name of the resource in the Aspire dashboard.
  • appDirectory: The path to the Go module root. This directory usually contains go.mod and is also the Docker build context for deployment targets that emit container build artifacts.
  • packagePath: The Go package to run or build relative to appDirectory. Defaults to ".".

Go applications commonly read the PORT environment variable set by WithHttpEndpointwithHttpEndpointWithHttpEndpoint:

main.go
package main
import (
"fmt"
"log"
"net/http"
"os"
)
func main() {
port := os.Getenv("PORT")
if port == "" {
port = "8080"
}
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "Hello from Go!")
})
log.Printf("Listening on :%s", port)
log.Fatal(http.ListenAndServe(":"+port, nil))
}

Use appDirectory for the Go module root, and use packagePath when the main package is under a subdirectory such as cmd/server.

For a common layout like this:

Go app layout
api/
|-- go.mod
|-- internal/
`-- cmd/
`-- server/
`-- main.go

Configure the AppHost to run go run ./cmd/server from ./api:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const api = await builder.addGoApp('api', './api', {
packagePath: './cmd/server',
});
await api.withHttpEndpoint({ env: 'PORT' });
await builder.build().run();

The same packagePath is used for local run mode, headless Delve debugging, and publish-time go build.

Go build-time options are parameters on AddGoApp / addGoApp. Aspire passes them to go run during local development and to go build when it generates a Dockerfile for publish.

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const api = await builder.addGoApp('api', './api', {
packagePath: './cmd/server',
buildTags: ['netgo', 'integration'],
ldFlags: '-X main.version=1.2.3 -s -w',
gcFlags: 'all=-N -l',
raceDetector: true,
});
await builder.build().run();

The options map to Go command-line flags:

  • buildTags: Adds -tags=<tag1>,<tag2>.
  • ldFlags: Adds -ldflags=<value>.
  • gcFlags: Adds -gcflags=<value>.
  • raceDetector: Adds -race in local run mode. The generated Dockerfile excludes -race because race detection requires CGO and publish builds create a static Linux binary.

Use WithAppArgswithAppArgsWithAppArgs to pass arguments to the Go program after the package path.

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const api = await builder.addGoApp('api', './api');
await api.withAppArgs(['--config', 'dev.yaml']);
await api.withHttpEndpoint({ env: 'PORT' });
await builder.build().run();

In normal run mode, this produces a command like go run . --config dev.yaml. In headless Delve mode, Aspire passes the app arguments after Delve’s -- separator.

The Go integration can run common module and static analysis commands before the app starts. These helpers create setup resources in run mode and make the Go app wait for them to complete.

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const api = await builder.addGoApp('api', './api');
await api.withModTidy();
await api.withModVendor();
await api.withModDownload();
await api.withVetTool();
await api.withHttpEndpoint({ env: 'PORT' });
await builder.build().run();

The helper methods run these commands:

When multiple module helpers are configured, Aspire orders them so dependency-changing steps complete before later module cache or vendor steps.

These helpers run as separate resources, so they use the platform defaults for certificate trust: CertificateTrustScope.System on macOS and Windows, and CertificateTrustScope.Append on Linux. On macOS and Windows, the certificate bundle Aspire generates includes the system root certificates, so Go can still download modules over TLS. Certificate verification remains enabled.

Trust scope overrides that you set on the Go app, such as .WithCertificateTrustScope(...), aren’t inherited by these helper resources.

Go app resources automatically support VS Code debugging when the Go extension for Visual Studio Code (golang.go) is installed.

The Aspire VS Code extension detects the golang.go extension and, when you start your AppHost in debug mode, launches the Go debugger via dlv-dap. No additional configuration is required beyond AddGoApp / addGoApp. Any buildTags, ldFlags, or gcFlags configured on the resource are automatically forwarded to Delve as build flags, so the debugger compiles your program with the same flags used during normal development.

Starting with Aspire 17.0, you can attach the VS Code debugger to a Go resource that’s already running. Attach requires Aspire extension v1.25.0 or later, the golang.go extension, and Delve (dlv).

Start the AppHost with Run Without Debugging or aspire start. In both cases, Aspire runs the resource with go run. Then right-click the running Go resource in the Aspire view and select Attach debugger. The debugger attaches to your app process, not to go run. Attaching and detaching don’t restart the resource or the AppHost.

Source breakpoints need the symbols and DWARF debug information in your binary. Local AddGoApp / addGoApp launches keep this information by default, including under aspire start, so no opt-in is required. Aspire preserves other linker options from GOFLAGS, but explicit -s and -w flags take precedence. Published Docker builds keep the linker flags that you configure.

When you set custom ldFlags, include -s=false -w=false, and don’t pass -s or -w. For example, the -s -w flags in Configure build options strip the information that source breakpoints need. For predictable stepping, also set gcFlags: "all=-N -l" to turn off compiler optimizations and inlining:

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const api = await builder.addGoApp('api', './api', {
ldFlags: '-X main.version=1.2.3 -s=false -w=false',
gcFlags: 'all=-N -l',
});
await builder.build().run();

Attach isn’t available for resources that use WithDelveServer / withDelveServer, because those resources run under a headless Delve server instead.

For attach steps, troubleshooting, and Linux and macOS permission requirements, see Attach a debugger to a running resource.

For GoLand, VS Code attach mode, or another Delve-compatible client, use WithDelveServer / withDelveServer. This replaces the application command with a headless Delve server, such as dlv --headless=true --listen=127.0.0.1:2345 --api-version=2 debug ..

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const api = await builder.addGoApp('api', './api');
await api.withDelveServer();
await api.withHttpEndpoint({ port: 8080, env: 'PORT' });
await builder.build().run();

By default the Delve server accepts a single debugger client on port 2345. To accept multiple clients, keep the server running after a client disconnects, or configure additional Delve flags, pass a DelveServerOptions instance:

apphost.mts
const api = await builder.addGoApp('api', './api');
await api.withDelveServer({
acceptMultiClient: true,
continueOnStart: true,
log: true,
logOutput: 'rpc,dap,debugger',
});
OptionDefaultDelve behavior
Port2345Sets the loopback listener port.
AcceptMultiClientfalsePasses --accept-multiclient when enabled.
OnlySameUsernullPasses --only-same-user=true or --only-same-user=false when set.
ContinueOnStartfalsePasses --continue when enabled.
LogfalsePasses --log when enabled.
LogOutputnullPasses --log-output=<components> when logging is enabled and components are specified.

Start your attach configuration after the Go resource is running in the Aspire dashboard. For GoLand, create a Go Remote configuration with host localhost and port 2345. For VS Code attach mode, add a launch configuration like this:

.vscode/launch.json
{
"name": "Attach to api",
"type": "go",
"request": "attach",
"mode": "remote",
"host": "localhost",
"port": 2345
}

When a publisher or deployment target emits container build artifacts for a Go app, Aspire uses the appDirectory as the Docker build context:

  • If the app directory already contains a Dockerfile, Aspire uses it.
  • If no Dockerfile exists, Aspire generates a multi-stage Dockerfile.
  • The generated Dockerfile uses a golang:<version>-alpine build image by default. Aspire detects the Go version from go.mod, preferring a toolchain directive over the go directive when both are present.
  • The build stage runs go mod download, caches the module and build caches, and builds a static Linux binary with CGO_ENABLED=0 and GOOS=linux.
  • The runtime stage uses a small runtime image, installs certificate and time zone data for Alpine-based images, creates a non-root app user, and starts the compiled binary.
  • The generated go build command uses the same packagePath, buildTags, ldFlags, and gcFlags configured on the Go app resource. It intentionally excludes raceDetector for publish builds.

An existing Dockerfile is used as-is, so Aspire can’t apply a non-default packagePath to it. When the container has no explicit entrypoint and packagePath resolves to something other than the app directory, publishing logs a warning that names the resource, the requested package, and the Dockerfile path. The warning doesn’t fail the publish, because a custom Dockerfile can already build and run the requested package. Build tags, linker flags, compiler flags, and the race detector don’t trigger it.

To silence the warning, set an explicit container entrypoint with PublishAsDockerFile(c => c.WithEntrypoint(...)), or rename the Dockerfile so Aspire generates one. The warning comes from a pipeline step, so a manifest-only publish (--publisher manifest) doesn’t show it.

For private modules, use WithGoPrivatewithGoPrivateWithGoPrivate to configure the generated Dockerfile with GOPRIVATE and BuildKit secret-based authentication. This setting only affects generated Dockerfiles; local run mode continues to use the developer’s local Go and Git credentials.

apphost.mts
import { createBuilder } from './.aspire/modules/aspire.mjs';
const builder = await createBuilder();
const api = await builder.addGoApp('api', './api');
await api.withGoPrivate(['github.com/myorg'], 'github.com');
await builder.build().run();

For more information about publishing Aspire apps, see Deployment overview.

The Aspire.Hosting.Go integration works from C#, TypeScript, and Go AppHosts. A Go AppHost calls AddGoApp through the Go SDK that the Aspire CLI generates from your aspire.config.json file.

To create a Go AppHost, see Get started with the Go AppHost. For the Go error model and optional parameters, see Go AppHost API conventions.