Development Rules
General Principles (Clean Code)
Constants Over Magic Numbers
- Replace hard-coded values with named constants.
- Use descriptive constant names that explain the value's purpose.
- Keep constants at the top of the file or in a dedicated constants file.
Meaningful Names
- Variables, functions, and types should reveal their purpose.
- Names should explain why something exists and how it's used.
- Avoid abbreviations unless they're universally understood.
- Go Specific: Use
PascalCasefor exported identifiers andcamelCasefor unexported ones.
Smart Comments
- Don't comment on what the code does - make the code self-documenting.
- Use comments to explain why something is done a certain way (decision documentation).
- Document APIs, complex algorithms, and non-obvious side effects.
Single Responsibility & DRY
- Each function should do exactly one thing and be small and focused.
- Extract repeated code into reusable functions.
- Maintain single sources of truth.
Encapsulation
- Hide implementation details.
- Expose clear interfaces.
- Move nested conditionals into well-named functions.
Go Development Rules
Error Handling
- Always check errors:
if err != nil { ... }. - Return errors to the caller rather than panicking (except during initialization).
- Use custom error types when beneficial for the caller.
- Wrap errors with context when propagating them (e.g.,
fmt.Errorf("failed to process item: %w", err)).
Concurrency
- Utilize Go's built-in concurrency features (goroutines, channels) when beneficial for performance, but avoid over-engineering.
- Always manage goroutine lifecycles (use
contextfor cancellation). - Use
sync.Mutexorsync.RWMutexto protect shared state.
Dependency Management
- Use Go Modules.
- Group imports: Standard library, Third-party, Internal project imports.
Backend & API Development
API Structure (REST/Gin)
- Follow RESTful API design principles.
- Use appropriate HTTP status codes (200 OK, 201 Created, 400 Bad Request, 500 Internal Server Error).
- Format JSON responses consistently.
- Implement input validation for all API endpoints.
Security & Best Practices
- Input Validation: Validate all incoming data.
- SQL Injection: Use prepared statements or ORM features that handle parameterization safely.
- Authentication/Authorization: Implement proper checks (middleware) before processing sensitive requests.
- Logging: Use structured logging (
logrus) for errors and important events. Do not log sensitive data (passwords, tokens). - Rate Limiting: Implement rate limiting to protect API resources.
Database Interaction
- Use connection pooling to improve performance.
- Close database connections/rows when they are no longer needed (defer
rows.Close()). - Handle database errors gracefully.
- Consider using an ORM for complex queries and data modeling.
Scalability & Performance
- Consider caching strategies for read-heavy operations.
- Optimize database queries (indexing, avoiding N+1 problems).
- Design for horizontal scalability (stateless services where possible).
Version Control (Git)
- Write clear, imperative commit messages (e.g., "Add user login endpoint" not "Added user login endpoint").
- Make small, focused commits.
- Review code for cleanliness and adherence to these rules before committing.
Go ServeMux REST API Rules (Cursor Rules)
General Guidelines
- You are an expert AI programming assistant specializing in building APIs with Go, using the standard library's net/http package and the new ServeMux introduced in Go 1.22.
- Always use the latest stable version of Go (1.22 or newer) and be familiar with RESTful API design principles, best practices, and Go idioms.
- Follow the user's requirements carefully & to the letter.
- Planning: First think step-by-step - describe your plan for the API structure, endpoints, and data flow in pseudocode, written out in great detail. Confirm the plan, then write code!
- Write correct, up-to-date, bug-free, fully functional, secure, and efficient Go code for APIs.
- Leverage the power and simplicity of Go's standard library to create efficient and idiomatic APIs.
Implementation Details
- Error Handling: Implement proper error handling, including custom error types when beneficial.
- Response Formatting: Use appropriate status codes and format JSON responses correctly.
- Validation: Implement input validation for API endpoints.
- Concurrency: Utilize Go's built-in concurrency features when beneficial for API performance.
- Logging: Implement proper logging using the standard library's log package or a simple custom logger.
- Middleware: Consider implementing middleware for cross-cutting concerns (e.g., logging, authentication).
- Security: Implement rate limiting and authentication/authorization when appropriate. Always prioritize security, scalability, and maintainability.
- Completeness: Leave NO todos, placeholders, or missing pieces in the API implementation.
- Comments: Be concise in explanations, but provide brief comments for complex logic or Go-specific idioms.
- Testing: Offer suggestions for testing the API endpoints using Go's testing package.
Go Backend Scalability Rules
General Expertise
- Consider scalability, reliability, maintainability, and security in all recommendations.
- Key areas: Database Management, API Development (REST, gRPC), Performance Optimization, Caching Strategies, Data Infrastructure (Kafka, Redis), and Containerization.
gRPC & Protocol Buffers
- Proto Files: Define clear messages/services. Use proper types/naming. Ensure
go_packageis correct. - Implementation: Generate code with
protoc. Handle errors/validation properly. - Database: Connect using
database/sqlor ORM (e.g. GORM). Use prepared statements.
Node.js and Express.js Best Practices
Project Structure
- Use proper directory structure.
- Implement proper module organization.
- Keep routes organized by domain.
- Implement proper error handling.
Express Setup
- Use proper middleware setup.
- Implement proper routing.
- Configure proper security middleware (CORS, Helmet).
- Implement proper validation.
Database & Auth
- Use proper ORM/ODM (Mongoose/Sequelize/Prisma).
- Implement proper migrations.
- Implement proper JWT handling and password hashing.
- Handle auth errors properly.
Performance & Security
- Implement proper caching and async operations.
- Implement proper rate limiting and input validation.
- Use proper security headers.
- Handle high traffic properly.
Testing & Deployment
- Write proper unit and integration tests.
- Use proper Docker setup and environment variables.
- Implement proper CI/CD.