github.com/kaptinlin/jsonschema@v0.4.6/.cursor/golang-rules.mdc (about)

     1  ---
     2  description:
     3  globs:
     4  alwaysApply: true
     5  ---
     6  # Golang Rules for JSON Schema Validator
     7  
     8  ## ๐ŸŽฏ Core Principles
     9  
    10  ### Code Style
    11  - Follow `gofmt` and `goimports` strictly
    12  - Use `golangci-lint` with strict settings
    13  - Prefer short, clear variable names in limited scopes
    14  - Document all exported APIs with examples
    15  
    16  ### Dependencies & Modules
    17  - Pin exact versions for reproducible builds
    18  - Use `go mod tidy` regularly
    19  - Group imports: stdlib โ†’ third-party โ†’ local
    20  - Minimize external dependencies for core functionality
    21  
    22  ## ๐Ÿš€ Modern Go Features
    23  
    24  ### Generics & Types
    25  - Use generics for type-safe collections and utilities
    26  - Prefer `any` over `interface{}`
    27  - Use type constraints appropriately (`comparable`, `constraints.Ordered`)
    28  - Apply generics judiciously - avoid over-engineering
    29  
    30  ### Error Handling
    31  - Use `errors.Is()` and `errors.As()` for error checking
    32  - Wrap errors with context: `fmt.Errorf("operation failed: %w", err)`
    33  - Create domain-specific error types with error codes
    34  - Design errors for internationalization from the start
    35  
    36  ### Context & Lifecycle
    37  - Pass `context.Context` as first parameter when applicable
    38  - Use `context.WithTimeout` for operations with deadlines
    39  - Check `ctx.Err()` in long-running operations
    40  - Propagate context through API boundaries
    41  
    42  ## ๐Ÿ” Validation Library Specific
    43  
    44  ### Input Type Handling
    45  - Support multiple input types consistently: `[]byte`, `map[string]interface{}`, structs
    46  - Handle `[]byte` intelligently: parse as JSON if valid, treat as raw bytes otherwise
    47  - Use type switches for clean, efficient input processing
    48  - Document input type behavior clearly in API
    49  
    50  ### Performance Optimization
    51  - Pre-allocate slices and maps with known capacity
    52  - Cache compiled schemas and reflection data
    53  - Use `sync.Pool` for frequently allocated objects
    54  - Implement zero-allocation paths for hot code
    55  - Profile and benchmark critical paths continuously
    56  
    57  ### Schema Compilation
    58  - Compile schemas once, validate many times
    59  - Cache `reflect.Type` and field information
    60  - Use concurrent-safe caching with appropriate locking
    61  - Optimize for both compilation and validation speed
    62  
    63  ### Type Conversion & Reflection
    64  - Cache struct field metadata to avoid repeated reflection
    65  - Use type assertions before falling back to reflection
    66  - Implement fast paths for common types (string, int, bool, time.Time)
    67  - Minimize reflection usage in validation hot paths
    68  
    69  ## ๐Ÿงช Testing Strategy
    70  
    71  ### Test Coverage
    72  - Test all supported input types comprehensively
    73  - Include edge cases: nil pointers, empty values, nested structures
    74  - Use table-driven tests for multiple scenarios
    75  - Integrate official test suites (JSON Schema Test Suite)
    76  
    77  ### Performance Testing
    78  - Write benchmarks for all critical paths
    79  - Track memory allocations and CPU usage
    80  - Test both simple and complex validation scenarios
    81  - Set performance regression thresholds in CI
    82  
    83  ### Error Testing
    84  - Verify error message accuracy and consistency
    85  - Test error localization and formatting
    86  - Validate error codes and contexts
    87  - Test error propagation through call stacks
    88  
    89  ## ๐Ÿ“š API Design
    90  
    91  ### Public Interface
    92  - Design APIs for multiple input types from the start
    93  - Provide consistent behavior across all input types
    94  - Document performance characteristics clearly
    95  - Follow Go idioms for method naming and signatures
    96  
    97  ### Backward Compatibility
    98  - Use semantic versioning strictly
    99  - Deprecate features gracefully with clear migration paths
   100  - Maintain API stability for core functionality
   101  - Document breaking changes thoroughly
   102  
   103  ### Documentation
   104  - Document all exported functions, types, and constants
   105  - Explain behavior differences between input types
   106  - Include performance notes for resource-intensive operations
   107  - Provide comprehensive usage examples
   108  
   109  ## ๐ŸŒ Internationalization
   110  
   111  ### Error Messages
   112  - Use error codes instead of hardcoded strings
   113  - Support message localization with context parameters
   114  - Provide fallback to English for missing translations
   115  - Design error types to carry localization context
   116  
   117  ### Localization Support
   118  - Separate message keys from display text
   119  - Support cultural formatting differences
   120  - Handle pluralization rules correctly
   121  - Use structured error data for translation
   122  
   123  ## โšก Performance Guidelines
   124  
   125  ### Memory Management
   126  - Reuse buffers with `sync.Pool`
   127  - Avoid string concatenation in loops
   128  - Use `strings.Builder` for dynamic string construction
   129  - Cache expensive computations
   130  
   131  ### JSON Processing
   132  - Allow custom JSON encoders/decoders (sonic, jsoniter)
   133  - Use streaming JSON for large inputs when possible
   134  - Pre-define struct tags to avoid runtime reflection
   135  - Handle JSON unmarshaling errors gracefully
   136  
   137  ### Concurrency
   138  - Use `sync.RWMutex` for read-heavy caches
   139  - Prefer channels for coordination, mutexes for protection
   140  - Avoid goroutines for simple, fast operations
   141  - Design thread-safe APIs by default
   142  
   143  ## ๐Ÿšซ Anti-Patterns
   144  
   145  ### Performance
   146  - Don't allocate in validation hot paths unnecessarily
   147  - Avoid reflection when type assertions work
   148  - Don't copy large structs by value
   149  - Avoid string concatenation with `+` in loops
   150  
   151  ### API Design
   152  - Don't ignore input type differences in behavior
   153  - Avoid mutable global state in validators
   154  - Don't skip validation for "trusted" input
   155  - Avoid breaking API changes in minor versions
   156  
   157  ### Error Handling
   158  - Don't ignore errors or use blank assignments
   159  - Don't use `panic()` for expected error conditions
   160  - Avoid generic error messages without context
   161  - Don't return errors without proper wrapping
   162  
   163  ## ๐Ÿ”ง Development Tools
   164  
   165  ### Required Tools
   166  ```bash
   167  go install golang.org/x/tools/cmd/goimports@latest
   168  go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest
   169  go install honnef.co/go/tools/cmd/staticcheck@latest
   170  ```
   171  
   172  ### CI/CD Integration
   173  - Run `go vet`, `golangci-lint`, and `staticcheck` in CI
   174  - Include comprehensive test coverage reporting
   175  - Run benchmarks and track performance regressions
   176  - Validate against official JSON Schema test suites
   177  - Test on multiple Go versions
   178  
   179  ### Code Quality
   180  - Set up pre-commit hooks for formatting and linting
   181  - Use `goimports` on save in editor
   182  - Configure benchmark result tracking
   183  - Integrate with code coverage tools
   184  
   185  ---
   186  
   187  > ๐Ÿ’ก **Focus**: Build a fast, correct, and maintainable JSON Schema validator. Prioritize correctness first, then optimize for performance without sacrificing code clarity.