Comprehensive Go development guide covering code organization, performance, security, testing, design patterns, error handling, and common pitfalls. Ideal for building scalable Go applications with proper structure and maintainable code.
Comprehensive guide for developing high-quality Go applications following industry best practices.
Provides expert guidance on Go development covering:
**Directory Structure:**
```
project-name/
├── cmd/ # Application entry points
│ └── project-name/
│ └── main.go
├── internal/ # Private application code
│ ├── app/ # Business logic
│ ├── domain/ # Core domain types
│ └── pkg/ # Internal utilities
├── pkg/ # Public libraries
├── api/ # API definitions
├── web/ # Web assets
├── scripts/ # Build/deployment scripts
├── configs/ # Configuration files
├── go.mod
└── README.md
```
**Key Principles:**
**Module Organization:**
**Layered Architecture:**
**Dependency Injection:**
```go
type Server struct {
Addr string
Port int
Protocol string
Timeout time.Duration
}
type Option func(*Server)
func WithAddress(addr string) Option {
return func(s *Server) {
s.Addr = addr
}
}
func NewServer(options ...Option) *Server {
srv := &Server{
Addr: "localhost",
Port: 8080,
Protocol: "tcp",
Timeout: 30 * time.Second,
}
for _, option := range options {
option(srv)
}
return srv
}
```
**Context Pattern:**
```go
func handleRequest(ctx context.Context, req *http.Request) {
select {
case <-ctx.Done():
// Operation cancelled
return
default:
// Process the request
}
}
```
**Middleware Pattern:**
```go
func loggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Request: %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
}
```
**Always Handle Errors:**
```go
// Bad
_, _ = fmt.Println("Hello, world!")
// Good
_, err := fmt.Println("Hello, world!")
if err != nil {
log.Println("Error printing: ", err)
}
```
**Error Wrapping:**
```go
func readFile(filename string) ([]byte, error) {
data, err := ioutil.ReadFile(filename)
if err != nil {
return nil, fmt.Errorf("failed to read file %s: %w", filename, err)
}
return data, nil
}
```
**Custom Error Types:**
```go
type NotFoundError struct {
Resource string
}
func (e *NotFoundError) Error() string {
return fmt.Sprintf("%s not found", e.Resource)
}
```
**Sentinel Errors:**
```go
var ErrNotFound = errors.New("not found")
func getUser(id int) (*User, error) {
if id == 0 {
return nil, ErrNotFound
}
// ...
}
```
**Profiling:**
```bash
go tool pprof http://localhost:6060/debug/pprof/profile # CPU
go tool pprof http://localhost:6060/debug/pprof/heap # Memory
```
**Benchmarking:**
```go
func BenchmarkFunction(b *testing.B) {
for i := 0; i < b.N; i++ {
// Code to benchmark
}
}
```
**String Concatenation:**
```go
var sb strings.Builder
for i := 0; i < 1000; i++ {
sb.WriteString("hello")
}
result := sb.String()
```
**State Management with Mutex:**
```go
var mu sync.Mutex
var counter int
func incrementCounter() {
mu.Lock()
defer mu.Unlock()
counter++
}
```
**Configuration Management:**
**Logging:**
**Database Access:**
**HTTP Handling:**
**Input Validation:**
**Resource Cleanup:**
```go
func processFile(filename string) error {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close() // Ensure cleanup
// ...
}
```
**Creating a new Go service with proper structure:**
1. Initialize module: `go mod init github.com/username/project`
2. Create directory structure following the layout above
3. Implement layered architecture with dependency injection
4. Add comprehensive error handling with wrapped errors
5. Include benchmarks and profiling for critical paths
6. Use context for cancellation and timeouts
7. Implement middleware for cross-cutting concerns
**Refactoring existing code:**
1. Profile to identify bottlenecks
2. Apply optimization techniques (string builders, object pooling)
3. Add proper error wrapping and custom error types
4. Implement synchronization primitives for concurrent access
5. Add comprehensive tests and benchmarks
Leave a review
No reviews yet. Be the first to review this skill!
# Download SKILL.md from killerskills.ai/api/skills/go-best-practices-and-architecture/raw