|
| 1 | +# Go Development Instructions |
| 2 | + |
| 3 | +Follow idiomatic Go practices and community standards when writing Go code. These instructions are based on [Effective Go](https://go.dev/doc/effective_go), [Go Code Review Comments](https://go.dev/wiki/CodeReviewComments), and [Google's Go Style Guide](https://google.github.io/styleguide/go/). |
| 4 | + |
| 5 | +## General Instructions |
| 6 | + |
| 7 | +- Write simple, clear, and idiomatic Go code |
| 8 | +- Favor clarity and simplicity over cleverness |
| 9 | +- Follow the principle of least surprise |
| 10 | +- Keep the happy path left-aligned (minimize indentation) |
| 11 | +- Return early to reduce nesting |
| 12 | +- Make the zero value useful |
| 13 | +- Document exported types, functions, methods, and packages |
| 14 | +- Use Go modules for dependency management |
| 15 | + |
| 16 | +## Naming Conventions |
| 17 | + |
| 18 | +### Packages |
| 19 | + |
| 20 | +- Use lowercase, single-word package names |
| 21 | +- Avoid underscores, hyphens, or mixedCaps |
| 22 | +- Choose names that describe what the package provides, not what it contains |
| 23 | +- Avoid generic names like `util`, `common`, or `base` |
| 24 | +- Package names should be singular, not plural |
| 25 | + |
| 26 | +### Variables and Functions |
| 27 | + |
| 28 | +- Use mixedCaps or MixedCaps (camelCase) rather than underscores |
| 29 | +- Keep names short but descriptive |
| 30 | +- Use single-letter variables only for very short scopes (like loop indices) |
| 31 | +- Exported names start with a capital letter |
| 32 | +- Unexported names start with a lowercase letter |
| 33 | +- Avoid stuttering (e.g., avoid `http.HTTPServer`, prefer `http.Server`) |
| 34 | + |
| 35 | +### Interfaces |
| 36 | + |
| 37 | +- Name interfaces with -er suffix when possible (e.g., `Reader`, `Writer`, `Formatter`) |
| 38 | +- Single-method interfaces should be named after the method (e.g., `Read` → `Reader`) |
| 39 | +- Keep interfaces small and focused |
| 40 | + |
| 41 | +### Constants |
| 42 | + |
| 43 | +- Use MixedCaps for exported constants |
| 44 | +- Use mixedCaps for unexported constants |
| 45 | +- Group related constants using `const` blocks |
| 46 | +- Consider using typed constants for better type safety |
| 47 | + |
| 48 | +## Code Style and Formatting |
| 49 | + |
| 50 | +### Formatting |
| 51 | + |
| 52 | +- Always use `gofmt` to format code |
| 53 | +- Use `goimports` to manage imports automatically |
| 54 | +- Keep line length reasonable (no hard limit, but consider readability) |
| 55 | +- Add blank lines to separate logical groups of code |
| 56 | + |
| 57 | +### Comments |
| 58 | + |
| 59 | +- Write comments in complete sentences |
| 60 | +- Start sentences with the name of the thing being described |
| 61 | +- Package comments should start with "Package [name]" |
| 62 | +- Use line comments (`//`) for most comments |
| 63 | +- Use block comments (`/* */`) sparingly, mainly for package documentation |
| 64 | +- Document why, not what, unless the what is complex |
| 65 | + |
| 66 | +### Error Handling |
| 67 | + |
| 68 | +- Check errors immediately after the function call |
| 69 | +- Don't ignore errors using `_` unless you have a good reason (document why) |
| 70 | +- Wrap errors with context using `fmt.Errorf` with `%w` verb |
| 71 | +- Create custom error types when you need to check for specific errors |
| 72 | +- Place error returns as the last return value |
| 73 | +- Name error variables `err` |
| 74 | +- Keep error messages lowercase and don't end with punctuation |
| 75 | + |
| 76 | +## Architecture and Project Structure |
| 77 | + |
| 78 | +### Package Organization |
| 79 | + |
| 80 | +- Follow standard Go project layout conventions |
| 81 | +- Keep `main` packages in `cmd/` directory |
| 82 | +- Put reusable packages in `pkg/` or `internal/` |
| 83 | +- Use `internal/` for packages that shouldn't be imported by external projects |
| 84 | +- Group related functionality into packages |
| 85 | +- Avoid circular dependencies |
| 86 | + |
| 87 | +### Dependency Management |
| 88 | + |
| 89 | +- Use Go modules (`go.mod` and `go.sum`) |
| 90 | +- Keep dependencies minimal |
| 91 | +- Regularly update dependencies for security patches |
| 92 | +- Use `go mod tidy` to clean up unused dependencies |
| 93 | +- Vendor dependencies only when necessary |
| 94 | + |
| 95 | +## Type Safety and Language Features |
| 96 | + |
| 97 | +### Type Definitions |
| 98 | + |
| 99 | +- Define types to add meaning and type safety |
| 100 | +- Use struct tags for JSON, XML, database mappings |
| 101 | +- Prefer explicit type conversions |
| 102 | +- Use type assertions carefully and check the second return value |
| 103 | + |
| 104 | +### Pointers vs Values |
| 105 | + |
| 106 | +- Use pointers for large structs or when you need to modify the receiver |
| 107 | +- Use values for small structs and when immutability is desired |
| 108 | +- Be consistent within a type's method set |
| 109 | +- Consider the zero value when choosing pointer vs value receivers |
| 110 | + |
| 111 | +### Interfaces and Composition |
| 112 | + |
| 113 | +- Accept interfaces, return concrete types |
| 114 | +- Keep interfaces small (1-3 methods is ideal) |
| 115 | +- Use embedding for composition |
| 116 | +- Define interfaces close to where they're used, not where they're implemented |
| 117 | +- Don't export interfaces unless necessary |
| 118 | + |
| 119 | +## Concurrency |
| 120 | + |
| 121 | +### Goroutines |
| 122 | + |
| 123 | +- Don't create goroutines in libraries; let the caller control concurrency |
| 124 | +- Always know how a goroutine will exit |
| 125 | +- Use `sync.WaitGroup` or channels to wait for goroutines |
| 126 | +- Avoid goroutine leaks by ensuring cleanup |
| 127 | + |
| 128 | +### Channels |
| 129 | + |
| 130 | +- Use channels to communicate between goroutines |
| 131 | +- Don't communicate by sharing memory; share memory by communicating |
| 132 | +- Close channels from the sender side, not the receiver |
| 133 | +- Use buffered channels when you know the capacity |
| 134 | +- Use `select` for non-blocking operations |
| 135 | + |
| 136 | +### Synchronization |
| 137 | + |
| 138 | +- Use `sync.Mutex` for protecting shared state |
| 139 | +- Keep critical sections small |
| 140 | +- Use `sync.RWMutex` when you have many readers |
| 141 | +- Prefer channels over mutexes when possible |
| 142 | +- Use `sync.Once` for one-time initialization |
| 143 | + |
| 144 | +## Error Handling Patterns |
| 145 | + |
| 146 | +### Creating Errors |
| 147 | + |
| 148 | +- Use `errors.New` for simple static errors |
| 149 | +- Use `fmt.Errorf` for dynamic errors |
| 150 | +- Create custom error types for domain-specific errors |
| 151 | +- Export error variables for sentinel errors |
| 152 | +- Use `errors.Is` and `errors.As` for error checking |
| 153 | + |
| 154 | +### Error Propagation |
| 155 | + |
| 156 | +- Add context when propagating errors up the stack |
| 157 | +- Don't log and return errors (choose one) |
| 158 | +- Handle errors at the appropriate level |
| 159 | +- Consider using structured errors for better debugging |
| 160 | + |
| 161 | +## API Design |
| 162 | + |
| 163 | +### HTTP Handlers |
| 164 | + |
| 165 | +- Use `http.HandlerFunc` for simple handlers |
| 166 | +- Implement `http.Handler` for handlers that need state |
| 167 | +- Use middleware for cross-cutting concerns |
| 168 | +- Set appropriate status codes and headers |
| 169 | +- Handle errors gracefully and return appropriate error responses |
| 170 | + |
| 171 | +### JSON APIs |
| 172 | + |
| 173 | +- Use struct tags to control JSON marshaling |
| 174 | +- Validate input data |
| 175 | +- Use pointers for optional fields |
| 176 | +- Consider using `json.RawMessage` for delayed parsing |
| 177 | +- Handle JSON errors appropriately |
| 178 | + |
| 179 | +## Performance Optimization |
| 180 | + |
| 181 | +### Memory Management |
| 182 | + |
| 183 | +- Minimize allocations in hot paths |
| 184 | +- Reuse objects when possible (consider `sync.Pool`) |
| 185 | +- Use value receivers for small structs |
| 186 | +- Preallocate slices when size is known |
| 187 | +- Avoid unnecessary string conversions |
| 188 | + |
| 189 | +### Profiling |
| 190 | + |
| 191 | +- Use built-in profiling tools (`pprof`) |
| 192 | +- Benchmark critical code paths |
| 193 | +- Profile before optimizing |
| 194 | +- Focus on algorithmic improvements first |
| 195 | +- Consider using `testing.B` for benchmarks |
| 196 | + |
| 197 | +## Testing |
| 198 | + |
| 199 | +### Test Organization |
| 200 | + |
| 201 | +- Keep tests in the same package (white-box testing) |
| 202 | +- Use `_test` package suffix for black-box testing |
| 203 | +- Name test files with `_test.go` suffix |
| 204 | +- Place test files next to the code they test |
| 205 | + |
| 206 | +### Writing Tests |
| 207 | + |
| 208 | +- Use table-driven tests for multiple test cases |
| 209 | +- Name tests descriptively using `Test_functionName_scenario` |
| 210 | +- Use subtests with `t.Run` for better organization |
| 211 | +- Test both success and error cases |
| 212 | +- Use `testify` or similar libraries sparingly |
| 213 | + |
| 214 | +### Test Helpers |
| 215 | + |
| 216 | +- Mark helper functions with `t.Helper()` |
| 217 | +- Create test fixtures for complex setup |
| 218 | +- Use `testing.TB` interface for functions used in tests and benchmarks |
| 219 | +- Clean up resources using `t.Cleanup()` |
| 220 | + |
| 221 | +## Security Best Practices |
| 222 | + |
| 223 | +### Input Validation |
| 224 | + |
| 225 | +- Validate all external input |
| 226 | +- Use strong typing to prevent invalid states |
| 227 | +- Sanitize data before using in SQL queries |
| 228 | +- Be careful with file paths from user input |
| 229 | +- Validate and escape data for different contexts (HTML, SQL, shell) |
| 230 | + |
| 231 | +### Cryptography |
| 232 | + |
| 233 | +- Use standard library crypto packages |
| 234 | +- Don't implement your own cryptography |
| 235 | +- Use crypto/rand for random number generation |
| 236 | +- Store passwords using bcrypt or similar |
| 237 | +- Use TLS for network communication |
| 238 | + |
| 239 | +## Documentation |
| 240 | + |
| 241 | +### Code Documentation |
| 242 | + |
| 243 | +- Document all exported symbols |
| 244 | +- Start documentation with the symbol name |
| 245 | +- Use examples in documentation when helpful |
| 246 | +- Keep documentation close to code |
| 247 | +- Update documentation when code changes |
| 248 | + |
| 249 | +### README and Documentation Files |
| 250 | + |
| 251 | +- Include clear setup instructions |
| 252 | +- Document dependencies and requirements |
| 253 | +- Provide usage examples |
| 254 | +- Document configuration options |
| 255 | +- Include troubleshooting section |
| 256 | + |
| 257 | +## Tools and Development Workflow |
| 258 | + |
| 259 | +### Essential Tools |
| 260 | + |
| 261 | +- `go fmt`: Format code |
| 262 | +- `go vet`: Find suspicious constructs |
| 263 | +- `golint` or `golangci-lint`: Additional linting |
| 264 | +- `go test`: Run tests |
| 265 | +- `go mod`: Manage dependencies |
| 266 | +- `go generate`: Code generation |
| 267 | + |
| 268 | +### Development Practices |
| 269 | + |
| 270 | +- Run tests before committing |
| 271 | +- Use pre-commit hooks for formatting and linting |
| 272 | +- Keep commits focused and atomic |
| 273 | +- Write meaningful commit messages |
| 274 | +- Review diffs before committing |
| 275 | + |
| 276 | +## Common Pitfalls to Avoid |
| 277 | + |
| 278 | +- Not checking errors |
| 279 | +- Ignoring race conditions |
| 280 | +- Creating goroutine leaks |
| 281 | +- Not using defer for cleanup |
| 282 | +- Modifying maps concurrently |
| 283 | +- Not understanding nil interfaces vs nil pointers |
| 284 | +- Forgetting to close resources (files, connections) |
| 285 | +- Using global variables unnecessarily |
| 286 | +- Over-using empty interfaces (`interface{}`) |
| 287 | +- Not considering the zero value of types |
0 commit comments