diff --git a/src/frontend/config/sidebar/docs.topics.ts b/src/frontend/config/sidebar/docs.topics.ts index 7a78693ec2..aadb057d41 100644 --- a/src/frontend/config/sidebar/docs.topics.ts +++ b/src/frontend/config/sidebar/docs.topics.ts @@ -1050,6 +1050,20 @@ export const docsTopics = { label: 'TypeScript', slug: 'app-host/typescript-apphost', }, + { + label: 'Go', + collapsed: false, + items: [ + { + label: 'Get started', + slug: 'app-host/go-apphost', + }, + { + label: 'API conventions', + slug: 'app-host/go-apphost-conventions', + }, + ], + }, ], }, { diff --git a/src/frontend/src/content/docs/app-host/go-apphost-conventions.mdx b/src/frontend/src/content/docs/app-host/go-apphost-conventions.mdx new file mode 100644 index 0000000000..9eb29923fc --- /dev/null +++ b/src/frontend/src/content/docs/app-host/go-apphost-conventions.mdx @@ -0,0 +1,94 @@ +--- +title: Go AppHost API conventions +seoTitle: Go AppHost API conventions for the Aspire SDK +description: Learn how the generated Aspire Go SDK names methods, passes optional parameters with options structs, reports errors through handles, and cancels a running AppHost. +--- + +The Aspire CLI generates the Go SDK from the integrations in your `aspire.config.json` file, and every integration follows the same conventions. The examples on this page use a `builder` from `aspire.CreateBuilder()`, as in [Get started with the Go AppHost](/app-host/go-apphost/). + +## Names and handles + +Every integration adds its methods to the `aspire` package, and method names are PascalCase. The TypeScript method `addRedis` is `AddRedis` in Go. + +Methods that add a resource, such as `AddRedis` and `AddGoApp`, return a _handle_. A handle is a Go interface that stands for the resource in the app model, for example `aspire.RedisResource`. Methods that configure a resource return the same handle type, so calls chain. Every handle has an `Err() error` method, which is described in [Errors](#errors). + +## Optional parameters + +Optional parameters go in a trailing variadic options argument. Leave it out to use the defaults. The argument is usually a struct named `Options`, such as `*aspire.WithHttpEndpointOptions`. Methods with the same name share one struct when their optional parameters match. If they don't match, or if another type already has the name, the name starts with the type that defines the method, such as `*aspire.ExecutableResourceWithVolumeOptions` for `WithVolume` on a Go app. A few methods take an existing type instead, such as `*aspire.DelveServerOptions` for `WithDelveServer`, and that type declares its own field types. + +In a `Options` struct, scalar fields (string, number, bool, and enum) are pointers, so a field that you don't set stays `nil`. Use `aspire.StringPtr`, `aspire.BoolPtr`, and `aspire.Float64Ptr` to create the values. Numeric fields are `*float64`. Slice, map, callback, and `any` fields can already be `nil`, so they aren't pointers. For example, `AddGoAppOptions.BuildTags` is a `[]string`. + +```go title="apphost.go" +builder.AddGoApp("api", "./api"). + WithHttpEndpoint(&aspire.WithHttpEndpointOptions{ + Port: aspire.Float64Ptr(8080), + Env: aspire.StringPtr("PORT"), + }) +``` + +The [`WithHttpEndpoint` API reference](/reference/api/go/aspire.hosting/withhttpendpoint/) describes each field of `WithHttpEndpointOptions`. + +## Errors + +The SDK reports errors in two ways. + +Methods that add or configure a resource return a handle instead of an error. The handle records the first failure, later calls on it do nothing, and `Err()` returns the recorded error. A child resource, such as a database that you add to a server, inherits the error of its parent, so checking the last handle in a chain is enough: + +```go title="apphost.go" +db := builder.AddPostgres("postgres").AddDatabase("postgresdb") +if err := db.Err(); err != nil { + log.Fatal(aspire.FormatError(err)) +} +``` + +A failed `Add` call records its error on the handle that it returns, not on the builder, so `builder.Err()` doesn't report it. To check several resources at once, put them in a slice of `aspire.Resource`: + +```go title="apphost.go" +cache := builder.AddRedis("cache") +api := builder.AddGoApp("api", "./api").WithReference(cache) + +for _, resource := range []aspire.Resource{cache, api} { + if err := resource.Err(); err != nil { + log.Fatal(aspire.FormatError(err)) + } +} +``` + +Methods that return a value return a `(T, error)` pair, and `Build` and `Run` return an `error`: + +```go title="apphost.go" +dir, err := builder.AppHostDirectory() +if err != nil { + log.Fatal(aspire.FormatError(err)) +} + +log.Println("AppHost directory:", dir) +``` + +`aspire.FormatError` turns an error into a message that is ready to log. When the AppHost server returns an error for a call, the error is an `*aspire.CapabilityError`, and `FormatError` adds its error code and the capability that failed. Use `errors.As` and the `Code`, `Message`, and `Capability` methods to read these values yourself. For any other error, `FormatError` returns `err.Error()`. + +## Cancellation + +A method that accepts a cancellation token takes it in its options struct. For example, `aspire.RunOptions` has a `CancellationToken` field. Create a token with `aspire.NewCancellationToken`, pass it in the options, and call its `Cancel` method to cancel the call: + +```go title="apphost.go" +app, err := builder.Build() +if err != nil { + log.Fatal(aspire.FormatError(err)) +} + +// Cancel the Run call if the AppHost is still running after an hour. +token := aspire.NewCancellationToken() +time.AfterFunc(time.Hour, token.Cancel) + +if err := app.Run(&aspire.RunOptions{CancellationToken: token}); err != nil { + log.Fatal(aspire.FormatError(err)) +} +``` + +You can't create a token from a `context.Context`. To cancel a token when an existing context ends, call `context.AfterFunc(ctx, token.Cancel)`. The token's `Context` method returns a `context.Context` that ends when the token is canceled, so you can use the same token with other Go APIs. + +## See also + +- [Get started with the Go AppHost](/app-host/go-apphost/) +- [Go API reference](/reference/api/go/) diff --git a/src/frontend/src/content/docs/app-host/go-apphost.mdx b/src/frontend/src/content/docs/app-host/go-apphost.mdx new file mode 100644 index 0000000000..ebaea02456 --- /dev/null +++ b/src/frontend/src/content/docs/app-host/go-apphost.mdx @@ -0,0 +1,364 @@ +--- +title: Get started with the Go AppHost +seoTitle: Get started with the Aspire Go AppHost and generated SDK +description: Create an Aspire Go AppHost with the Aspire CLI, learn the project layout and generated SDK, add integrations, and orchestrate apps in other languages. +--- + +import FileTree from 'starlight-plugin-icons/components/FileTree.astro'; +import LearnMore from '@components/LearnMore.astro'; + +A Go AppHost is a Go program that defines the resources in your application and how they connect. It uses the same app model as a C# AppHost, through a Go SDK that the Aspire CLI generates from the hosting integrations you install. + +## Prerequisites + +- [Go](https://go.dev/dl/) 1.26 or later, with `go` on your `PATH` +- The [Aspire CLI](/get-started/install-cli/) +- A container runtime for the Redis container in the starter template. See [Aspire prerequisites](/get-started/prerequisites/) for the supported options. + +## Create a Go AppHost + +Create a new app from the Go starter template: + +```bash title="Aspire CLI" +aspire new aspire-go-starter -n aspire-app -o aspire-app +``` + +The template creates a Go AppHost, a Go API that uses a Redis cache, and the generated SDK. To choose from the templates that support Go, run `aspire new --language go` instead. + + + See the [`aspire new` command reference](/reference/cli/commands/aspire-new/) for all options. + + +The project has the following structure: + + + +- aspire-app/ + - .aspire/modules/ Generated Go SDK (do not edit) + - aspire.go + - base.go + - go.mod + - transport.go + - .vscode/ + - extensions.json Recommended VS Code extensions + - api/ Go API that the AppHost runs + - go.mod + - main.go + - telemetry.go + - .gitignore Keeps the generated .aspire/ directory out of source control + - apphost.go Your AppHost entry point + - aspire.config.json Aspire configuration + - go.mod Go module for the AppHost + + + +## Run the AppHost + +From the project directory, start the AppHost with the Aspire CLI: + +```bash title="Aspire CLI" +aspire run +``` + +The CLI regenerates the SDK when the `packages` list has changed, starts the AppHost with `go run .`, and prints the dashboard URL. Open the dashboard to see the `cache` and `api` resources with their logs, traces, and metrics. + +:::note +Always start the AppHost with `aspire run`. The CLI sets the environment variables that the SDK uses to connect to the AppHost server, so running `go run .` on its own fails with `REMOTE_APP_HOST_SOCKET_PATH environment variable not set`. +::: + +## apphost.go + +The AppHost is a `package main` Go program. The starter template defines a Redis cache and a Go API that references it: + +```go title="apphost.go" +package main + +import ( + "log" + + "apphost/modules/aspire" +) + +func main() { + builder, err := aspire.CreateBuilder() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + + // A Redis cache the API will use for read-through caching. + cache := builder.AddRedis("cache") + + // The Go HTTP API. WithModTidy runs "go mod tidy" before launching so that + // go.sum is always up to date. Aspire injects: + // - "ConnectionStrings__cache" so the API can dial Redis. + // - "OTEL_EXPORTER_OTLP_*" env vars (via WithOtlpExporter) so traces, + // metrics, and logs flow to the Aspire dashboard. + api := builder.AddGoApp("api", "./api"). + WithModTidy(). + WithReference(cache). + WaitFor(cache). + WithHttpEndpoint(&aspire.WithHttpEndpointOptions{Env: aspire.StringPtr("PORT")}). + WithExternalHttpEndpoints(). + WithOtlpExporter() + + // Each call records its failure on the handle that it returns, so check every resource. + for _, resource := range []aspire.Resource{cache, api} { + if err := resource.Err(); err != nil { + log.Fatal(aspire.FormatError(err)) + } + } + + app, err := builder.Build() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + if err := app.Run(); err != nil { + log.Fatal(aspire.FormatError(err)) + } +} +``` + +The program has three parts: + +1. `aspire.CreateBuilder()` connects to the AppHost server that the CLI starts and returns the builder. +2. `AddRedis` and `AddGoApp` add resources. Each call returns a handle, so `WithReference`, `WaitFor`, and the other configuration methods chain onto it. +3. A loop checks the handle of each resource with `Err()`, because a failed call records its error on the handle that it returns, not on the builder. `builder.Build()` creates the application, and `app.Run()` blocks until the AppHost stops. Both return an error. See [Go AppHost API conventions](/app-host/go-apphost-conventions/#errors) for how to check handles and format errors. + +## aspire.config.json + +The `aspire.config.json` file is the central configuration for your AppHost: + +```json title="aspire.config.json" +{ + "appHost": { + "path": "apphost.go", + "language": "go" + }, + "packages": { + "Aspire.Hosting.Go": "%ASPIRE_VERSION%", + "Aspire.Hosting.Redis": "%ASPIRE_VERSION%" + }, + "profiles": { + "https": { + "applicationUrl": "https://localhost:17127;http://localhost:15118", + "environmentVariables": { + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "https://localhost:21169", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "https://localhost:22260" + } + }, + "http": { + "applicationUrl": "http://localhost:15118", + "environmentVariables": { + "ASPIRE_DASHBOARD_OTLP_ENDPOINT_URL": "http://localhost:19001", + "ASPIRE_RESOURCE_SERVICE_ENDPOINT_URL": "http://localhost:20115", + "ASPIRE_ALLOW_UNSECURED_TRANSPORT": "true" + } + } + } +} +``` + +### Key sections + +| Section | Description | +|---------|-------------| +| `appHost.path` | Path to the AppHost entry point (`apphost.go`) | +| `appHost.language` | The AppHost language (`go`) | +| `packages` | Hosting integration packages and their versions. `aspire add` updates this section. | +| `profiles` | Launch profiles with dashboard URLs and environment variables | + +## Generated SDK + +The `.aspire/modules/` directory holds the Go SDK that the CLI generates from the packages in `aspire.config.json`. The CLI creates and updates it, so don't edit these files. + +| File | Purpose | +|------|---------| +| `aspire.go` | Typed API for the installed integrations | +| `base.go` | Handle, option, and error infrastructure | +| `transport.go` | JSON-RPC transport to the AppHost server | + +The SDK is one Go package for all integrations. The AppHost's `go.mod` file maps the `apphost/modules/aspire` import path to the `.aspire/modules/` directory, so `apphost.go` imports it like any other package: + +```text title="go.mod" +module apphost + +go 1.26 + +require apphost/modules/aspire v0.0.0 + +replace apphost/modules/aspire => ./.aspire/modules +``` + +The SDK regenerates when: + +- You run `aspire add` to add or update an integration +- You run `aspire run` or `aspire start` and the package list has changed +- You run `aspire restore` + +:::tip +The starter's `.gitignore` already lists `.aspire/`. The directory holds generated files that the CLI recreates from `aspire.config.json`, so keep it out of source control. +::: + +### Restore the SDK + +Run `aspire restore` to regenerate the SDK without starting the AppHost: + +```bash title="Aspire CLI" +aspire restore --apphost apphost.go +``` + +Restore after you clone a repository, switch branches, or edit the `packages` section by hand. In CI, restore before any step that compiles the AppHost, such as `go build` or `go vet`. + +## Add integrations + +Use `aspire add` from the AppHost directory to add a hosting integration. The CLI adds the package to `aspire.config.json` and regenerates the Go SDK in `.aspire/modules/`: + +```bash title="Aspire CLI" +aspire add postgresql +``` + +The `packages` section now lists the PostgreSQL integration: + +```json title="aspire.config.json" ins={5} +{ + "packages": { + "Aspire.Hosting.Go": "%ASPIRE_VERSION%", + "Aspire.Hosting.Redis": "%ASPIRE_VERSION%", + "Aspire.Hosting.PostgreSQL": "%ASPIRE_VERSION%" + } +} +``` + +The regenerated SDK has an `AddPostgres` method. This AppHost adds a PostgreSQL server with one database and gives the API access to it: + +```go title="apphost.go" +package main + +import ( + "log" + + "apphost/modules/aspire" +) + +func main() { + builder, err := aspire.CreateBuilder() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + + cache := builder.AddRedis("cache") + db := builder.AddPostgres("postgres").AddDatabase("postgresdb") + + api := builder.AddGoApp("api", "./api"). + WithModTidy(). + WithReference(cache). + WithReference(db). + WaitFor(cache). + WaitFor(db). + WithHttpEndpoint(&aspire.WithHttpEndpointOptions{Env: aspire.StringPtr("PORT")}). + WithExternalHttpEndpoints(). + WithOtlpExporter() + + // Each call records its failure on the handle that it returns, so check every resource. + for _, resource := range []aspire.Resource{cache, db, api} { + if err := resource.Err(); err != nil { + log.Fatal(aspire.FormatError(err)) + } + } + + app, err := builder.Build() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + if err := app.Run(); err != nil { + log.Fatal(aspire.FormatError(err)) + } +} +``` + +- `AddPostgres` adds the PostgreSQL server, and `AddDatabase` returns a handle for a database on that server. +- `WithReference(db)` passes the connection details to the API as environment variables named after the resource, such as `POSTGRESDB_URI`. See [Connect to PostgreSQL](/integrations/databases/postgres/postgres-connect/) for a Go example that reads them. +- `WaitFor(db)` starts the API after the database is ready. +- The loop checks each handle with `Err()` before `Build`, because a failed call records its error on the handle that it returns. + +## Orchestrate apps in other languages + +A Go AppHost can run resources written in other languages next to your Go apps. Add the integration for each language that you use. Python and Node.js must also be installed, because these resources run on your machine: + +```bash title="Aspire CLI" +aspire add python +aspire add javascript +``` + +This AppHost runs a Go API and a Python recommendation service that share a Redis cache, and a Vite frontend that calls both: + +```go title="apphost.go" +package main + +import ( + "log" + + "apphost/modules/aspire" +) + +func main() { + builder, err := aspire.CreateBuilder() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + + cache := builder.AddRedis("cache") + + api := builder.AddGoApp("api", "./api"). + WithReference(cache). + WaitFor(cache). + WithHttpEndpoint(&aspire.WithHttpEndpointOptions{Env: aspire.StringPtr("PORT")}) + + recommender := builder.AddUvicornApp("recommender", "./recommender", "main:app"). + WithReference(cache). + WaitFor(cache) + + web := builder.AddViteApp("web", "./web"). + WithReference(api). + WithReference(recommender). + WaitFor(api) + + for _, resource := range []aspire.Resource{cache, api, recommender, web} { + if err := resource.Err(); err != nil { + log.Fatal(aspire.FormatError(err)) + } + } + + app, err := builder.Build() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + if err := app.Run(); err != nil { + log.Fatal(aspire.FormatError(err)) + } +} +``` + +- `AddUvicornApp` runs a Python ASGI app. The `main:app` argument names the Python module and the application object in it. +- `AddViteApp` runs a Vite frontend. `AddUvicornApp` and `AddViteApp` already register an `http` endpoint that reads its port from `PORT`, so only the Go API calls `WithHttpEndpoint`. +- `WithReference` and `WaitFor` work the same for every resource type. The frontend receives the endpoints of the API and the recommender, and it starts after the API is ready. + + + See [Set up JavaScript apps in the AppHost](/integrations/frameworks/javascript/) and [Python integration](/integrations/frameworks/python/) for the options of each integration. + + +## Debug a Go AppHost + +{/* PLACEHOLDER: replace the link below with the Go AppHost debugging guide when it is published. */} + +To debug AppHosts and their resources in Visual Studio Code, see [Run, debug, and deploy](/get-started/aspire-vscode-extension/#run-debug-and-deploy). + +## See also + +- [Go AppHost API conventions](/app-host/go-apphost-conventions/) +- [Go API reference](/reference/api/go/) +- [Set up Go apps in the AppHost](/integrations/frameworks/go/go-host/) +- [Multi-language architecture](/architecture/multi-language-architecture/) +- [aspire new command](/reference/cli/commands/aspire-new/) +- [aspire run command](/reference/cli/commands/aspire-run/) +- [aspire restore command](/reference/cli/commands/aspire-restore/) diff --git a/src/frontend/src/content/docs/architecture/multi-language-architecture.mdx b/src/frontend/src/content/docs/architecture/multi-language-architecture.mdx index 241dafec22..514c6ed731 100644 --- a/src/frontend/src/content/docs/architecture/multi-language-architecture.mdx +++ b/src/frontend/src/content/docs/architecture/multi-language-architecture.mdx @@ -1,13 +1,13 @@ --- title: Multi-language architecture -seoTitle: 'Aspire multi-language architecture: C# and TypeScript' -description: Understand how Aspire uses a guest/host architecture, ATS, SDK generation, and local token-based auth to support TypeScript AppHosts. +seoTitle: 'Aspire multi-language architecture: C#, TypeScript, and Go' +description: Understand how Aspire uses a guest/host architecture, ATS, SDK generation, and local token-based auth to support TypeScript and Go AppHosts. --- import LearnMore from '@components/LearnMore.astro'; import ApiReference from '@components/ApiReference.astro'; -Aspire supports writing AppHosts in multiple languages. While the orchestration engine is built on .NET, a guest/host architecture allows AppHosts written in TypeScript today, and additional languages in the future, to access Aspire integrations, service discovery, and the dashboard. +Aspire supports writing AppHosts in multiple languages. While the orchestration engine is built on .NET, a guest/host architecture allows AppHosts written in TypeScript and Go, and additional languages in the future, to access Aspire integrations, service discovery, and the dashboard. ## Why a shared backend @@ -24,6 +24,8 @@ When you run a TypeScript AppHost, the Aspire CLI orchestrates two processes: The guest communicates with the host via JSON-RPC over a local transport: Unix sockets on macOS and Linux, and named pipes on Windows. Your code calls methods such as `addRedis()` or `withReference()`, and the generated SDK translates those calls into RPC requests. +A Go AppHost works the same way. The guest is your `apphost.go` program, which the CLI starts with `go run .`, and it calls methods such as `AddRedis()` and `WithReference()` from the generated `aspire` package. + ```mermaid flowchart TB subgraph Guest["Guest Process (Node.js)"] @@ -53,7 +55,7 @@ flowchart TB ## Startup sequence 1. The CLI prepares the host process with the required hosting packages. -2. The ATS scanner inspects assemblies for exports and generates the TypeScript SDK into `.aspire/modules/`. +2. The ATS scanner inspects assemblies for exports and generates the SDK for your AppHost language into `.aspire/modules/`. 3. The CLI starts the host process and creates the local socket or pipe endpoint. 4. The CLI starts the guest process and passes connection details through environment variables. 5. The guest connects and invokes capabilities such as , `addRedis`, `build`, and . @@ -92,6 +94,19 @@ The Aspire Type System, or ATS, is the contract that bridges .NET and guest lang Resource types are passed by handle. The actual instance remains in the host process, while the TypeScript SDK keeps a reference and dispatches method calls as JSON-RPC requests. +### How ATS maps to Go + +| .NET type | Go representation | +|----------|-------------------| +| Primitives | `string`, `bool`, and `float64` for numbers | +| Enums | String types with typed constants, such as `aspire.ContainerLifetimePersistent` | +| Resource types | Interfaces with chainable methods that return the same handle type | +| DTOs | Structs serialized as JSON | +| Collections | Slices such as `[]string` and maps such as `map[string]string` | +| Delegates | Go functions | + +The Go SDK passes resource types by handle in the same way. Each resource interface wraps a handle to the host-side object, and calling a method sends a JSON-RPC request. + ## Polymorphism flattening .NET APIs rely on inheritance, interfaces, and generics. Guest SDKs do not need to expose that full shape directly. During scanning, ATS flattens the exported type system so the generated guest API is easier to consume: @@ -113,6 +128,8 @@ The TypeScript SDK is generated from hosting integration assemblies. When you ad This keeps the SDK in sync with the .NET implementation. Integration authors do not hand-write TypeScript bindings; they export their .NET APIs and the CLI generates the guest surface automatically. +For a Go AppHost, the CLI emits a Go package into `.aspire/modules/`. See [Generated SDK](/app-host/go-apphost/#generated-sdk). + If you're building a hosting integration and want it to work with TypeScript AppHosts, see [Multi-language integrations](/extensibility/multi-language-integration-authoring/). @@ -120,20 +137,21 @@ This keeps the SDK in sync with the .NET implementation. Integration authors do ## Same model, different syntax -The AppHost model is the same regardless of language. A TypeScript AppHost defines the same resources, references, and dependency graph as a C# AppHost. The difference is the authoring syntax. +The AppHost model is the same regardless of language. A TypeScript or Go AppHost defines the same resources, references, and dependency graph as a C# AppHost. The difference is the authoring syntax. -| Concept | C# | TypeScript | -|---------|----|------------| -| Create builder | `DistributedApplication.CreateBuilder(args)` | `await createBuilder()` | -| Add resource | `builder.AddRedis("cache")` | `await builder.addRedis("cache")` | -| Reference | `.WithReference(db)` | `.withReference(db)` | -| Wait for | `.WaitFor(api)` | `.waitFor(api)` | -| Build and run | `builder.Build().Run()` | `await builder.build().run()` | +| Concept | C# | TypeScript | Go | +|---------|----|------------|----| +| Create builder | `DistributedApplication.CreateBuilder(args)` | `await createBuilder()` | `aspire.CreateBuilder()` | +| Add resource | `builder.AddRedis("cache")` | `await builder.addRedis("cache")` | `builder.AddRedis("cache")` | +| Reference | `.WithReference(db)` | `.withReference(db)` | `.WithReference(db)` | +| Wait for | `.WaitFor(api)` | `.waitFor(api)` | `.WaitFor(api)` | +| Build and run | `builder.Build().Run()` | `await builder.build().run()` | `builder.Build()` then `app.Run()` | The resulting dashboard, service discovery behavior, health checks, and deployment artifacts come from the same host-side orchestration engine. ## See also - [Build your first app](/get-started/first-app/?lang=typescript) — get started with a TypeScript AppHost +- [Get started with the Go AppHost](/app-host/go-apphost/) - [Resource model](/architecture/resource-model/) — understand how Aspire models resources and relationships - [Multi-language integrations](/extensibility/multi-language-integration-authoring/) — make your integration work with TypeScript AppHosts diff --git a/src/frontend/src/content/docs/integrations/frameworks/go/go-get-started.mdx b/src/frontend/src/content/docs/integrations/frameworks/go/go-get-started.mdx index 85196481f5..a1244fa2f6 100644 --- a/src/frontend/src/content/docs/integrations/frameworks/go/go-get-started.mdx +++ b/src/frontend/src/content/docs/integrations/frameworks/go/go-get-started.mdx @@ -70,17 +70,17 @@ architecture-beta Set up Go apps in the AppHost -2. ### Optionally try the Go AppHost templates +2. ### Write the AppHost in Go - The `Aspire.Hosting.Go` integration works from C# and TypeScript AppHosts. Aspire also includes experimental Go AppHost and Go starter template support in the Aspire CLI. These templates use experimental Go AppHost APIs instead of the `Aspire.Hosting.Go` package. + The `Aspire.Hosting.Go` integration works from C#, TypeScript, and Go AppHosts. To write the AppHost itself in Go, create a project from the Go starter template and use the Go SDK that the Aspire CLI generates. - Try the experimental Go templates + Get started with the Go AppHost @@ -89,4 +89,5 @@ architecture-beta - [Go documentation](https://go.dev/doc/) - [Go AppHost setup reference](/integrations/frameworks/go/go-host/) +- [Get started with the Go AppHost](/app-host/go-apphost/) - [Aspire integrations overview](/integrations/overview/) diff --git a/src/frontend/src/content/docs/integrations/frameworks/go/go-host.mdx b/src/frontend/src/content/docs/integrations/frameworks/go/go-host.mdx index 9056fb1646..60a173d6f9 100644 --- a/src/frontend/src/content/docs/integrations/frameworks/go/go-host.mdx +++ b/src/frontend/src/content/docs/integrations/frameworks/go/go-host.mdx @@ -21,7 +21,7 @@ import ApiReference from '@components/ApiReference.astro'; classOverride="float-inline-left icon" /> -This article is the reference for the Aspire Go hosting integration. It enumerates the AppHost APIs — with examples for both `AppHost.cs` and `apphost.mts` — that you use to orchestrate Go applications in your [`AppHost`](/get-started/app-host/) project. +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`](/get-started/app-host/) 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](/integrations/frameworks/go/go-get-started/) guide. @@ -81,6 +81,28 @@ This updates your `aspire.config.json` with the Go hosting integration package: } ``` + + + +```bash title="Terminal" +aspire add go +``` + + + Learn more about [`aspire add`](/reference/cli/commands/aspire-add/) in the + command reference. + + +This updates your `aspire.config.json` with the Go hosting integration package and regenerates the Go SDK in `.aspire/modules/`: + +```json title="aspire.config.json" ins={3} +{ + "packages": { + "Aspire.Hosting.Go": "%ASPIRE_VERSION%" + } +} +``` + @@ -126,9 +148,47 @@ await api.withExternalHttpEndpoints(); await builder.build().run(); ``` + + + +```go title="apphost.go" +package main + +import ( + "log" + + "apphost/modules/aspire" +) + +func main() { + builder, err := aspire.CreateBuilder() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + + api := builder.AddGoApp("api", "./api"). + WithHttpEndpoint(&aspire.WithHttpEndpointOptions{Port: aspire.Float64Ptr(8080), Env: aspire.StringPtr("PORT")}). + WithExternalHttpEndpoints() + + if err := api.Err(); err != nil { + log.Fatal(aspire.FormatError(err)) + } + + app, err := builder.Build() + if err != nil { + log.Fatal(aspire.FormatError(err)) + } + if err := app.Run(); err != nil { + log.Fatal(aspire.FormatError(err)) + } +} +``` + +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. @@ -210,6 +270,16 @@ await api.withHttpEndpoint({ env: 'PORT' }); await builder.build().run(); ``` + + + +```go title="apphost.go" +builder.AddGoApp("api", "./api", &aspire.AddGoAppOptions{ + PackagePath: aspire.StringPtr("./cmd/server"), +}). + WithHttpEndpoint(&aspire.WithHttpEndpointOptions{Env: aspire.StringPtr("PORT")}) +``` + @@ -256,6 +326,19 @@ const api = await builder.addGoApp('api', './api', { await builder.build().run(); ``` + + + +```go title="apphost.go" +builder.AddGoApp("api", "./api", &aspire.AddGoAppOptions{ + PackagePath: aspire.StringPtr("./cmd/server"), + BuildTags: []string{"netgo", "integration"}, + LdFlags: aspire.StringPtr("-X main.version=1.2.3 -s -w"), + GcFlags: aspire.StringPtr("all=-N -l"), + RaceDetector: aspire.BoolPtr(true), +}) +``` + @@ -298,6 +381,15 @@ await api.withHttpEndpoint({ env: 'PORT' }); await builder.build().run(); ``` + + + +```go title="apphost.go" +builder.AddGoApp("api", "./api"). + WithAppArgs([]any{"--config", "dev.yaml"}). + WithHttpEndpoint(&aspire.WithHttpEndpointOptions{Env: aspire.StringPtr("PORT")}) +``` + @@ -341,6 +433,18 @@ await api.withHttpEndpoint({ env: 'PORT' }); await builder.build().run(); ``` + + + +```go title="apphost.go" +builder.AddGoApp("api", "./api"). + WithModTidy(). + WithModVendor(). + WithModDownload(). + WithVetTool(). + WithHttpEndpoint(&aspire.WithHttpEndpointOptions{Env: aspire.StringPtr("PORT")}) +``` + @@ -397,6 +501,15 @@ await api.withHttpEndpoint({ port: 8080, env: 'PORT' }); await builder.build().run(); ``` + + + +```go title="apphost.go" +builder.AddGoApp("api", "./api"). + WithDelveServer(). + WithHttpEndpoint(&aspire.WithHttpEndpointOptions{Port: aspire.Float64Ptr(8080), Env: aspire.StringPtr("PORT")}) +``` + @@ -432,6 +545,19 @@ await api.withDelveServer({ }); ``` + + + +```go title="apphost.go" +builder.AddGoApp("api", "./api"). + WithDelveServer(&aspire.DelveServerOptions{ + AcceptMultiClient: aspire.BoolPtr(true), + ContinueOnStart: aspire.BoolPtr(true), + Log: aspire.BoolPtr(true), + LogOutput: aspire.StringPtr("rpc,dap,debugger"), + }) +``` + @@ -502,6 +628,14 @@ await api.withGoPrivate(['github.com/myorg'], 'github.com'); await builder.build().run(); ``` + + + +```go title="apphost.go" +builder.AddGoApp("api", "./api"). + WithGoPrivate([]string{"github.com/myorg"}, "github.com") +``` + @@ -510,25 +644,15 @@ await builder.build().run(); overview](/deployment/overview/). -## Experimental Go AppHost templates +## Write the AppHost in Go -The `Aspire.Hosting.Go` integration can be used from C# and TypeScript AppHosts. Aspire also includes experimental Go AppHost and Go starter template support in the Aspire CLI. The Go AppHost templates use experimental Go AppHost APIs instead of the `Aspire.Hosting.Go` package. To enable Go AppHost language support for CLI templates, enable the Go feature flag: - -```bash title="Aspire CLI" -aspire config set features:experimentalPolyglot:go true --global -``` - -After enabling the feature, you can create a Go starter app with: - -```bash title="Aspire CLI" -aspire new aspire-go-starter -``` +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. - For more information about feature flags, see [Aspire CLI - configuration](/reference/cli/configuration/#toggle-preview-feature-experiences). - For template command details, see [`aspire - new`](/reference/cli/commands/aspire-new/). + To create a Go AppHost, see [Get started with the Go + AppHost](/app-host/go-apphost/). For the Go error model and optional + parameters, see [Go AppHost API + conventions](/app-host/go-apphost-conventions/). ## See also @@ -536,5 +660,6 @@ aspire new aspire-go-starter - [Go documentation](https://go.dev/doc/) - [Delve debugger](https://github.com/go-delve/delve) - [Get started with the Go integration](/integrations/frameworks/go/go-get-started/) +- [Get started with the Go AppHost](/app-host/go-apphost/) - [Aspire integrations overview](/integrations/overview/) - [Aspire GitHub repo](https://github.com/microsoft/aspire) diff --git a/src/frontend/src/content/docs/languages-and-runtimes/index.mdx b/src/frontend/src/content/docs/languages-and-runtimes/index.mdx index f0b4c86db9..58ca9d323d 100644 --- a/src/frontend/src/content/docs/languages-and-runtimes/index.mdx +++ b/src/frontend/src/content/docs/languages-and-runtimes/index.mdx @@ -10,7 +10,7 @@ Aspire works well with distributed apps that span more than one service, tool, o ## What this means in practice -- Write the **AppHost** in **C#** or **TypeScript** today. +- Write the **AppHost** in **C#**, **TypeScript**, or **Go**. - Orchestrate services and tools written in **C#**, **JavaScript**, **Python**, **Go**, **Java**, **Rust**, **PowerShell**, and more. - Start with the **Aspire Dashboard** if observability is your first step. - Adopt Aspire without rewriting your existing app around a single language. @@ -30,12 +30,13 @@ Pick the AppHost language that best fits your repo and team. Your workloads do n ## AppHost languages -Both AppHost styles use the same Aspire model. The main difference is how the orchestration is authored and how it fits into your existing workflow. +Every AppHost language uses the same Aspire model. The main difference is how the orchestration is authored and how it fits into your existing workflow. | AppHost language | Good fit for | Start here | Support | | --- | --- | --- | --- | | C# | Teams already using .NET tooling or who want a single-file AppHost | [What is the AppHost?](/get-started/app-host/) | Official | | TypeScript | Teams working in Node.js or TypeScript workspaces | [TypeScript AppHost project structure](/app-host/typescript-apphost/) | Official | +| Go | Teams working in Go modules who want the AppHost in the same language as their services | [Get started with the Go AppHost](/app-host/go-apphost/) | Official | ## Guides for app languages and runtimes diff --git a/src/frontend/src/content/docs/reference/cli/commands/aspire-add.mdx b/src/frontend/src/content/docs/reference/cli/commands/aspire-add.mdx index 83e4e09af1..c55dedf5cd 100644 --- a/src/frontend/src/content/docs/reference/cli/commands/aspire-add.mdx +++ b/src/frontend/src/content/docs/reference/cli/commands/aspire-add.mdx @@ -22,7 +22,7 @@ The `aspire add` command searches for an integration package and adds it to the - Project-based C# AppHosts receive a package reference. - File-based C# AppHosts receive a `#:package` directive. -- TypeScript AppHosts receive an entry in the `packages` section of `aspire.config.json`, then the generated `.aspire/modules/` TypeScript SDK is regenerated. +- TypeScript and Go AppHosts receive an entry in the `packages` section of `aspire.config.json`, then the generated SDK in `.aspire/modules/` is regenerated. @@ -86,6 +86,12 @@ The following options are available: aspire add redis --apphost './apphost.mts' ``` +- Add the **redis** integration to a Go AppHost and regenerate `.aspire/modules/`: + + ```bash title="Aspire CLI" + aspire add redis --apphost './apphost.go' + ``` + - Add the **azure-kubernetes** integration from a stable-shaped `staging` quality CLI, where the integration remains prerelease even though most other packages are stable: ```bash title="Aspire CLI" diff --git a/src/frontend/src/content/docs/reference/cli/commands/aspire-init.mdx b/src/frontend/src/content/docs/reference/cli/commands/aspire-init.mdx index a65a78de26..29f7ac64be 100644 --- a/src/frontend/src/content/docs/reference/cli/commands/aspire-init.mdx +++ b/src/frontend/src/content/docs/reference/cli/commands/aspire-init.mdx @@ -10,7 +10,7 @@ import ApiReference from '@components/ApiReference.astro'; ## Name -`aspire init` - Initialize Aspire support in an existing codebase with a C# or TypeScript AppHost. +`aspire init` - Initialize Aspire support in an existing codebase with a C#, TypeScript, or Go AppHost. ## Synopsis @@ -36,6 +36,7 @@ The command adapts to the repo it finds: - **C# file-based AppHost** (when selected interactively) — creates `apphost.cs` with `#:sdk` and `#:package` directives for a lightweight single-file orchestrator. - **TypeScript AppHost** (when selected interactively) — creates `apphost.mts` with the generated `.aspire/modules/` folder. If the repo already has a root `package.json`, the AppHost is created as a nested `aspire-apphost/` package and the root `aspire.config.json` points to `aspire-apphost/apphost.mts`. +- **Go AppHost** (when selected interactively): creates `apphost.go`, a `go.mod` that points at the generated SDK, and the generated `.aspire/modules/` folder. :::note When a `.sln` or `.slnx` is present, the C# option creates a **project-based AppHost** instead — an `AppHost.csproj` added to the solution with `ProjectReference` items and strongly-typed `AddProject()` calls. @@ -109,7 +110,7 @@ The following options are available: - **`--language`** - The AppHost language to scaffold (`csharp`, `typescript`). + The AppHost language to scaffold (`csharp`, `typescript`, `go`). - **`--file-based`** @@ -149,6 +150,12 @@ The following options are available: aspire init --language typescript ``` +- Initialize Aspire support with a Go AppHost: + + ```bash title="Aspire CLI" + aspire init --language go + ``` + - Initialize an empty C# AppHost at the repository root, ignoring any incidental `.sln` or `.slnx` files: ```bash title="Aspire CLI" diff --git a/src/frontend/src/content/docs/reference/cli/commands/aspire-new.mdx b/src/frontend/src/content/docs/reference/cli/commands/aspire-new.mdx index 98a602d04f..c557f4dcb0 100644 --- a/src/frontend/src/content/docs/reference/cli/commands/aspire-new.mdx +++ b/src/frontend/src/content/docs/reference/cli/commands/aspire-new.mdx @@ -120,6 +120,10 @@ The following options are available: Requesting `--channel staging` explicitly only resolves on `stable` or `staging` Aspire CLI builds. Daily, local, and per-PR builds don't have a deterministic staging feed, so they refuse the request with an error naming the running CLI's identity and pointing at the recovery options: install a staging or stable Aspire CLI, or set [`overrideStagingFeed`](/reference/cli/configuration/#settings-surfaced-by-aspire-config) to point at the staging feed you want to use. +- **`--language`** + + The programming language for the AppHost, such as `csharp`, `typescript`, or `go`. When you don't pass a template, `aspire new` offers only the templates that support the language. + - **`--suppress-agent-init`** Suppress the prompt to initialize MCP server configuration for agent environments after project creation. @@ -148,14 +152,16 @@ The following options are available: Each command represents a template. Pass the `--help` parameter to the template command to print the options available to the template. -| Command | Template | -| ---------------------- | --------------------------------- | -| `aspire-starter` | Starter App (ASP.NET Core/Blazor) | -| `aspire-ts-cs-starter` | Starter App (ASP.NET Core/React) | -| `aspire-py-starter` | Starter App (FastAPI/React) | -| `aspire-ts-starter` | Starter App (Express/React) | -| `aspire-empty` | Empty (C# AppHost) | -| `aspire-ts-empty` | Empty (TypeScript AppHost) | +| Command | Template | +| ---------------------- | ---------------------------------------- | +| `aspire-starter` | Starter App (ASP.NET Core/Blazor) | +| `aspire-ts-cs-starter` | Starter App (ASP.NET Core/React) | +| `aspire-py-starter` | Starter App (FastAPI/React) | +| `aspire-ts-starter` | Starter App (Express/React) | +| `aspire-go-starter` | Starter App (Go API + Redis, Go AppHost) | +| `aspire-empty` | Empty (C# AppHost) | +| `aspire-ts-empty` | Empty (TypeScript AppHost) | +| `aspire-go-empty` | Empty (Go AppHost) | ### aspire-py-starter options diff --git a/src/frontend/src/content/docs/reference/cli/commands/aspire-restore.mdx b/src/frontend/src/content/docs/reference/cli/commands/aspire-restore.mdx index 74ec200a26..70976d2fb3 100644 --- a/src/frontend/src/content/docs/reference/cli/commands/aspire-restore.mdx +++ b/src/frontend/src/content/docs/reference/cli/commands/aspire-restore.mdx @@ -19,7 +19,7 @@ aspire restore [options] The `aspire restore` command restores the AppHost and generates the SDK code that Aspire uses for resources, integrations, and tooling. Use it when you want to make restore an explicit step in automation or validate that the AppHost can restore cleanly without starting it. -For TypeScript AppHosts, restore reads the `packages` section in `aspire.config.json`, restores those hosting integration packages, and regenerates the `.aspire/modules/` TypeScript SDK imported by `apphost.mts`. This is useful after running `aspire add`, switching branches, updating pinned package versions, or restoring dependencies in CI before `aspire run`, `aspire publish`, or deployment workflows. +For TypeScript and Go AppHosts, restore reads the `packages` section in `aspire.config.json`, restores those hosting integration packages, and regenerates the SDK in `.aspire/modules/` that `apphost.mts` or `apphost.go` imports. This is useful after running `aspire add`, switching branches, updating pinned package versions, or restoring dependencies in CI before `aspire run`, `aspire publish`, or deployment workflows. @@ -63,6 +63,12 @@ The following options are available: aspire restore --apphost './apphost.mts' ``` +- Restore a specific Go AppHost and regenerate `.aspire/modules/`: + + ```bash title="Aspire CLI" + aspire restore --apphost './apphost.go' + ``` + ## See also - [aspire run](../aspire-run/) diff --git a/src/frontend/src/content/docs/reference/cli/configuration.mdx b/src/frontend/src/content/docs/reference/cli/configuration.mdx index 210346d4ac..3296d533e9 100644 --- a/src/frontend/src/content/docs/reference/cli/configuration.mdx +++ b/src/frontend/src/content/docs/reference/cli/configuration.mdx @@ -181,10 +181,10 @@ and their default values. aspire config set features. true --global ``` - For example, consider the following that enables global support for Go: + For example, consider the following that enables global support for Rust: - ```bash title="Enable global Go support" - aspire config set features.experimentalPolyglot:go true --global + ```bash title="Enable global Rust support" + aspire config set features.experimentalPolyglot:rust true --global ``` Always set `experimentalPolyglot:` flags with `--global`, or add diff --git a/src/frontend/src/content/docs/reference/cli/includes/config-settings-table.md b/src/frontend/src/content/docs/reference/cli/includes/config-settings-table.md index 37e54486ef..c3a696428b 100644 --- a/src/frontend/src/content/docs/reference/cli/includes/config-settings-table.md +++ b/src/frontend/src/content/docs/reference/cli/includes/config-settings-table.md @@ -11,7 +11,6 @@ title: Config Settings Table | `docs.api.sitemapUrl` | `https://aspire.dev/sitemap-0.xml` | API reference sitemap used by `aspire docs api`. Leave it unset to use the built-in aspire.dev source. | | `docs.llmsTxtUrl` | `https://aspire.dev/llms-full.txt` | `llms.txt` documentation source used by `aspire docs`. Leave it unset to use the built-in aspire.dev source. | | `features.defaultWatchEnabled` | `false` | Enable or disable watch mode by default when running Aspire applications for automatic restarts on file changes. | -| `features.experimentalPolyglot:go` | `false` | Enable or disable experimental Go AppHost support. | | `features.experimentalPolyglot:java` | `false` | Enable or disable experimental Java AppHost support. | | `features.experimentalPolyglot:python` | `false` | Enable or disable experimental Python AppHost support. | | `features.experimentalPolyglot:rust` | `false` | Enable or disable experimental Rust AppHost support. | @@ -32,6 +31,6 @@ Each `.` in a key maps to a nested object in `aspire.config.json`. For example, :::caution `aspire config set` treats every `.` and `:` in a key as a nesting separator, so it can't write keys whose names contain those characters: -- In `features.experimentalPolyglot:`, `experimentalPolyglot:` is a single feature name. Without `--global`, the CLI writes a nested `experimentalPolyglot` object to the local `aspire.config.json` file, and later commands fail to load the file. Set these flags with `--global`, or add them to the local file by hand, for example `"experimentalPolyglot:go": true` in the `features` object. +- In `features.experimentalPolyglot:`, `experimentalPolyglot:` is a single feature name. Without `--global`, the CLI writes a nested `experimentalPolyglot` object to the local `aspire.config.json` file, and later commands fail to load the file. Set these flags with `--global`, or add them to the local file by hand, for example `"experimentalPolyglot:rust": true` in the `features` object. - Package IDs such as `Aspire.Hosting.Redis` contain dots. Use `aspire add` to add packages, or edit the `packages` object by hand. :::