Best Practices and Code Organization
The 10,000-Line main.go That Made Me Cry
package main
import (
// 47 imports...
)
// 23 global variables
var db *sql.DB
var cache *redis.Client
var logger *log.Logger
// ... 20 more
// 147 functions in no particular order
func handleUserCreate(w http.ResponseWriter, r *http.Request) { }
func validateEmail(email string) bool { }
func connectDatabase() error { }
func processPayment(amount float64) error { }
// ... 143 more functionsStandard Go Project Layout
Small Project
Medium Project
Large Project (Standard Layout)
Directory Purposes
Package Organization Principles
Organize by Feature, Not Layer
Small, Focused Packages
Naming Conventions
Package Names
File Names
Variable Names
Function Names
Constants
Go Tools
gofmt - Format Code
go vet - Check for Bugs
golint - Style Checker
staticcheck - Advanced Linter
golangci-lint - Meta Linter
Code Review Checklist
Error Handling
Resource Management
Goroutine Leaks
Nil Checks
Interface Segregation
Effective Go Principles
Accept Interfaces, Return Structs
Handle Errors, Don't Panic
Use Context for Cancellation
Prefer Composition Over Inheritance
Common Mistakes to Avoid
Mistake 1: Goroutines Without Exit
Mistake 2: Ignoring Error Returns
Mistake 3: Pointer to Loop Variable
Mistake 4: Not Closing Channels
Mistake 5: Race Conditions
Real Example: Refactored Project Structure
Before (10,000 lines in main.go)
After (organized structure)
Your Challenge
Key Takeaways
What I Learned
Last updated