You can use the github.com/compose-spec/compose-go/v2/cli package to parse and load Docker Compose files according to the official Compose specification.
To load a project, use cli.NewProjectOptions to configure the file paths and loading behavior (such as including OS environment variables or .env files), then call options.LoadProject(ctx) to retrieve the project object. Once loaded, you can interact with the project, for example, by using project.MarshalYAML() to get the YAML representation of the loaded configuration.
package main
import (
"context"
"fmt"
"log"
"github.com/compose-spec/compose-go/v2/cli"
)
func main() {
composeFilePath := "docker-compose.yml"
projectName := "my_project"
ctx := context.Background()
options, err := cli.NewProjectOptions(
[]string{composeFilePath},
cli.WithOsEnv,
cli.WithDotEnv,
cli.WithName(projectName),
)
if err != nil {
log.Fatal(err)
}
project, err := options.LoadProject(ctx)
if err != nil {
log.Fatal(err)
}
// Use the MarshalYAML method to get YAML representation
projectYAML, err := project.MarshalYAML()
if err != nil {
log.Fatal(err)
}
fmt.Println(string(projectYAML))
}