This document provides AI agents with collaboration guidelines for working in this repository, covering code structure, development standards, and best practices.
This project is a Go Web framework based on net/http, providing API compatibility with host-fasthttp while embracing microservice-first design principles. It adopts the RMR (Resource-Method-Representation) pattern:
- Resource: URL paths define business entities (
/users,/health) - Method: HTTP methods map to Go methods (
Get()→ GET,Post()→ POST) - Representation: Structured response formatting (JSON/Text)
The framework embodies Go's core principles:
- Standard Library First: Built on
net/httpfor maximum ecosystem compatibility - Convention over Configuration: Sensible defaults with minimal setup required
- Explicit over Implicit: Clear, readable patterns with minimal magic
- Composition over Inheritance: Middleware chains and dependency injection
- Zero-Config Startup: Works out of the box with environment overrides
- RequestHandler Signature: Standard
func(http.ResponseWriter, *http.Request)- Full Go ecosystem compatibility - Middleware Chain: Chain-of-responsibility pattern with dependency injection support
- Automatic Routing: Route registration via struct tags and reflection
- Microservice-Optimized: Stateless design with built-in health checks and tracing
- Testing-Driven: 40%+ coverage target with example-driven development
internal/ # Framework core implementation
├── middleware/ # Middleware implementations
├── responseutil/ # Response utilities
└── tracingutil/ # Tracing utilities
response/ # Response formatting system
├── failure/ # Structured error handling
handlers/ # Built-in handlers
tracing/ # Tracing integration
_examples/basic/ # Complete usage examples
docs/ # Comprehensive documentation
```textplain
### Type System Design
- `RequestCtx`: Type alias for `*http.Request` - standard Go request handling
- `RequestHandler`: Standard `func(http.ResponseWriter, *http.Request)` signature
- `RequestHandleModule`: Middleware interface for chain-of-responsibility pattern
- `ResponseState`: Request processing state tracking (Begin/End)
- `Router`: Route registration and lookup interface
### Core Framework Patterns
#### RMR Implementation Pattern
```go
// Resource definition through URL tags
type RequestManager struct {
*UserRequest `url:"/users"` // Resource: /users
*ProductRequest `url:"/products"` // Resource: /products
*HealthRequest `url:"/health"` // Resource: /health
}
// Method mapping: Go method names → HTTP verbs
type UserRequest struct{}
func (r *UserRequest) Get(w http.ResponseWriter, req *http.Request) { // GET /users
response.JSON.Success(w, users)
}
func (r *UserRequest) Post(w http.ResponseWriter, req *http.Request) { // POST /users
response.JSON.Success(w, newUser)
}
// Middleware implements RequestHandleModule
type LoggingMiddleware struct {
successor RequestHandleModule
logger *log.Logger
}
func (m *LoggingMiddleware) ProcessRequest(w http.ResponseWriter, r *http.Request, state RequestState, recover *Recover) {
// Pre-processing logic
defer func() {
// Post-processing cleanup
}()
// Continue middleware chain
if m.successor != nil {
m.successor.ProcessRequest(w, r, state, recover)
}
}-
Import Patterns:
- Framework import:
hosthttp "github.com/Bofry/host-http" - Standard library:
"net/http" - Response utilities:
"github.com/Bofry/host-http/response"
- Framework import:
-
Error Handling: Use
response/failurepackage for structured errors -
Test Coverage: All public functionality must have unit tests (40%+ target)
-
Documentation Updates: Synchronize API changes with documentation
-
Go 1.24 Compliance: Use
anyinstead ofinterface{}
// Production application structure
type App struct {
Host *hosthttp.Host `host:""`
Config *Config `config:""`
ServiceProvider *ServiceProvider `serviceProvider:""`
}
// Configuration with environment variable support
type Config struct {
ListenAddress string `env:"HTTP_LISTEN_ADDRESS" default:":8080"`
DatabaseURL string `env:"DATABASE_URL" required:"true"`
JaegerEndpoint string `env:"JAEGER_ENDPOINT"`
TracingEnabled bool `env:"TRACING_ENABLED" default:"false"`
}
// Service-oriented startup
func main() {
app := &App{
Config: loadConfig(),
ServiceProvider: initServices(),
}
hosthttp.Startup(app).
Middlewares(
hosthttp.UseLogging(&LoggingService{}),
hosthttp.UseTracing(true), // OpenTelemetry/Jaeger integration
hosthttp.UseCorsHeader("Authorization"), // CORS with custom headers
hosthttp.UseRequestManager(&RequestManager{}),
hosthttp.UseErrorHandler(handleError),
).
Run()
}type HealthRequest struct {
DatabaseService *service.DatabaseService `service:"DatabaseService"`
RedisService *service.RedisService `service:"RedisService"`
}
func (r *HealthRequest) Get(w http.ResponseWriter, req *http.Request) {
health := map[string]string{
"status": "healthy",
"version": "1.0.0",
}
// Optional: Add dependency health checks
if !r.DatabaseService.IsHealthy() {
response.JSON.Failure(w, "Database unhealthy", http.StatusServiceUnavailable)
return
}
response.JSON.Success(w, health)
}type CustomMiddleware struct {
// Dependency fields
}
func (m *CustomMiddleware) ProcessRequest(ctx *RequestCtx, state RequestState, recover *Recover) {
// Pre-processing logic
defer func() {
// Post-processing cleanup
}()
// Call next middleware
m.successor.ProcessRequest(ctx, state, recover)
}
```textplain
### Request Handler Pattern
```go
type ResourceRequest struct {
// Dependency injection fields (automatically populated by framework)
ServiceProvider *ServiceProvider
Config *Config
}
func (r *ResourceRequest) Get(ctx *http.RequestCtx) {
// 1. Validate input
// 2. Execute business logic
// 3. Format response
// 4. Handle errors consistently
}
```textplain
## Testing Strategy and Patterns
### Test Hierarchy
1. **Unit Tests**: Individual function and method testing
2. **Integration Tests**: Middleware chain and routing testing
3. **Example Tests**: Complete application flow testing (`test_examples.sh`)
### Mock Design Patterns
- Use `httptest` for HTTP testing
- Create mock implementations for main interfaces (`RequestHandleModule`, `WellKnownError`)
- Test isolation: Each test creates independent RequestContext
### Test Command Reference
```bash
go test ./... # All tests
go test -v ./internal # Specific package with verbose output
go test -run TestSpecific # Run specific test
./test_examples.sh # Example integration tests
```textplain
## Documentation Cross-References
### Essential Documentation
Before making changes, review these documents:
- **[docs/architecture.md](docs/architecture.md)**: Core design principles and patterns
- **[docs/getting-started.md](docs/getting-started.md)**: Setup and first application guide
- **[docs/api-reference.md](docs/api-reference.md)**: Complete API documentation
- **[docs/migration.md](docs/migration.md)**: Migration from host-fasthttp
- **[docs/best-practices.md](docs/best-practices.md)**: Production deployment practices
- **[docs/middleware.md](docs/middleware.md)**: Custom middleware development
- **[docs/development.md](docs/development.md)**: Development workflow standards
### Example Applications
The `_examples/basic/` directory provides complete implementation examples:
- **[_examples/basic/hello-world/](_examples/basic/hello-world/)**: Basic API structure
- **[_examples/basic/health-check/](_examples/basic/health-check/)**: Health monitoring patterns
- **[_examples/basic/json-api/](_examples/basic/json-api/)**: RESTful API implementation
- **[_examples/basic/error-handling/](_examples/basic/error-handling/)**: Error handling strategies
- **[_examples/basic/middleware-chain/](_examples/basic/middleware-chain/)**: Middleware composition
Refer to **[_examples/basic/README.md](_examples/basic/README.md)** for running instructions and API testing.
## AI Collaboration Best Practices
### Codebase Understanding Sequence
1. **Core Definitions**: First read `internal/def.go` to understand base types
2. **Example Learning**: Examine `_examples/basic/` to understand usage patterns
3. **Architecture Files**: Reference `docs/architecture.md` for design principles
4. **API Reference**: Check `docs/api-reference.md` to verify interfaces
5. **Testing Patterns**: Study existing test structures before adding new tests
### Modification Workflow
1. **Analyze Existing**: Understand current implementation and design decisions
2. **Compatibility Check**: Ensure changes don't break API compatibility
3. **Test Verification**: Add/modify corresponding test cases
4. **Documentation Sync**: Update relevant documentation
5. **Example Updates**: Update corresponding examples if needed
### Error Handling Collaboration
- Use `failure.ThrowFailure()` and `failure.ThrowFailureMessage()` for structured errors
- Follow `UPPER_CASE_WITH_UNDERSCORES` format for error codes
- Define standard error codes in `response/failure/def.go`
### Performance Considerations
- RequestContext lifecycle management
- Middleware chain execution efficiency
- Route resolution and matching performance
- JSON serialization/deserialization optimization
## Common Collaboration Scenarios
### Adding New Middleware
1. Implement `RequestHandleModule` interface
2. Add implementation in `middleware/` directory
3. Update export functions (e.g., `UseCustomMiddleware`)
4. Add corresponding tests and examples
### Adding Request Handlers
1. Define request struct
2. Implement corresponding HTTP methods (`Get`, `Post`, etc.)
3. Register routes in RequestManager
4. Add unit test verification
### Modifying Response Format
1. Check existing formatters in `response/` package
2. Consider backward compatibility
3. Update related error handling logic
4. Synchronize examples and tests
### Framework Upgrade Migration
1. Check existing guidance in `docs/migration.md`
2. Mark breaking changes
3. Provide automated migration tools or scripts
4. Update versions and changelog
## Quality Assurance Workflow
### Pre-Commit Sequence
Always execute these commands in order before committing changes:
```bash
# 1. Clean up module dependencies
go mod tidy
# 2. Format imports
goimports -w .
# 3. Run linter and fix Go 1.24 warnings
golangci-lint run
# 4. Static analysis check
go vet ./...
# 5. Ensure all tests pass
go test ./...
```textplain
This sequence ensures code quality, Go 1.24 compliance, and framework stability.
### Task Execution Guidelines
When working on tasks:
1. **Understanding Phase**: Review relevant documentation and examples
2. **Implementation Phase**: Follow established patterns and conventions
3. **Testing Phase**: Add comprehensive tests for new functionality
4. **Quality Phase**: Run the complete quality assurance workflow
5. **Documentation Phase**: Update relevant documentation and examples
## Framework-Specific Considerations
### RequestContext Usage
- Always use `*RequestContext` parameter in handlers
- Avoid creating new RequestContext instances
- Utilize context for request-scoped data storage
### Middleware Chain Behavior
- Middleware executes in registration order
- Each middleware must call successor or terminate chain
- Use defer for cleanup operations
### Route Resolution
- Routes defined via struct tags and reflection
- Method names map to HTTP verbs
- Custom method binding supported via `@BindMethod` tags
By following these guidelines, AI agents can effectively understand, modify, and extend the host-http framework while maintaining code quality and project consistency.