跳转到内容

Go integration

此内容尚不支持你的语言。

⭐ Community Toolkit Go logo

The Aspire Go hosting integration enables you to run Go applications alongside your Aspire projects in the Aspire app host.

To get started with the Aspire Go hosting integration, install the CommunityToolkit.Aspire.Hosting.Golang NuGet package in the app host project.

Aspire CLI — 添加 CommunityToolkit.Aspire.Hosting.Golang 包
aspire add communitytoolkit-golang

Aspire CLI 是交互式的;按提示选择合适的搜索结果:

Aspire CLI — 输出示例
Select an integration to add:
> communitytoolkit-golang (CommunityToolkit.Aspire.Hosting.Golang)
> Other results listed as selectable options...

To add a Go application to your app host, use the AddGolangApp extension method:

C# — AppHost.cs
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

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:

C# — AppHost.cs
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)
}

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.

问 & 答协作社区讨论观看