Regenerate all MDC rules with fresh Exa data and December 2025 best practices

- Refreshed all 241 library rules with current best practices
- Updated Exa search results for all libraries with 2025 content
- Fixed --regenerate-all flag logic to properly process all libraries
- Removed duplicate astro entry in rules.json (merged tags)
- Added missing docker.mdc and vim.mdc files
- All rules now include modern patterns and anti-patterns
- Updated with framework-specific recommendations for 2025

Technical improvements:
- Fixed retry_failed_only logic in generate_mdc_files.py
- Improved progress tracking for regeneration scenarios
- Ensured proper handling of --refresh-exa flag
This commit is contained in:
sanjeed5
2025-12-17 22:40:28 +05:30
parent 331fb6ffac
commit 8fbf269085
244 changed files with 66701 additions and 52708 deletions
+368 -318
View File
@@ -1,406 +1,456 @@
---
description: This rule enforces best practices for using the `net/http` ServeMux in Go, promoting clean, maintainable, and efficient code. It covers routing, handler design, and error handling specifics to help developers leverage ServeMux effectively.
globs: *.go
description: This rule file provides definitive guidelines for using Go's `http.ServeMux` effectively, leveraging Go 1.22+ features for robust, maintainable, and secure API development.
globs: **/*.go
---
---
# servemux Best Practices and Coding Standards
# servemux Best Practices
This document provides comprehensive guidelines for using the `net/http` ServeMux in Go, promoting best practices, coding standards, and efficient development.
Go's `http.ServeMux`, especially with the enhancements in Go 1.22+, is the definitive choice for building performant and maintainable HTTP services. This guide outlines the best practices for its use.
## 1. Code Organization and Structure
### 1.1 Directory Structure Best Practices
Organize your application for clarity, testability, and scalability.
- **Modular Design:** Organize your code into logical modules, each responsible for a specific set of functionalities.
- **Handler Grouping:** Group related handlers within the same directory or package. For instance, all user-related handlers could reside in a `users` package.
- **Middleware Directory:** Create a dedicated `middleware` directory for reusable middleware functions.
- **Internal vs. External:** Utilize the `internal` directory to encapsulate code that should not be exposed outside your module. This enhances encapsulation and reduces the API surface.
### ✅ GOOD: Centralized Mux Assembly, Dedicated Handlers
Create a single `http.ServeMux` instance in your application's entry point (`cmd/server/main.go`) and register handlers from a dedicated `handlers` package. Inject business logic into handlers via interfaces.
project-root/
├── cmd/
│ └── my-app/
│ └── main.go
├── internal/
│ ├── handlers/
│ │ ├── users.go
│ │ └── products.go
│ └── middleware/
│ ├── auth.go
│ └── logging.go
├── pkg/
│ └── utils/
│ └── utils.go
└── go.mod
```go
// cmd/server/main.go
package main
import (
"context"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
### 1.2 File Naming Conventions
"yourproject/internal/handlers"
"yourproject/internal/service" // Business logic interface
)
- **Descriptive Names:** Use clear and descriptive file names that reflect the functionality they contain. For example, `users.go` for user-related handlers, and `auth.go` for authentication middleware.
- **Handler Specifics:** If a file contains a specific handler, name it accordingly. For example, `get_user_handler.go` or `create_product_handler.go`.
- **Lowercase:** Use lowercase for all file names.
func main() {
logger := log.New(os.Stdout, "API: ", log.Ldate|log.Ltime|log.Lshortfile)
### 1.3 Module Organization
// Initialize business logic (e.g., database connection)
userService := service.NewUserService(logger) // Assume concrete implementation
- **`go.mod`:** Ensure your project has a `go.mod` file to manage dependencies. Run `go mod init <module_name>` to create one.
- **Semantic Versioning:** Follow semantic versioning for your modules. Use tags (e.g., `v1.0.0`) to mark releases.
- **Vendor Dependencies:** Consider vendoring dependencies using `go mod vendor` to ensure reproducibility.
// Create and configure the mux
mux := http.NewServeMux()
handlers.RegisterRoutes(mux, logger, userService) // Pass dependencies
### 1.4 Component Architecture
server := &http.Server{
Addr: ":8080",
Handler: mux,
ReadTimeout: 5 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 120 * time.Second,
ErrorLog: logger,
}
- **Separation of Concerns:** Design your components to have a single responsibility. Separate handler logic from business logic and data access.
- **Interfaces:** Use interfaces to define contracts between components, promoting loose coupling and testability. For example:
// Start server in a goroutine
go func() {
logger.Printf("Server starting on %s", server.Addr)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
logger.Fatalf("Could not listen on %s: %v\n", server.Addr, err)
}
}()
go
type UserStore interface {
GetUser(id int) (*User, error)
CreateUser(user *User) error
// Graceful shutdown
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
logger.Println("Server shutting down...")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
logger.Fatalf("Server forced to shutdown: %v", err)
}
logger.Println("Server exited gracefully")
}
type UserHandler struct {
store UserStore
}
// internal/handlers/user.go
package handlers
### 1.5 Code Splitting Strategies
import (
"encoding/json"
"log"
"net/http"
"strconv"
"yourproject/internal/service" // Business logic interface
)
- **Package-Based Splitting:** Divide your application into packages based on functionality. Each package should be cohesive and have a clear purpose.
- **Feature-Based Splitting:** Organize code based on features. Each feature gets its own directory or package containing all relevant components.
- **Layered Architecture:** Implement a layered architecture (e.g., presentation, business logic, data access) and split the code accordingly.
## 2. Common Patterns and Anti-patterns
### 2.1 Design Patterns Specific to servemux
- **Middleware Chaining:** Implement middleware as a chain of functions that decorate the handler. This allows for modular and reusable logic. Example:
go
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("Request: %s %s", r.Method, r.URL.Path)
next.ServeHTTP(w, r)
})
// UserService defines the interface for user-related business logic.
type UserService interface {
GetUser(id int) (*service.User, error)
CreateUser(user *service.User) error
// ... other user methods
}
// Usage:
mux := http.NewServeMux()
mux.Handle("/", LoggingMiddleware(http.HandlerFunc(myHandler)))
- **Context-Aware Handlers:** Utilize the `context.Context` to pass request-scoped values to handlers. This facilitates tracing, request cancellation, and data sharing.
go
func MyHandler(w http.ResponseWriter, r *http.Request) {
userID := r.Context().Value("userID").(int)
// ...
// UserHandlers holds dependencies for user-related HTTP handlers.
type UserHandlers struct {
log *log.Logger
svc UserService
}
// Setting context value in middleware:
ctx := context.WithValue(r.Context(), "userID", 123)
r = r.WithContext(ctx)
// RegisterRoutes registers all user-related HTTP routes with the given mux.
func RegisterRoutes(mux *http.ServeMux, logger *log.Logger, userService UserService) {
uh := &UserHandlers{
log: logger,
svc: userService,
}
- **Route Grouping (with custom muxes):** Use separate ServeMux instances for different route groups (e.g., API v1, API v2, admin routes). This improves organization and maintainability.
go
v1Mux := http.NewServeMux()
v1Mux.HandleFunc("/users", v1UsersHandler)
v1Mux.HandleFunc("/products", v1ProductsHandler)
v2Mux := http.NewServeMux()
v2Mux.HandleFunc("/users", v2UsersHandler)
v2Mux.HandleFunc("/products", v2ProductsHandler)
http.Handle("/api/v1/", v1Mux)
http.Handle("/api/v2/", v2Mux)
### 2.2 Recommended Approaches for Common Tasks
- **Creating a New ServeMux:** Always use `http.NewServeMux()` to create a new ServeMux instance. Avoid using the default `http.DefaultServeMux` to prevent global state issues. Example:
go
mux := http.NewServeMux()
mux.HandleFunc("/", myHandler)
http.ListenAndServe(":8080", mux)
- **Registering Handlers:** Use `mux.HandleFunc()` or `mux.Handle()` to register handlers with the ServeMux.
go
mux.HandleFunc("/users", usersHandler)
mux.Handle("/products", productHandler{})
- **Serving Static Files:** Use `http.FileServer()` to serve static files.
go
fs := http.FileServer(http.Dir("./static"))
mux.Handle("/static/", http.StripPrefix("/static/", fs))
- **Handling HTTP Methods:** Use `http.MethodGet`, `http.MethodPost`, etc., constants to check the HTTP method. With Go 1.22+, specify methods in the pattern itself for `HandleFunc`.
go
mux.HandleFunc("GET /users/{id}", getUserHandler)
mux.HandleFunc("POST /users", createUserHandler)
### 2.3 Anti-patterns and Code Smells to Avoid
- **Global State:** Avoid using global variables or the default `http.DefaultServeMux` for request handling, as it can lead to race conditions and difficult debugging.
- **Overlapping Routes:** Be mindful of overlapping routes. Go 1.22+ will panic if conflicting patterns are registered. Ensure that your routes are distinct and do not cause conflicts. Properly consider precedence rules.
- **Ignoring Errors:** Always handle errors returned by functions. Log errors and return appropriate HTTP status codes to the client.
- **Long Handler Functions:** Keep handler functions short and focused. Delegate complex logic to other functions or services.
- **Hardcoding Values:** Avoid hardcoding configuration values. Use environment variables or configuration files.
- **Lack of Input Validation:** Always validate user input to prevent security vulnerabilities.
### 2.4 State Management Best Practices
- **Stateless Handlers:** Design handlers to be stateless whenever possible. If state is required, store it in the request context or an external data store.
- **Request-Scoped Values:** Use the `context.Context` to store request-scoped values. Avoid using global variables to store state related to a specific request.
- **Sessions:** Use secure session management techniques to maintain user sessions.
### 2.5 Error Handling Patterns
- **Centralized Error Handling:** Implement a centralized error handling middleware to catch and log errors. Return appropriate HTTP status codes and error messages to the client.
go
func ErrorHandlingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
log.Printf("Panic: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
- **Custom Error Types:** Define custom error types to provide more context about the error.
go
type ValidationError struct {
Field string
Message string
mux.HandleFunc("GET /users/{id}", uh.GetUser)
mux.HandleFunc("POST /users", uh.CreateUser)
// ... other route registrations
}
func (e *ValidationError) Error() string {
return fmt.Sprintf("Validation error: %s - %s", e.Field, e.Message)
}
// GetUser handles GET requests for /users/{id}
func (uh *UserHandlers) GetUser(w http.ResponseWriter, r *http.Request) {
idStr := r.PathValue("id")
id, err := strconv.Atoi(idStr)
if err != nil {
uh.respondWithError(w, http.StatusBadRequest, "Invalid user ID")
return
}
- **Logging Errors:** Log errors with sufficient detail for debugging.
- **Returning Appropriate Status Codes:** Return appropriate HTTP status codes based on the error. Use descriptive error messages in the response body.
user, err := uh.svc.GetUser(id)
if err != nil {
uh.respondWithError(w, http.StatusNotFound, "User not found")
return
}
## 3. Performance Considerations
### 3.1 Optimization Techniques
- **Connection Pooling:** Use connection pooling for database connections to reduce overhead.
- **Caching:** Implement caching for frequently accessed data to reduce database load.
- **Gzip Compression:** Enable Gzip compression for responses to reduce bandwidth usage.
go
func GzipMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
gz, err := gzip.NewWriterLevel(w, gzip.BestSpeed)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
defer gz.Close()
w.Header().Set("Content-Encoding", "gzip")
next.ServeHTTP(gzipResponseWriter{Writer: gz, ResponseWriter: w}, r)
} else {
next.ServeHTTP(w, r)
}
})
uh.respondWithJSON(w, http.StatusOK, user)
}
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
// CreateUser handles POST requests for /users
func (uh *UserHandlers) CreateUser(w http.ResponseWriter, r *http.Request) {
var user service.User // Assuming service.User is the DTO
if err := json.NewDecoder(r.Body).Decode(&user); err != nil {
uh.respondWithError(w, http.StatusBadRequest, "Invalid request payload")
return
}
if err := uh.svc.CreateUser(&user); err != nil {
uh.respondWithError(w, http.StatusInternalServerError, "Failed to create user")
return
}
uh.respondWithJSON(w, http.StatusCreated, user)
}
func (w gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
// respondWithError sends a JSON error response.
func (uh *UserHandlers) respondWithError(w http.ResponseWriter, code int, message string) {
uh.respondWithJSON(w, code, map[string]string{"error": message})
}
- **Keep-Alive Connections:** Enable keep-alive connections to reduce connection establishment overhead.
- **Efficient Data Structures:** Use efficient data structures and algorithms for data processing.
// respondWithJSON sends a JSON response.
func (uh *UserHandlers) respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
response, err := json.Marshal(payload)
if err != nil {
uh.log.Printf("Error marshaling JSON response: %v", err)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
w.Write(response)
}
```
### 3.2 Memory Management
### ❌ BAD: Global Mux, Logic in `main`, Repetitive Naming
- **Avoid Memory Leaks:** Be aware of potential memory leaks, especially when using goroutines. Ensure that all goroutines are properly terminated.
- **Object Pooling:** Consider using object pooling for frequently allocated objects.
- **String Conversions:** Minimize unnecessary string conversions, as they can be expensive.
- **Defer Statements:** Use `defer` statements carefully. While convenient, they can add overhead if overused in performance-critical sections.
Avoid using `http.DefaultServeMux` and polluting `main.go` with handler logic. Do not repeat package or receiver names in function signatures.
### 3.3 Rendering Optimization
```go
// main.go (BAD example)
package main
- **Template Caching:** Cache templates to reduce parsing overhead.
- **Efficient Template Rendering:** Use efficient template rendering techniques. Consider using pre-compiled templates.
- **Minimize DOM Updates:** Minimize DOM updates in the client-side JavaScript code.
import (
"fmt"
"log"
"net/http"
"strconv"
)
### 3.4 Bundle Size Optimization
// Bad naming: GetUserHandler repeats "User" and "Handler"
func GetUserHandler(w http.ResponseWriter, r *http.Request) {
idStr := r.PathValue("id")
id, err := strconv.Atoi(idStr)
if err != nil {
http.Error(w, "Invalid ID", http.StatusBadRequest)
return
}
// Business logic directly here, hard to test
fmt.Fprintf(w, "Getting user %d\n", id)
}
- **Code Minification:** Minify JavaScript and CSS code to reduce bundle size.
- **Tree Shaking:** Use tree shaking to remove unused code from the bundle.
- **Image Optimization:** Optimize images to reduce file size.
func main() {
// Bad: Using http.HandleFunc directly, relies on global DefaultServeMux
http.HandleFunc("GET /users/{id}", GetUserHandler)
log.Fatal(http.ListenAndServe(":8080", nil)) // nil uses DefaultServeMux
}
```
### 3.5 Lazy Loading Strategies
## 2. API Design and Routing (Go 1.22+ Features)
- **Lazy Loading Images:** Lazy load images that are not immediately visible.
- **Code Splitting:** Split the code into smaller chunks that can be loaded on demand.
- **Dynamic Imports:** Use dynamic imports to load modules only when they are needed.
Leverage Go 1.22's enhanced `http.ServeMux` for clean, expressive routing.
## 4. Security Best Practices
### ✅ GOOD: Method Matching, Path Values, and Exact Matches
### 4.1 Common Vulnerabilities and How to Prevent Them
Use HTTP method prefixes, `{name}` wildcards for path values, and `{$}` for strict path matching.
- **SQL Injection:** Prevent SQL injection by using parameterized queries or ORMs.
- **Cross-Site Scripting (XSS):** Prevent XSS by escaping user input before rendering it in HTML.
- **Cross-Site Request Forgery (CSRF):** Prevent CSRF by using CSRF tokens.
- **Authentication Bypass:** Implement robust authentication and authorization mechanisms to prevent authentication bypass.
- **Denial-of-Service (DoS):** Implement rate limiting and request validation to prevent DoS attacks.
```go
// In handlers.RegisterRoutes or similar setup
mux.HandleFunc("GET /users/{id}", uh.GetUser) // Matches GET /users/123, extracts "123" as "id"
mux.HandleFunc("POST /users", uh.CreateUser) // Matches POST /users
mux.HandleFunc("DELETE /users/{id}", uh.DeleteUser) // Matches DELETE /users/123
mux.HandleFunc("GET /healthz/{$}", uh.HealthCheck) // Matches ONLY GET /healthz, not /healthz/foo
mux.HandleFunc("/files/", uh.FileServer) // Matches /files/ and /files/foo/bar (subtree)
```
### 4.2 Input Validation
### ❌ BAD: Manual Method Checking, Suboptimal Path Matching
- **Validate All Inputs:** Validate all user inputs to ensure that they conform to the expected format and values. Use libraries like `ozzo-validation` for complex validation rules.
- **Sanitize Inputs:** Sanitize inputs to remove potentially malicious characters.
- **Whitelist Inputs:** Use a whitelist approach to only allow specific characters or patterns.
Avoid checking `r.Method` inside handlers or using generic path patterns when specific methods are required.
### 4.3 Authentication and Authorization Patterns
```go
// In handlers.RegisterRoutes or similar setup (BAD example)
mux.HandleFunc("/users/{id}", uh.UserHandlerGeneric) // Handles all methods for /users/{id}
- **Authentication Middleware:** Implement authentication middleware to verify user credentials.
- **Authorization Middleware:** Implement authorization middleware to check user permissions.
- **JWT (JSON Web Tokens):** Use JWT for stateless authentication.
- **OAuth 2.0:** Use OAuth 2.0 for delegated authorization.
- **Role-Based Access Control (RBAC):** Implement RBAC to manage user permissions.
// func (uh *UserHandlers) UserHandlerGeneric(w http.ResponseWriter, r *http.Request) {
// switch r.Method { // BAD: Manual method dispatch
// case http.MethodGet:
// uh.GetUser(w, r)
// case http.MethodDelete:
// uh.DeleteUser(w, r)
// default:
// http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
// }
// }
### 4.4 Data Protection Strategies
mux.HandleFunc("/healthz/", uh.HealthCheck) // BAD: Matches /healthz/foo, not just /healthz
```
- **Encryption:** Encrypt sensitive data at rest and in transit.
- **Hashing:** Hash passwords with a strong hashing algorithm like bcrypt.
- **Salting:** Use salts to prevent rainbow table attacks.
- **Data Masking:** Mask sensitive data in logs and error messages.
## 3. Error Handling and Response Encoding
### 4.5 Secure API Communication
Always return structured JSON error responses and use `json.NewEncoder` for output.
- **HTTPS:** Use HTTPS to encrypt communication between the client and the server.
- **TLS (Transport Layer Security):** Use TLS 1.3 or higher for secure communication.
- **Certificate Pinning:** Consider using certificate pinning to prevent man-in-the-middle attacks.
- **Rate Limiting:** Implement rate limiting to prevent abuse.
### ✅ GOOD: JSON Error Responses, `json.NewEncoder`
Define a consistent error response structure. Use `json.NewEncoder` for efficient and correct JSON output.
```go
// In handlers/user.go (example helper functions)
// respondWithError sends a JSON error response.
func (uh *UserHandlers) respondWithError(w http.ResponseWriter, code int, message string) {
uh.respondWithJSON(w, code, map[string]string{"error": message})
}
// respondWithJSON sends a JSON response.
func (uh *UserHandlers) respondWithJSON(w http.ResponseWriter, code int, payload interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(code)
if err := json.NewEncoder(w).Encode(payload); err != nil { // Use NewEncoder
uh.log.Printf("Error encoding JSON response: %v", err)
// Fallback to plain text error if JSON encoding fails
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}
```
### ❌ BAD: Plain Text Errors, Manual JSON Marshaling
Avoid `http.Error` for API responses and manual `json.Marshal` followed by `w.Write`.
```go
// func (uh *UserHandlers) GetUser(w http.ResponseWriter, r *http.Request) {
// // ...
// if err != nil {
// http.Error(w, "User not found", http.StatusNotFound) // BAD: Plain text error
// return
// }
//
// response, _ := json.Marshal(user) // BAD: Manual Marshal, then Write
// w.Header().Set("Content-Type", "application/json")
// w.WriteHeader(http.StatusOK)
// w.Write(response)
// }
```
## 4. Logging
Implement clear, request-level logging using the standard `log` package or a lightweight wrapper.
### ✅ GOOD: Request-Level Logging
Log incoming requests and critical events within handlers.
```go
// In handlers/user.go
func (uh *UserHandlers) GetUser(w http.ResponseWriter, r *http.Request) {
uh.log.Printf("INFO: Handling GET /users/%s from %s", r.PathValue("id"), r.RemoteAddr)
// ... handler logic
}
```
## 5. Testing Approaches
### 5.1 Unit Testing Strategies
Write comprehensive unit tests for each handler using `httptest.NewRecorder`.
- **Test Individual Units:** Unit test individual functions and methods in isolation.
- **Mock Dependencies:** Use mocks to isolate the unit under test from its dependencies. Use libraries like `gomock` or `testify/mock`.
- **Test Boundary Conditions:** Test boundary conditions and edge cases.
- **Table-Driven Tests:** Use table-driven tests to test multiple scenarios with different inputs and outputs.
### ✅ GOOD: `httptest.NewRecorder` for Handler Unit Tests
### 5.2 Integration Testing
Test handlers in isolation, validating status codes, headers, and response bodies.
- **Test Interactions Between Components:** Integration test the interactions between different components of the application.
- **Test Database Interactions:** Test the interactions with the database.
- **Test API Endpoints:** Test the API endpoints.
```go
// internal/handlers/user_test.go
package handlers_test
### 5.3 End-to-End Testing
import (
"bytes"
"encoding/json"
"log"
"net/http"
"net/http/httptest"
"testing"
- **Test the Entire Application:** End-to-end test the entire application flow.
- **Use Automated Testing Tools:** Use automated testing tools like Selenium or Cypress.
"yourproject/internal/handlers"
"yourproject/internal/service" // Business logic interface
)
### 5.4 Test Organization
// MockUserService implements handlers.UserService for testing purposes.
type MockUserService struct {
GetUserFn func(id int) (*service.User, error)
CreateUserFn func(user *service.User) error
}
- **Keep Tests Close to Code:** Keep test files in the same directory as the code they test. Use the `_test.go` suffix for test files.
- **Separate Test Packages:** Consider creating separate test packages for integration and end-to-end tests.
- **Descriptive Test Names:** Use descriptive test names that clearly indicate what is being tested.
func (m *MockUserService) GetUser(id int) (*service.User, error) {
return m.GetUserFn(id)
}
func (m *MockUserService) CreateUser(user *service.User) error {
return m.CreateUserFn(user)
}
### 5.5 Mocking and Stubbing
func TestGetUser(t *testing.T) {
tests := []struct {
name string
userID string
mockGetUser func(id int) (*service.User, error)
expectedStatus int
expectedBody string
}{
{
name: "Valid User ID",
userID: "1",
mockGetUser: func(id int) (*service.User, error) {
return &service.User{ID: 1, Name: "Test User"}, nil
},
expectedStatus: http.StatusOK,
expectedBody: `{"ID":1,"Name":"Test User"}`,
},
{
name: "User Not Found",
userID: "999",
mockGetUser: func(id int) (*service.User, error) {
return nil, service.ErrNotFound // Assume service.ErrNotFound
},
expectedStatus: http.StatusNotFound,
expectedBody: `{"error":"User not found"}`,
},
{
name: "Invalid User ID",
userID: "abc",
mockGetUser: nil, // Should not be called
expectedStatus: http.StatusBadRequest,
expectedBody: `{"error":"Invalid user ID"}`,
},
}
- **Use Interfaces:** Define interfaces for dependencies to facilitate mocking.
- **Use Mocking Libraries:** Use mocking libraries like `gomock` or `testify/mock` to generate mocks.
- **Create Stub Implementations:** Create stub implementations for dependencies that are difficult to mock.
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
mockSvc := &MockUserService{GetUserFn: tt.mockGetUser}
mux := http.NewServeMux()
handlers.RegisterRoutes(mux, log.Default(), mockSvc) // Use default logger for tests
## 6. Common Pitfalls and Gotchas
req := httptest.NewRequest(http.MethodGet, "/users/"+tt.userID, nil)
rr := httptest.NewRecorder()
### 6.1 Frequent Mistakes Developers Make
mux.ServeHTTP(rr, req) // Call the mux directly
- **Forgetting to Handle Errors:** Always check and handle errors returned by functions.
- **Ignoring Context Cancellation:** Respect context cancellation signals and terminate long-running operations.
- **Not Validating Inputs:** Always validate user inputs to prevent security vulnerabilities.
- **Using Global State:** Avoid using global variables for request handling, as it can lead to race conditions.
- **Overlapping Routes:** Failing to understand route precedence, especially in Go 1.22+ can lead to unexpected behavior or panics during server initialization. Thoroughly test route registrations.
if rr.Code != tt.expectedStatus {
t.Errorf("Expected status %d, got %d", tt.expectedStatus, rr.Code)
}
### 6.2 Edge Cases to Be Aware Of
// Compare JSON bodies
var actual map[string]interface{}
var expected map[string]interface{}
json.Unmarshal(rr.Body.Bytes(), &actual)
json.Unmarshal([]byte(tt.expectedBody), &expected)
- **Trailing Slashes:** Be aware of how trailing slashes affect route matching. In Go 1.22+, use `{$}` to match only the path with the trailing slash.
- **Wildcard Matching:** Understand how wildcards match different segments of the path. Use `{pathname...}` to match all remaining segments.
- **Method Matching:** Ensure that the correct HTTP method is being used for each route. With Go 1.22+, be aware that `GET` also matches `HEAD` requests.
if !bytes.Equal(rr.Body.Bytes(), []byte(tt.expectedBody)) && !jsonEqual(actual, expected) {
t.Errorf("Expected body %s, got %s", tt.expectedBody, rr.Body.String())
}
})
}
}
### 6.3 Version-Specific Issues
// jsonEqual compares two JSON objects for equality.
func jsonEqual(a, b interface{}) bool {
aj, _ := json.Marshal(a)
bj, _ := json.Marshal(b)
return bytes.Equal(aj, bj)
}
```
- **Go 1.22 Routing Enhancements:** Be aware of the new routing enhancements in Go 1.22, including method matching and wildcard support. Understand the new precedence rules.
- **Compatibility Issues:** Check for compatibility issues when upgrading to new versions of Go or third-party libraries.
## 6. Security Best Practices
### 6.4 Compatibility Concerns
Prioritize security by avoiding global state and validating all inputs.
- **Backwards Compatibility:** Ensure that changes do not break backwards compatibility. Use feature flags to gradually introduce new features.
- **API Versioning:** Use API versioning to manage changes to the API.
- **Client Compatibility:** Ensure that client applications are compatible with the API.
### ✅ GOOD: Use a Local `http.ServeMux`
### 6.5 Debugging Strategies
Always instantiate your own `http.ServeMux` instance. This prevents third-party packages from inadvertently or maliciously registering routes on your server.
- **Logging:** Use logging to track the execution flow and identify errors.
- **Debugging Tools:** Use debugging tools like `delve` to step through the code and inspect variables.
- **Profiling:** Use profiling tools to identify performance bottlenecks.
- **Tracing:** Use tracing tools to track requests across different services.
```go
// main.go
mux := http.NewServeMux() // ✅ GOOD: Local, controlled mux
// ... register handlers
http.ListenAndServe(":8080", mux)
```
## 7. Tooling and Environment
### ❌ BAD: Relying on `http.DefaultServeMux`
### 7.1 Recommended Development Tools
Never pass `nil` to `http.ListenAndServe()` or use `http.Handle`/`http.HandleFunc` directly, as this exposes the global `http.DefaultServeMux`.
- **GoLand:** A powerful IDE for Go development.
- **Visual Studio Code with Go Extension:** A lightweight and versatile code editor with excellent Go support.
- **Delve:** A Go debugger.
- **Profiling Tools:** `pprof` is the built-in Go profiler.
```go
// main.go (BAD example)
http.HandleFunc("/", homeHandler) // BAD: Registers on global mux
http.ListenAndServe(":8080", nil) // BAD: Uses global mux
```
### 7.2 Build Configuration
## 7. Common Pitfalls and Gotchas
- **Makefile:** Use a Makefile to automate common build tasks.
- **`go build`:** Use `go build` to compile the application.
- **`go test`:** Use `go test` to run tests.
Be aware of `servemux`'s specific behaviors to avoid unexpected issues.
### 7.3 Linting and Formatting
### ✅ GOOD: Understand Pattern Precedence and Conflicts
- **`go fmt`:** Use `go fmt` to format the code according to the Go style guidelines.
- **`go vet`:** Use `go vet` to identify potential errors in the code.
- **`golangci-lint`:** Use `golangci-lint` for more advanced linting.
Go 1.22+ `ServeMux` panics on registration if patterns conflict. Design your routes to be unambiguous. Use `{$}` for exact matches to prevent subtree matching.
### 7.4 Deployment Best Practices
```go
// Correctly defined patterns
mux.HandleFunc("GET /tasks/{id}/status", handlerTaskStatus) // Specific
mux.HandleFunc("GET /tasks/{id}", handlerTask) // More general, but no conflict
mux.HandleFunc("GET /admin/{$}", handlerAdminRoot) // Exact match for /admin
```
- **Containerization:** Use containers (e.g., Docker) to package the application and its dependencies.
- **Orchestration:** Use orchestration tools (e.g., Kubernetes) to manage and scale the application.
- **Immutable Infrastructure:** Deploy immutable infrastructure to ensure consistency and reproducibility.
### ❌ BAD: Ambiguous Patterns, Forgetting `{$}`
### 7.5 CI/CD Integration
- **Continuous Integration:** Integrate with a CI/CD pipeline to automate the build, test, and deployment process.
- **Automated Testing:** Run automated tests as part of the CI/CD pipeline.
- **Automated Deployment:** Automate the deployment process using tools like Jenkins, CircleCI, or GitHub Actions.
## Additional Best Practices
- **Meaningful Handler Names:** Use meaningful, concise names for handlers, avoiding repetition of context in function names (as per the Google Style Guide).
- **Document Code:** Write clear and concise documentation for all functions, methods, and types.
- **Code Reviews:** Conduct regular code reviews to ensure code quality and identify potential issues.
- **Stay Updated:** Stay up-to-date with the latest Go best practices and security vulnerabilities.
By following these best practices and coding standards, you can develop robust, maintainable, and efficient applications using the `net/http` ServeMux in Go.
```go
// mux.HandleFunc("/tasks/{id}/status/", handlerTaskStatus) // BAD: Trailing slash makes it a subtree
// mux.HandleFunc("/tasks/0/{action}/", handlerTaskAction) // BAD: Conflicts with above for /tasks/0/status/
//
// mux.HandleFunc("/admin/", handlerAdminRoot) // BAD: Matches /admin/foo, not just /admin
```