1.2 KiB
1.2 KiB
Go Best Practices
Code Style
- Use
gofmtfor formatting - Use
golintandgo vetfor linting - Follow effective Go guidelines
- Keep functions short and focused
Error Handling
// GOOD: Check and handle errors
func readConfig(path string) (*Config, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("reading config: %w", err)
}
var config Config
if err := json.Unmarshal(data, &config); err != nil {
return nil, fmt.Errorf("parsing config: %w", err)
}
return &config, nil
}
// BAD: Ignoring errors
func readConfig(path string) *Config {
data, _ := os.ReadFile(path) // Don't ignore errors
var config Config
json.Unmarshal(data, &config)
return &config
}
Concurrency
- Use channels for communication between goroutines
- Use
sync.WaitGroupfor waiting on multiple goroutines - Use
context.Contextfor cancellation and timeouts - Avoid shared mutable state; prefer message passing
Security
- Use
html/templatefor HTML output (auto-escaping) - Use parameterized queries for SQL
- Validate all input at API boundaries
- Use
crypto/randfor secure random numbers