Go integration
The Aspire Go hosting integration enables you to run Go applications alongside your Aspire projects in the Aspire app host.
Hosting integration
Section titled “Hosting integration”To get started with the Aspire Go hosting integration, install the CommunityToolkit.Aspire.Hosting.Golang NuGet package in the app host project.
aspire add communitytoolkit-golangThe Aspire CLI is interactive, be sure to select the appropriate search result when prompted:
Select an integration to add:
> communitytoolkit-golang (CommunityToolkit.Aspire.Hosting.Golang)> Other results listed as selectable options...#:package CommunityToolkit.Aspire.Hosting.Golang@*<PackageReference Include="CommunityToolkit.Aspire.Hosting.Golang" Version="*" />Add Go app
Section titled “Add Go app”To add a Go application to your app host, use the AddGolangApp extension method:
var builder = DistributedApplication.CreateBuilder(args);
var goApp = builder.AddGolangApp( name: "go-api", workingDirectory: "../go-app") .WithHttpEndpoint(port: 8080, env: "PORT");
builder.AddProject<Projects.ExampleProject>() .WithReference(goApp);
// After adding all resources, run the app...The AddGolangApp method requires:
- name: The name of the resource in the Aspire dashboard
- workingDirectory: The path to the directory containing your Go application
Configure endpoints
Section titled “Configure endpoints”Go applications typically use environment variables to configure the port they listen on. Use WithHttpEndpoint to configure the port and set the PORT environment variable:
var builder = DistributedApplication.CreateBuilder(args);
var goApp = builder.AddGolangApp("go-api", "../go-app") .WithHttpEndpoint(port: 8080, env: "PORT");
// After adding all resources, run the app...Your Go application can read the PORT environment variable to determine which port to listen on:
package main
import ( "fmt" "net/http" "os")
func main() { port := os.Getenv("PORT") if port == "" { port = "8080" }
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello from Go!") })
fmt.Printf("Server listening on port %s\n", port) http.ListenAndServe(":"+port, nil)}Working directory
Section titled “Working directory”The workingDirectory parameter specifies where the Go application is located. The Aspire app host will run go run . in this directory to start your Go application.