Golang Basics - Project Structure
π§± Basic Structure of a Go File
This is a pretty simple code to debscribe Golangβs key elements
package main
import "fmt"
func main(){
fmt.print("it works! yay!")
}
π¦ package:
Every Go source file starts with a package declaration. It defines which package the file belongs to.
package main: This is a special package name. Programs with this package are executable (not just reusable libraries). For libraries or shared code, you typically use something like package utils, package models, etc.
π₯ import
The import statement brings in external packages so you can use their exported functions, types, etc.
- You can import standard library packages like fmt, math/rand, or third-party packages.
- If youβre importing multiple packages, wrap them in parentheses.
example:
import (
"fmt"
"strings"
)
π§ Functions
Functions are declared using the func keyword.
- main(): This is the entry point when your Go program runs.
- Other functions can be defined to keep your code clean and modular.
π File and Directory Structure
Go encourages keeping your project organized in packages and modules.
Example structure:
myapp/
β
βββ go.mod
βββ go.sum
βββ main.go
βββ /cmd/
β βββ myapp/
β βββ main.go
βββ /internal/
β βββ auth/
β βββ token.go
βββ /pkg/
β βββ logger/
β βββ logger.go
βββ /api/
β βββ handlers.go
βββ /models/
βββ user.go
π§© Modules (go.mod)
go.mod defines the module name and tracks dependencies. Itβs created with:
go mod init github.com/yourname/myapp
Example content:
module github.com/yourname/myapp
go 1.20
main.go
or /cmd/myapp/main.go
- Your appβs entry point.
- If youβre building a CLI tool or server, this is where func main() lives.
- By convention, larger apps put their main logic in cmd/myapp/main.go.
cmd
- Each subfolder is an executable program.
- Example: cmd/myapp/main.go compiles into the myapp binary.
- You can have multiple CLI tools: e.g. cmd/admin, cmd/worker, etc.
internal
- Private application code β cannot be imported from outside your module.
- Helps enforce encapsulation.
- Example: internal/auth/token.go contains token-related logic that only your app can use.
pkg
- Public libraries intended to be reusable by others.
- If youβre building helper packages (e.g., logging, config loading), place them here.
- Example: pkg/logger/logger.go could be used by other apps if you open-source it.
api or handlers
- Defines HTTP routes, controllers, and API logic.
- You might also include middleware here.
models
- Struct definitions that map to database records or API models.
- Often used with ORMs like GORM.
File Naming Tips
- Filenames should match the content (e.g., user.go contains the User struct).
- Keep test files in the same package with _test.go suffix (e.g., user_test.go).
π§ Key Principles
- One package per folder: Each folder is its own package.
- Name packages clearly: e.g., utils, auth, config.
- Keep main() thin: Delegate logic to other packages.