Step Over to Go Part 53 of 53
  1. 1 Goodbye .csproj, Hello go.mod
  2. 2 The Phrasebook: C# Concepts in Go Terms
  3. 3 You Know .NET, Now Meet the Go Toolchain
  4. 4 No Enums? No Problem (Sort Of)
  5. 5 Generics: Late to the Party
  6. 6 The Million Dollar Mistake, Differently
  7. 7 Your Class Is Now a Struct (And That's Fine)
  8. 8 Where Did My Properties Go?
  9. 9 if err != nil: Your New Reality
  10. 10 Panic and Recover: The Emergency Exit
  11. 11 The switch Statement You Always Wanted
  12. 12 Stack vs Heap: Go's Escape Analysis
  13. 13 Pointers Without the Pain
  14. 14 Slices Are Not Arrays (And Neither Is List<T>)
  15. 15 Channels: The sync You Didn't Know You Wanted
  16. 16 Context Is King
  17. 17 Async/Await vs Goroutines: A Mindset Shift
  18. 18 select: Multiplexing Like a Pro
  19. 19 Mutexes and WaitGroups: When Channels Aren't the Answer
  20. 20 The Empty Interface and Type Assertions
  21. 21 Composition Over Inheritance (For Real This Time)
  22. 22 Implicit Interfaces: Scary Then Brilliant
  23. 23 Benchmarks and Profiling Out of the Box
  24. 24 Mocking in a Language Without Mockito
  25. 25 Multi-Module Repos: Monorepo Thinking
  26. 26 Organising a Real Project
  27. 27 Testing Without a Framework
  28. 28 Configuration Without IOptions<T>
  29. 29 Database Access: database/sql vs Entity Framework
  30. 30 Debugging: Delve vs Visual Studio's Comfort
  31. 31 Generate All the Things
  32. 32 GORM and Friends: When You Do Want an ORM
  33. 33 HTTP Services: net/http vs ASP.NET Core
  34. 34 JSON: Struct Tags and the Marshal Dance
  35. 35 Linting and Formatting: gofmt Is Non-Negotiable
  36. 36 Logging: slog and the Structured Logging Story
  37. 37 Shrinking Binaries and Build Tags
  38. 38 Dockerfile for Go: Simpler Than You'd Think
  39. 39 GitHub Actions for Go Projects
  40. 40 Health Checks and Readiness Probes
  41. 41 Kubernetes and Go: A Natural Fit
  42. 42 AWS Lambda and Go: Cold Starts That Don't Hurt
  43. 43 Metrics, Traces, and Logs: The OpenTelemetry Way
  44. 44 Single Binary Deploys: The Killer Feature
  45. 45 Versioning Your Modules
  46. 46 What I Actually Miss From C#
  47. 47 What I'll Never Go Back For
  48. 48 Six Months In: Was It Worth It?
  49. 49 Forty-Eight Posts on Moving From C# to Go, in the Right Order
  50. 50 Range-Over-Func Iterators for People Who Miss LINQ
  51. 51 What I Got Wrong About Go
  52. 52 Attribute Routing Comes to Go's ServeMux, in Struct Tags
  53. 53 How a .NET Solution Structure Maps to a Go Project Layout
About this series

How a .NET Solution Structure Maps to a Go Project Layout

How a .NET Solution Structure Maps to a Go Project Layout

This is how .NET solutions and Go modules are structured, shown with the same small app built both ways: where projects and packages go, how each language decides what is visible, where the tests live, and how many files each needs to say so. It comes with my opinions on both, and a rather daft benchmark at the end.

This series has covered Go's project layout three times, a piece at a time: packages and folders, go.mod against the csproj and repositories with several modules. Each of those described the Go side and pointed back at .NET. This time I wrote the same small app twice, once as a .NET solution and once as a Go module, laid each one out the way its own community would expect, and put both in one repository so they can be read side by side: dotnet-go-layout.

The app

It is the tab at a tabanco in Jerez. The waiter chalks each round on the wooden bar in front of you as tally marks, and adds it up when you leave. The code has a rules library (the menu, tabs, rounds, the bill) and two programs that use it: an HTTP API and a command line tool called chalk.

$ chalk order Mari fino fino fino fino fino px chicharrones
Mari
  Fino           ||||/              5    10,00 €
  Pedro Ximénez  |                  1     2,50 €
  Chicharrones   |                  1     4,00 €
  ----------------------------------------------
  total                                  16,50 €

There is also chalk penultima Mari, which orders one more of whatever she has drunk most. Nobody in Andalucía orders la última, only the one before it.

That shape (one library, two executables, tests, a data file shipped inside the library, a third-party test package on one side) is small enough to read in an evening and still needs every part of a project layout.

The two trees

dotnet/                                  go/
  Tabanco.slnx                             go.mod
  global.json
  Directory.Build.props
  Directory.Packages.props
  src/
    Tabanco.Core/                          internal/
      Tabanco.Core.csproj                    tab/
      Menu.cs                                  menu.go
      Tab.cs                                   tab.go
      Chalk.cs                                 menu.json
      Json.cs                                  tab_test.go
      Storage/                               store/
        ITabStore.cs                           store.go
        MemoryTabStore.cs                      store_test.go
        FileTabStore.cs                      api/
    Tabanco.Api/                               api.go
      Tabanco.Api.csproj                       api_test.go
      Program.cs                           cmd/
      Bartender.cs                           tabanco-api/
      Problems.cs                              main.go
      appsettings.json                       chalk/
    Tabanco.Cli/                               main.go
      Tabanco.Cli.csproj
      Program.cs
  tests/
    Directory.Build.props
    Tabanco.Core.Tests/
      Tabanco.Core.Tests.csproj
      TabTests.cs
      StoreTests.cs
    Tabanco.Api.Tests/
      Tabanco.Api.Tests.csproj
      ContractTests.cs

The .NET side has 25 files and the Go side 11. Eleven of the 25 are build configuration of some kind: the solution, global.json, two Directory.Build.props, Directory.Packages.props, five project files and an appsettings.json. The Go side has one, go.mod, and it is three lines long because the app depends on nothing outside the standard library. There is no go.sum, since there is nothing to check a hash of.

Line counts go the other way. Leaving out blank lines and comments, the Go code is 573 lines and the C# 425. Half the difference is the HTTP layer (193 lines against 116), where each Go handler decodes its own body and checks its own errors and minimal APIs bind parameters for you. This morning's post on routing is about closing that gap with struct tags. The rest is spread across the rules, the stores and the CLI, mostly in if err != nil.

What each unit means

.NET Go
Solution (.slnx) Module (go.mod) The thing you open, build and test as a whole
Project (.csproj) Package (a directory) The unit of compilation, and of internal visibility
Namespace Import path How other code names it
Assembly (none) Go links everything into one binary
OutputType Exe package main What makes an executable
ProjectReference import Depending on your own code

The second row is the one that changes how you lay things out. In .NET a project can hold any number of namespaces in any folders, and the folders are a convention the IDE keeps. Tabanco.Core has a Storage folder whose classes are in the Tabanco.Core.Storage namespace, and they still compile into the same assembly as everything else in Core and can see its internal members.

In Go the folder is the package. store had to be its own directory and its own package, which means it imports tab like any other caller and sees only what tab exports. So the Go side ends up with five packages where .NET has three projects. That is the normal result: a Go package tends to be smaller than a .NET project, closer to a namespace that has to stand on its own.

Executables

The .NET CLI is a project of its own, with two settings that matter:

<PropertyGroup>
  <OutputType>Exe</OutputType>
  <AssemblyName>chalk</AssemblyName>
</PropertyGroup>

The API project gets its executable from Microsoft.NET.Sdk.Web instead. Both have a ProjectReference to Core.

The Go CLI is cmd/chalk/main.go, which starts with package main, and that is the whole declaration. The binary takes its name from the directory, so go build ./cmd/chalk makes chalk and go install ./cmd/... makes both programs. There is no project file to say that cmd/chalk depends on internal/tab; the import says so.

The cmd/ folder is a convention, as src/ is in .NET, and the Go tool would build a main package from anywhere.

Who can see what

Go's internal is a directory name. Anything under go/internal/ can be imported only by code inside go/, so the rules, the store and the handler can't be used by another module even though their names are exported. The two programs under cmd/ can import them because they are in the same module.

C#'s internal is a keyword, and its boundary is the assembly. Core's types have to be public for the API and CLI projects to use them, and once they are public, any project that references the DLL can use them too. .NET has nothing that says “public to this solution only”.

Tests show the same difference from the other direction. The function that draws tally marks is unexported in Go (tally) and internal in C# (Chalk.Tally). Go tests live in the package, in tab_test.go beside tab.go, so they call tally with nothing extra. The C# tests are a separate assembly, so Core's project file has to let them in:

<ItemGroup>
  <InternalsVisibleTo Include="Tabanco.Core.Tests" />
</ItemGroup>

Tests

That is also the biggest difference in how the trees look. .NET tests are projects, kept in their own folder, each with a project file that references the code it tests. Go tests are files ending in _test.go, next to the code, compiled only by go test. Go has no test project and no test framework package. testing is in the standard library, and the table tests here are plain loops.

The .NET test projects share settings through a second Directory.Build.props in tests/. MSBuild uses the nearest one it finds walking up from a project, and stops there, so this one has to import its parent explicitly before adding the test settings:

<Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" />
<PropertyGroup>
  <OutputType>Exe</OutputType>
  <IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
  <PackageReference Include="xunit.v3" />
  <Using Include="Xunit" />
</ItemGroup>

Package versions are in Directory.Packages.props with central package management switched on, so a project names a package without a version. I first included Microsoft.NET.Test.Sdk and xunit.runner.visualstudio out of habit, and dotnet test on the .NET 10 SDK refused:

error : Testing with VSTest target is no longer supported by Microsoft.Testing.Platform
on .NET 10 SDK and later. If you use dotnet test, you should opt-in to the new dotnet
test experience.

xunit.v3 runs on Microsoft.Testing.Platform, and the opt-in is a setting in global.json, which therefore now says which test runner the solution uses as well as which SDK:

{
  "sdk": { "version": "10.0.101", "rollForward": "latestFeature" },
  "test": { "runner": "Microsoft.Testing.Platform" }
}

The Go equivalent of global.json is the go 1.27.3 line in go.mod. A newer toolchain builds the module, and an older one downloads the version it asks for.

Shipping a data file inside the library

The menu is a JSON file in contract/ at the root of the repository, outside both trees, because both sides use it. .NET embeds it from there:

<EmbeddedResource Include="..\..\..\contract\menu.json" LogicalName="Tabanco.Core.menu.json" />

Go's //go:embed can't do that. It only embeds files in the package's directory or below it, and a path with .. in it doesn't compile:

internal/tab/menu.go:15:12: pattern ../../../contract/menu.json: invalid pattern syntax

So go/internal/tab/menu.json is a copy, and a test reads the original and fails if the two differ. A module is meant to be buildable from its own directory, which is what makes go install from a URL work, and anything it embeds has to come with it.

One repository, two trees

Three things needed setting up at the root because the Go module isn't there.

Editors. gopls looks for a module from where the editor was opened, and with the repository root open every Go file showed:

This file is within module "../dotnet-go-layout/go", which is not included in your
workspace. To fix this problem, you can add a go.work file that uses this directory.

A go.work at the root that lists the module (go 1.27.3, then use ./go) fixes it.

CI. There are two workflows, go.yml and dotnet.yml, each filtered on its own folder plus contract/, so a change to the Go code doesn't build the .NET solution and a change to the contract builds both. Each sets working-directory for its steps. setup-go takes go-version-file: go/go.mod and setup-dotnet takes global-json-file: dotnet/global.json, so the versions are written in one place on each side.

A contract both sides run. contract/http.json is an evening at the bar written as seventeen requests, in order, each with the exact status and body expected: Mari opens a tab, orders, tries to order a cerveza, asks for la penúltima before she has had anything, settles up. Both test suites start a server in-process (httptest.NewServer in Go, WebApplicationFactory<Program> in .NET) and run every step.

The test projects find the file in different ways. A Go test runs with its package directory as the working directory, so api_test.go reads ../../../contract/http.json directly. A .NET test runs from its bin folder, so the project file copies the contract there:

<None Include="..\..\..\contract\*.json" LinkBase="contract" CopyToOutputDirectory="PreserveNewest" />

What the contract caught

The Go side passed the contract on its first run. The .NET side failed one step:

step 2 (a tab needs a name): got
{"type":"https://tools.ietf.org/html/rfc9110#section-15.5.1","title":"Bad Request","status":400,"detail":"a tab needs a name"}
want
{"title":"Bad Request","status":400,"detail":"a tab needs a name"}

I had built the error with TypedResults.Problem and set Type = null, and ASP.NET Core filled in a link anyway. The fix was to write the problem body as a record, the way the Go side writes a map. I had also already set the JSON encoder to UnsafeRelaxedJsonEscaping, because the default one writes “Pedro Ximénez” as Pedro Ximénez. Both are valid JSON and would have passed a comparison by value, but curl output would have differed between the two servers.

Two more .NET details came up while wiring it. A body that isn't JSON is turned into a bare 400 by minimal APIs outside Development and thrown as an exception in Development, so the tests (Development) and a real run would answer differently unless RouteHandlerOptions.ThrowOnBadRequest is set to true. And WebApplicationFactory<Program> worked with no public partial class Program anywhere, which earlier versions needed and .NET 10 generates.

The two CLIs agree as well. Both keep tabs in chalk.json in the same shape, so I opened a tab with the Go chalk, ordered with the .NET one, ordered again with Go, asked .NET for la penúltima and printed the result from both. The output was identical byte for byte.

A daft benchmark

The app does almost nothing. chalk show Mari starts, reads a small JSON file, parses the menu it carries inside it, prints eight lines and exits. Timing that tells you about start-up and very little else, so comparing the two is rather silly, and I did it anyway, with the method from the Hot Path series. A static Go runner is mounted into each Docker image and starts chalk 100 times in a row, after five runs that don't count, recording the wall time from spawn to exit and the peak memory the kernel reports. Everything ran under Docker on my laptop, linux/arm64, and bench/bench.sh in the repository does the lot.

Build Cold start (median) Fastest 90th percentile Peak memory App Image Compile
Go 0.88 ms 0.72 ms 1.08 ms 3.3 MB 3.7 MB 48 MB 1.6 s
.NET, JIT 24.33 ms 22.98 ms 29.19 ms 34.5 MB 0.2 MB 81 MB 1.2 s
.NET, Native AOT 2.13 ms 1.86 ms 2.41 ms 9.1 MB 2.6 MB 47 MB 2.8 s

App is what each build adds to its base image: the binary, or for the JIT build the published folder of DLLs. The Go and Native AOT builds sit on the same small Debian image, and the JIT build on the one with the .NET runtime in it. Compile is a cold go build (an empty build cache, so it compiles the standard library packages it uses too) or a dotnet publish after a restore that isn't timed. All three printed the same tab, byte for byte.

The JIT build takes 24 ms to show a tab, about 28 times as long as Go, and most of that is the runtime starting up and compiling the code it needs before anything is printed. It peaks at 34.5 MB to print eight lines.

Native AOT gets that down to 2.1 ms and 9.1 MB, nearly two and a half times Go's 0.9 ms. The Hot Path series found much the same gap with a real HTTPS client: the Go client started in 1.7 ms and the Native AOT C# client in 3.0 ms, until breaking a few rules brought C# level with Go at 1.67 ms.

The AOT binary is smaller than Go's, 2.6 MB against 3.7 MB, which surprised me until I built Go with -ldflags="-s -w". Without its symbol table and debug information the Go binary is 2.4 MB. Native AOT strips them by default and go build keeps them.

Getting the AOT build to work changed the layout on the .NET side. Native AOT can't use reflection to serialise JSON, so the publish stopped at every JsonSerializer call in Core with IL2026 and IL3050, even after I gave the options a source-generated resolver: the overloads that take a JsonSerializerOptions are flagged whatever the options hold. Core now has a JsonSerializerContext and calls the overloads that take its JsonTypeInfo. The build also needed a newer SDK than the one on this machine. On 10.0.101, Native AOT pulls in a native compiler package with a known high-severity vulnerability (a bug in the Brotli decoder, GHSA-p3jp-9v83-76w9), NuGet's audit turns that into a build error, and pinning a newer compiler fails against the older SDK's build targets. So the bench builds .NET in the current mcr.microsoft.com/dotnet/sdk:10.0 image.

The Go side needed no change, since go build already makes a native binary. The runner went into the repository as a second Go module, bench/runner, with its own go.mod, because it measures the app rather than being part of it, and go.work now lists both modules.

Where each layout comes from

The .NET layout has many files because each answers a question the build would otherwise ask separately in every project: which SDK, which language settings, which package versions, which test runner. Without Directory.Build.props and Directory.Packages.props, those settings would be repeated in five project files. The solution's job is to group projects, and since .slnx it is a short XML file rather than a list of GUIDs.

The Go layout has few files because the language makes the same decisions in fixed places. The folder is the package, package main makes a program, _test.go is a test, internal/ is private, the module's go line is the toolchain. None of it is configurable, so none of it needs a file. What that gives up shows in the places where this repository needed something a little unusual: a data file outside the module, an editor opened one level too high, a module that isn't at the root.

The repository is github.com/AndyCross/dotnet-go-layout, and its README has the commands to build, test and run each side.