Overview
The Intro project demonstrates how to set up a “proper” Go workspace following the standard project layout preferred by the Go community. Rather than writing a singlemain.go file, this guide shows you how to structure your code for scalability and maintainability.
Why Project Structure Matters
A well-organized Go project:- Makes your code easier to navigate and understand
- Enforces encapsulation through the
internal/directory - Allows you to build multiple binaries from the same codebase
- Follows community conventions that other Go developers recognize
Key Concepts
Go Modules (go.mod)
The Create a new module with:
go.mod file defines your module’s path and dependencies. It enables reliable version management and imports.go.mod
Standard Directory Layout
Go projects follow a conventional structure:
cmd/- Contains the main entry point(s) of your application. The directory name usually matches the desired executable name (e.g.,cmd/introbuilds tointroorintro.exe)internal/- Contains private application code. Go’s toolchain enforces that code insideinternalcannot be imported by external modules, ensuring better encapsulationpkg/(optional) - Contains library code that can be imported by external projects
Folder Structure
A clean Go project looks like this:Visual Representation
Visual Representation
Code Walkthrough
The Entry Point
Thecmd/intro/main.go file is the “face” of your application. It belongs to package main, which tells the Go compiler to create an executable.
cmd/intro/main.go
Notice how we import our internal package using the full module path:
github.com/priyanshu-samal/Intro/internal/routesThe Logic Package
Theinternal/routes/routes.go file contains the business logic. By placing it in internal/, we signal that this code is specific to our application.
internal/routes/routes.go
How It Works
- Running
- Building
- Testing
When you run your application:Go compiles the
main package and links it with the imported routes package.The internal Directory Pattern
The internal directory is special in Go:
Best Practices
Keep main.go minimal
Your
main.go should primarily wire up dependencies and start the application. Business logic belongs in packages.Use meaningful package names
Package names should describe what the code does, not what it is:
- Good:
routes,users,auth - Bad:
helpers,utils,common
Next Steps
Now that you understand project structure, you’re ready to learn about:- The Go Runtime - How Go manages memory and executes your code
- Methods - Attaching behavior to your types
- Interfaces - Writing flexible, testable code