agentleFS
FreePeakFreePeak/cortex/.cursor/rules/go-architecture.mdc

cortex / rules

Cursor rule27 starsChanged 20 months agoApache-2.0View on GitHub

  • Where files are headingNew Cursor rule files have more rules about planning and tracking tasks, and fewer about code style.

    Of the Cursor rule files we read, the 1,533 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repositoryOne other file it gives its agents.

The file

Show its rules and text

We split this go-architecture.mdc into the rules it gives an agent

41 rules. About 0 are common, 39 are distinctive, and 2 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈39

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 2

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Follow dependency rule: inner layers must not depend on outer layers

    line 12
  2. Distinctive:

    Use dependency injection for infrastructure dependencies

    line 14
  3. Distinctive:

    Use value objects for immutable concepts

    line 54
  4. Distinctive:

    Keep business logic in domain entities or domain services

    line 57
  5. Distinctive:

    Interface Segregation: Prefer small, focused interfaces (1-3 methods)

    line 65
  6. Distinctive:

    Use middleware for cross-cutting concerns

    line 70
  7. Distinctive:

    Create utility functions for repeated operations

    line 71
  8. Distinctive:

    Factory Pattern: Create complex objects

    line 76
  9. Distinctive:

    Decorator Pattern: Add behavior dynamically

    line 79
  10. Distinctive:

    Write tests before implementation code

    line 85
  11. Distinctive:

    Start with test cases that validate interface contracts

    line 86
  12. Distinctive:

    Use table-driven tests for comprehensive test coverage

    line 87
  13. Distinctive:

    Use mocks for external dependencies

    line 88
  14. Very specific:

    Run all tests after each change (go test ./...)

    line 89
  15. Distinctive:

    Test each layer independently

    line 92
  16. Distinctive:

    Use interfaces to mock dependencies

    line 93
  17. Distinctive:

    Write integration tests for critical paths

    line 96
  18. Very specific:

    Use meaningful package names (avoid util, common, etc.)

    line 102
  19. Distinctive:

    Follow standard Go project layout

    line 103
  20. Distinctive:

    Keep packages small and focused

    line 104
  21. Distinctive:

    Use custom error types for domain-specific errors

    line 107
  22. Distinctive:

    Check all error returns

    line 110
  23. Distinctive:

    Use structured logging with errors

    line 111
  24. Distinctive:

    Keep interfaces small (1-3 methods)

    line 115
  25. Distinctive:

    Use embedded interfaces to compose larger interfaces

    line 117
  26. Distinctive:

    Use goroutines and channels appropriately

    line 120
  27. Distinctive:

    Avoid shared memory; prefer communication

    line 121
  28. Distinctive:

    Use sync package for simple synchronization

    line 122
  29. Distinctive:

    Use pointers judiciously (only when mutation is needed)

    line 127
  30. Distinctive:

    Use sync.Pool for frequently allocated objects

    line 129
  31. Distinctive:

    Use prepared statements for security

    line 138
  32. Distinctive:

    Use context for timeouts and cancellation

    line 140
  33. Distinctive:

    Use environment variables with sane defaults

    line 157
  34. Distinctive:

    Keep sensitive information in environment variables

    line 160
  35. Distinctive:

    Generate domain entity: Create a new domain entity with validation methods

    line 236
  36. Distinctive:

    Implement repository: Create concrete implementation of a repository interface

    line 238
  37. Distinctive:

    Generate use case: Create a new use case implementing business logic

    line 239
  38. Distinctive:

    Add handler: Create a new HTTP handler for a use case

    line 240
  39. Distinctive:

    Add middleware: Create new middleware for cross-cutting concerns

    line 242
  40. Distinctive:

    Add factory method: Create factory method for complex object creation

    line 244
  41. Distinctive:

    Use built-in golang http server, not using other libs, including http mux

    line 245

≈ “Common” is an estimate: at least 1 in 5 of the 3,030 Cursor rule files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
go-architecture.mdc
---
description: 
globs: 
alwaysApply: true
---
# IDE Cursor Rules for Golang Development

## Architecture & Structure

1. **Clean Architecture**
   - Maintain clear separation between layers: domain, repository, usecase, handler
   - Follow dependency rule: inner layers must not depend on outer layers
   - Domain entities should not have dependencies on frameworks or external libraries
   - Use dependency injection for infrastructure dependencies

2. **Project Structure**
   ```
root/
├── cmd
│   ├── app
│   └── tools
├── config
├── documents
├── internal
│   ├── domain
│   │   ├── authentication
│   │   ├── shared
│   │   │   ├── errors
│   │   │   └── valueobjects
│   │   └── user
│   ├── infrastructure
│   │   ├── background
│   │   ├── db
│   │   │   ├── migrations
│   │   │   └── repository
│   │   ├── file_storage
│   │   ├── filestorage
│   │   ├── logging
│   │   ├── server
│   │   └── temporal
│   ├── interfaces
│   │   ├── persistence
│   │   └── rest
│   ├── middleware
│   ├── shared
│   └── usecases
├── pkg
│   └── utils

   ```

3. **Domain-Driven Design**
   - Model domain entities around business concepts
   - Use value objects for immutable concepts
   - Implement aggregate roots to maintain consistency boundaries
   - Define repository interfaces in the domain layer
   - Keep business logic in domain entities or domain services

## Code Quality Principles

4. **SOLID Principles**
   - **Single Responsibility**: Each struct/function should have only one reason to change
   - **Open/Closed**: Extend behavior through interfaces rather than modification
   - **Liskov Substitution**: Interface implementations must be substitutable
   - **Interface Segregation**: Prefer small, focused interfaces (1-3 methods)
   - **Dependency Inversion**: Depend on abstractions, not concrete implementations

5. **DRY (Don't Repeat Yourself)**
   - Extract common functionality into shared packages
   - Use middleware for cross-cutting concerns
   - Create utility functions for repeated operations
   - Implement generic repository patterns where appropriate

6. **Design Patterns**
   - **Repository Pattern**: Abstract data access behind interfaces
   - **Factory Pattern**: Create complex objects
   - **Strategy Pattern**: Switch algorithms at runtime
   - **Adapter Pattern**: Convert interfaces
   - **Decorator Pattern**: Add behavior dynamically
   - **Dependency Injection**: Provide dependencies from outside

## Development Approaches

7. **Test-Driven Development**
   - Write tests before implementation code
   - Start with test cases that validate interface contracts
   - Use table-driven tests for comprehensive test coverage
   - Use mocks for external dependencies
   - Run all tests after each change (`go test ./...`)

8. **Testing Practices**
   - Test each layer independently
   - Use interfaces to mock dependencies
   - Organize tests to mirror production code structure
   - Maintain test coverage above 80%
   - Write integration tests for critical paths

## Golang-Specific Best Practices

9. **Code Organization**
   - Group related functionality in packages
   - Use meaningful package names (avoid `util`, `common`, etc.)
   - Follow standard Go project layout
   - Keep packages small and focused

10. **Error Handling**
    - Use custom error types for domain-specific errors
    - Wrap errors with context using `fmt.Errorf("context: %w", err)`
    - Return errors rather than panic
    - Check all error returns
    - Use structured logging with errors

11. **Interfaces**
    - Define interfaces where behavior varies
    - Keep interfaces small (1-3 methods)
    - Define interfaces where they're used, not implemented
    - Use embedded interfaces to compose larger interfaces

12. **Concurrency**
    - Use goroutines and channels appropriately
    - Avoid shared memory; prefer communication
    - Use sync package for simple synchronization
    - Implement proper context propagation
    - Handle goroutine termination properly

13. **Performance**
    - Use pointers judiciously (only when mutation is needed)
    - Minimize allocations in hot paths
    - Use sync.Pool for frequently allocated objects
    - Benchmark performance-critical code
    - Profile before optimizing

## Implementation Guidelines

14. **Repository Layer**
    - Implement repository interfaces defined in domain
    - Handle database-specific errors and conversions
    - Use prepared statements for security
    - Implement proper transaction handling
    - Use context for timeouts and cancellation

15. **Use Case Layer**
    - Orchestrate domain operations
    - Validate input
    - Handle transaction boundaries
    - Implement business processes
    - Return domain objects (not persistence models)

16. **Handler Layer**
    - Convert between domain models and DTOs
    - Validate request parameters
    - Handle HTTP-specific concerns
    - Implement consistent error responses
    - Use middleware for cross-cutting concerns

17. **Configuration**
    - Use environment variables with sane defaults
    - Implement configuration validation
    - Support different environments (dev, test, prod)
    - Keep sensitive information in environment variables

## Specific Patterns

18. **Dependency Injection**
    ```go
    type Service struct {
        repo Repository
        logger Logger
    }
    
    func NewService(repo Repository, logger Logger) *Service {
        return &Service{
            repo: repo,
            logger: logger,
        }
    }
    ```

19. **Repository Interface**
    ```go
    type UserRepository interface {
        FindByID(ctx context.Context, id string) (*User, error)
        Save(ctx context.Context, user *User) error
        Delete(ctx context.Context, id string) error
    }
    ```

20. **Error Types**
    ```go
    type NotFoundError struct {
        Entity string
        ID     string
    }
    
    func (e *NotFoundError) Error() string {
        return fmt.Sprintf("%s with ID %s not found", e.Entity, e.ID)
    }
    ```

21. **Table-Driven Tests**
    ```go
    func TestValidateUser(t *testing.T) {
        tests := []struct {
            name    string
            user    User
            wantErr bool
        }{
            {"valid user", User{Name: "John", Email: "john@example.com"}, false},
            {"empty name", User{Email: "john@example.com"}, true},
            {"invalid email", User{Name: "John", Email: "invalid"}, true},
        }
        
        for _, tt := range tests {
            t.Run(tt.name, func(t *testing.T) {
                if err := ValidateUser(tt.user); (err != nil) != tt.wantErr {
                    t.Errorf("ValidateUser() error = %v, wantErr %v", err, tt.wantErr)
                }
            })
        }
    }
    ```

22. **Middleware Pattern**
    ```go
    func LoggingMiddleware(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            start := time.Now()
            next.ServeHTTP(w, r)
            log.Printf("%s %s took %s", r.Method, r.URL.Path, time.Since(start))
        })
    }
    ```

## Commands for IDE Cursor

- **Generate domain entity**: Create a new domain entity with validation methods
- **Create repository interface**: Generate a repository interface for a domain entity
- **Implement repository**: Create concrete implementation of a repository interface
- **Generate use case**: Create a new use case implementing business logic
- **Add handler**: Create a new HTTP handler for a use case
- **Create test**: Generate test boilerplate for any component
- **Add middleware**: Create new middleware for cross-cutting concerns
- **Refactor to interface**: Extract interface from concrete implementation
- **Add factory method**: Create factory method for complex object creation
- Use built-in golang http server, not using other libs, including http mux



Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.