Skip to content
Merged
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
using Aspire.Hosting.ApplicationModel;
using CommunityToolkit.Aspire.Utils;
using System.Diagnostics;
using System.Globalization;
using System.Text.RegularExpressions;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging.Abstractions;

namespace Aspire.Hosting;

Expand Down Expand Up @@ -68,10 +74,148 @@ public static IResourceBuilder<GolangAppExecutableResource> AddGolangApp(this ID

return builder.AddResource(resource)
.WithGolangDefaults()
.WithArgs([.. allArgs]);
.WithArgs([.. allArgs])
.PublishAsGolangDockerfile(workingDirectory, executable, buildTags);
}

private static IResourceBuilder<GolangAppExecutableResource> WithGolangDefaults(
this IResourceBuilder<GolangAppExecutableResource> builder) =>
builder.WithOtlpExporter();
}

/// <summary>
/// Configures the Golang application to be published as a Dockerfile with automatic multi-stage build generation.
/// </summary>
/// <param name="builder">The resource builder.</param>
/// <param name="workingDirectory">The working directory containing the Golang application.</param>
/// <param name="executable">The path to the Golang package directory or source file to be executed.</param>
/// <param name="buildTags">The optional build tags to be used when building the Golang application.</param>
/// <returns>A reference to the <see cref="IResourceBuilder{T}"/>.</returns>
#pragma warning disable ASPIREDOCKERFILEBUILDER001
private static IResourceBuilder<GolangAppExecutableResource> PublishAsGolangDockerfile(
this IResourceBuilder<GolangAppExecutableResource> builder,
string workingDirectory,
string executable,
string[]? buildTags)
{
const string DefaultAlpineVersion = "3.21";

return builder.PublishAsDockerFile(publish =>
{
publish.WithDockerfileBuilder(workingDirectory, context =>
{
var buildArgs = new List<string> { "build", "-o", "/app/server" };

if (buildTags is { Length: > 0 })
{
buildArgs.Add("-tags");
buildArgs.Add(string.Join(",", buildTags));
}

buildArgs.Add(executable);

// Get custom base image from annotation, if present
context.Resource.TryGetLastAnnotation<DockerfileBaseImageAnnotation>(out var baseImageAnnotation);
var goVersion = baseImageAnnotation?.BuildImage ?? GetDefaultGoBaseImage(workingDirectory, context.Services);

var buildStage = context.Builder
.From(goVersion, "builder")
.WorkDir("/build")
.Copy(".", "./")
.Run(string.Join(" ", ["go", .. buildArgs]));

var runtimeImage = baseImageAnnotation?.RuntimeImage ?? $"alpine:{DefaultAlpineVersion}";

context.Builder
.From(runtimeImage)
.CopyFrom(buildStage.StageName!, "/app/server", "/app/server")
.Entrypoint(["/app/server"]);
});
});
}
#pragma warning restore ASPIREDOCKERFILEBUILDER001

private static string GetDefaultGoBaseImage(string workingDirectory, IServiceProvider serviceProvider)
{
const string DefaultGoVersion = "1.23";
var logger = serviceProvider.GetService<ILogger<GolangAppExecutableResource>>() ?? NullLogger<GolangAppExecutableResource>.Instance;
var goVersion = DetectGoVersion(workingDirectory, logger) ?? DefaultGoVersion;
return $"golang:{goVersion}";
}

/// <summary>
/// Detects the Go version to use for a project by checking go.mod and the installed Go toolchain.
/// </summary>
/// <param name="workingDirectory">The working directory of the Go project.</param>
/// <param name="logger">The logger for diagnostic messages.</param>
/// <returns>The detected Go version as a string, or <c>null</c> if no version is detected.</returns>
private static string? DetectGoVersion(string workingDirectory, ILogger logger)
{
// Check go.mod file
var goModPath = Path.Combine(workingDirectory, "go.mod");
if (File.Exists(goModPath))
{
try
{
var goModContent = File.ReadAllText(goModPath);
// Look for "go X.Y" or "go X.Y.Z" line in go.mod
var match = Regex.Match(goModContent, @"^\s*go\s+(\d+\.\d+(?:\.\d+)?)", RegexOptions.Multiline);
if (match.Success)
{
var version = match.Groups[1].Value;
// Extract major.minor (e.g., "1.22" from "1.22.3")
var versionParts = version.Split('.');
if (versionParts.Length >= 2)
{
var majorMinor = $"{versionParts[0]}.{versionParts[1]}";
logger.LogDebug("Detected Go version {Version} from go.mod file", majorMinor);
return majorMinor;
}
}
}
catch (Exception ex)
{
logger.LogDebug(ex, "Failed to parse go.mod file");
}
Copy link

Copilot AI Nov 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generic catch clause.

Suggested change
catch (Exception ex)
{
logger.LogDebug(ex, "Failed to parse go.mod file");
}
catch (IOException ex)
{
logger.LogDebug(ex, "Failed to parse go.mod file due to IO error");
}
catch (UnauthorizedAccessException ex)
{
logger.LogDebug(ex, "Failed to parse go.mod file due to unauthorized access");
}
catch (RegexMatchTimeoutException ex)
{
logger.LogDebug(ex, "Failed to parse go.mod file due to regex timeout");
}

Copilot uses AI. Check for mistakes.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed by catching specific exception types: IOException, UnauthorizedAccessException, and RegexMatchTimeoutException. (6897c21)

}

// Try to detect from installed Go toolchain
try
{
var startInfo = new ProcessStartInfo
{
FileName = "go",
Arguments = "version",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};

using var process = Process.Start(startInfo);
if (process != null)
{
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
Copy link

Copilot AI Nov 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reading the output stream before calling WaitForExit() can cause a deadlock if the process writes enough data to fill the output buffer. The process will block waiting for the buffer to be read, while the code waits for the process to exit. Consider using process.WaitForExit() first, or use asynchronous read operations, or read both StandardOutput and StandardError concurrently.

Suggested change
var output = process.StandardOutput.ReadToEnd();
process.WaitForExit();
// Read both output and error asynchronously, then wait for process exit
var outputTask = process.StandardOutput.ReadToEndAsync();
var errorTask = process.StandardError.ReadToEndAsync();
process.WaitForExit();
var output = outputTask.GetAwaiter().GetResult();
var error = errorTask.GetAwaiter().GetResult();

Copilot uses AI. Check for mistakes.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed by reading both StandardOutput and StandardError asynchronously before calling WaitForExit() to prevent potential deadlock. (6897c21)


if (process.ExitCode == 0)
{
// Output format: "go version goX.Y.Z ..."
var match = Regex.Match(output, @"go version go(\d+\.\d+)");
if (match.Success)
{
var version = match.Groups[1].Value;
logger.LogDebug("Detected Go version {Version} from installed toolchain", version);
return version;
}
}
}
}
catch (Exception ex)
{
logger.LogDebug(ex, "Failed to detect Go version from installed toolchain");
}
Copy link

Copilot AI Nov 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generic catch clause.

Copilot uses AI. Check for mistakes.
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed by catching specific exception types: IOException and Win32Exception (for go command not found). (6897c21)


logger.LogDebug("No Go version detected, will use default version");
return null;
}
}
35 changes: 35 additions & 0 deletions src/CommunityToolkit.Aspire.Hosting.Golang/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,41 @@ To have the Golang application listen on the correct port, you can use the follo
r.Run(":"+os.Getenv("PORT"))
```

## Publishing

When publishing your Aspire application, the Golang resource automatically generates a multi-stage Dockerfile for containerization. This means you don't need to manually create a Dockerfile for your Golang application.

### Automatic Version Detection

The integration automatically detects the Go version to use by:
1. Checking the `go.mod` file for the Go version directive
2. Falling back to the installed Go toolchain version
3. Using Go 1.23 as the default if no version is detected

### Customizing Base Images

You can customize the base images used in the Dockerfile by using the `DockerfileBaseImageAnnotation`:

```csharp
var golang = builder.AddGolangApp("golang", "../gin-api")
.WithHttpEndpoint(env: "PORT")
.WithAnnotation(new DockerfileBaseImageAnnotation
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot You can use WithDockerfileBaseImage:

builder.AddPythonApp("myapp", "path/to/app", "main.py")
             .WithDockerfileBaseImage(
            buildImage: "ghcr.io/astral-sh/uv:python3.12-bookworm-slim",
            runtimeImage: "python:3.12-slim-bookworm");

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated README to use WithDockerfileBaseImage() extension method for a cleaner API. (4fb890c)

{
BuildImage = "golang:1.22-alpine", // Custom build stage image
RuntimeImage = "alpine:3.20" // Custom runtime stage image
});
```

### Generated Dockerfile

The automatically generated Dockerfile:
- Uses the detected or default Go version (e.g., `golang:1.22`) as the build stage
- Uses `alpine:3.21` as the runtime stage for a smaller final image
- Respects your build tags if specified
- Builds the executable specified in your `AddGolangApp` call

This automatic Dockerfile generation happens when you publish your Aspire application and requires no additional configuration.

## Additional Information

https://learn.microsoft.com/dotnet/aspire/community-toolkit/hosting-golang
Expand Down