Skip to content

Latest commit

 

History

History
462 lines (331 loc) · 11.7 KB

CONTRIBUTING.md

File metadata and controls

462 lines (331 loc) · 11.7 KB

Contributing to host-http

Thank you for your interest in contributing to host-http! We welcome all forms of contribution, from bug reports to feature implementations. This guide will help you get started and make your contribution process smooth.

Quick Start

Getting Help & Support

Before contributing, here are the best places to get help:

Prerequisites

  • Go 1.24 or later
  • Git for version control
  • golangci-lint for code quality checks
  • Basic understanding of HTTP servers and Go web frameworks

Development Setup

1. Fork & Clone

# Fork the repository on GitHub, then clone your fork
git clone https://github.com/YOUR_USERNAME/host-http.git
cd host-http

2. Install Dependencies

# Download Go modules
go mod download

# Install development tools
go install golang.org/x/tools/cmd/goimports@latest
go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest

3. Create Feature Branch

git checkout -b feature/your-feature-name

4. Development Workflow

# Run tests frequently during development
go test ./...

# Check code quality before committing
make lint  # or: golangci-lint run

# Format code
go fmt ./...
goimports -w .

Types of Contributions

Bug Reports

Use: GitHub Issues

Please include:

  • Go version (go version)
  • Operating system and version
  • host-http version or commit hash
  • Clear reproduction steps
  • Expected vs actual behavior
  • Minimal code sample

Bug Report Template

**Environment**:
- Go Version: go1.24.0
- OS: Ubuntu 22.04
- host-http Version: v1.0.0

**Description**:
Brief description of the bug.

**Reproduction Steps**:
1. Create a server with...
2. Send request to...
3. Observe error...

**Expected**: Should return status 200
**Actual**: Returns status 500

**Code Sample**:
```go
// Minimal reproducible example

###  Feature Requests & Ideas

**Use**: [GitHub Discussions](https://github.com/orgs/Bofry/discussions/new/choose) (preferred) or [GitHub Issues](https://github.com/Bofry/host-http/issues/new)

For feature requests, include:

- **Problem**: What problem does this solve?
- **Solution**: Proposed approach or API design
- **Use Cases**: Real-world scenarios where this would help
- **Breaking Changes**: Impact on existing code

###  Code Contributions

1. **Create an issue first** for non-trivial changes
2. **Discuss the design** in GitHub Discussions or the issue
3. **Follow code standards** (see Quality Standards below)
4. **Write comprehensive tests**
5. **Update documentation** as needed

##  Quality Standards

### Code Quality Checklist

Before submitting a pull request, ensure your code passes:

```bash
# 1. Module cleanup
go mod tidy
go mod vendor

# 2. Code formatting  
goimports -w .
go fmt ./...

# 3. Linting (must pass without errors)
golangci-lint run

# 4. Static analysis
go vet ./...

# 5. All tests pass
go test ./... -race -cover

# 6. Examples still work (if modified)
cd _examples/basic
go run hello-world

Naming Conventions

  • Types & Functions: CamelCase (e.g., NetHTTPHost, AsNetHTTPHost)
  • Constants: CamelCase for public, ALL_CAPS allowed for internal tags
  • Variables: camelCase
  • Packages: lowercase, single word preferred

Error Handling

  • Always check errors: No ignored error returns
  • Wrap context: Use fmt.Errorf("operation failed: %w", err)
  • Meaningful messages: Provide clear error descriptions

Testing Requirements

  • Coverage: Aim for >80% test coverage
  • Table-driven tests: Use for multiple scenarios
  • Test naming: TestFunction_Scenario format
  • Benchmarks: Include for performance-critical code

Example test structure:

func TestUserHandler_Get(t *testing.T) {
    tests := []struct {
        name           string
        userID         string
        expectedStatus int
        expectedBody   string
    }{
        {
            name:           "valid user ID",
            userID:         "123", 
            expectedStatus: http.StatusOK,
            expectedBody:   `{"id":"123","name":"John"}`,
        },
        {
            name:           "missing user ID",
            userID:         "",
            expectedStatus: http.StatusBadRequest,
            expectedBody:   `{"error":"User ID required"}`,
        },
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            // Test implementation
        })
    }
}

Pull Request Process

Before Submitting

  1. Rebase on latest main:

    git fetch upstream
    git rebase upstream/main
  2. Run full quality check:

    golangci-lint run && go vet ./... && go test ./...
  3. Update documentation if needed

  4. Squash commits if you have multiple small commits

Pull Request Requirements

  • Clear title: Descriptive summary of changes
  • Detailed description: What changes and why
  • Issue reference: Link related issues with Closes #123
  • Breaking changes: Clearly marked if any
  • Tests included: New functionality must have tests

Review Process

All pull requests require review. Reviewers check:

    • Functionality: Code works as intended
    • Quality: Follows project standards
    • Tests: Adequate test coverage
    • Docs: Public APIs are documented
    • Compatibility: No unintended breaking changes

Review Standards

Immediate Rejection:

  • Security vulnerabilities
  • Hardcoded secrets/credentials
  • Missing tests for new features
  • Undiscussed breaking changes

Request Changes:

  • Code style violations
  • Missing error handling
  • Insufficient test coverage
  • Poor performance

Approval with Comments:

  • Minor style suggestions
  • Optional optimizations
  • Enhancement ideas for future

Commit Standards

We use Conventional Commits format:

<type>[optional scope]: <description>

[optional body]

[optional footer]

Types

  • feat: New feature
  • fix: Bug fix
  • docs: Documentation changes
  • style: Code formatting (no logic changes)
  • refactor: Code restructuring (no behavior change)
  • test: Adding or updating tests
  • perf: Performance improvements
  • chore: Maintenance tasks

Examples

feat(middleware): add rate limiting middleware

Add configurable rate limiting with:
- Per-IP rate limiting  
- Configurable time windows
- Custom limit exceeded handlers

Closes #123
fix(response): handle nil pointers in JSON encoding

Previously would panic on nil pointer fields.
Now gracefully encodes as null values.

Fixes #456

Architecture Guidelines

Design Principles

  1. Compatibility: Maintain API compatibility with host-fasthttp where possible
  2. Standard Library First: Prefer stdlib over third-party dependencies
  3. Simplicity: Keep APIs intuitive and easy to use
  4. Performance: Balance speed with maintainability
  5. Testability: Design for easy unit testing

Adding New Features

Before implementing:

  1. Create GitHub Discussion to propose the feature
  2. Review existing patterns in the codebase
  3. Consider compatibility with host-fasthttp
  4. Plan testing strategy
  5. Document breaking changes clearly

Breaking Changes

Breaking changes require special care:

  • Deprecation period: Provide migration path when possible
  • Major version bump: Follow semantic versioning
  • Migration guide: Update documentation
  • Community notice: Announce in GitHub Discussions

Documentation Standards

Code Documentation

  • Public APIs: All exported functions, types, constants must have doc comments
  • Package docs: Each package needs a package comment explaining its purpose
  • Examples: Include examples for complex APIs using Example_ tests
  • Internal docs: Document complex internal logic

Example documentation:

// UserHandler handles HTTP requests for user resources.
// It provides standard CRUD operations and supports both JSON and form data.
type UserHandler struct {
    UserService *UserService
    Logger      *log.Logger
}

// Get retrieves a user by ID from query parameters.
// 
// Query Parameters:
//   - id: User ID (required)
//
// Returns:
//   - 200: User data as JSON
//   - 400: Missing or invalid user ID  
//   - 404: User not found
//   - 500: Internal server error
func (h *UserHandler) Get(ctx *RequestContext) {
    // Implementation
}

Documentation Updates

When making changes:

  • Update relevant files in docs/
  • Update code examples if APIs change
  • Update README.md for significant features
  • Consider adding entries to CHANGELOG.md

Performance Guidelines

Development Practices

  • Profile before optimizing: Use go test -bench and go tool pprof
  • Avoid premature optimization: Focus on correctness first
  • Memory efficiency: Be mindful of allocations in hot paths
  • Concurrency safety: Use proper synchronization where needed

Benchmark Tests

Include benchmarks for performance-critical code:

func BenchmarkUserHandler_Get(b *testing.B) {
    req := httptest.NewRequest("GET", "/users?id=123", nil)
    w := httptest.NewRecorder()
    handler := &UserHandler{UserService: mockUserService}
    
    b.ResetTimer()
    for i := 0; i < b.N; i++ {
        handler.Get(internal.NewRequestContext(w, req))
    }
}

Community Guidelines

Code of Conduct

We're committed to providing a welcoming environment:

  • Be respectful and considerate
  • Be collaborative and constructive
  • Be patient with newcomers
  • Focus on technical merits over personal preferences
  • Help others learn and grow

Communication Channels

Asking Good Questions

When seeking help:

  1. Search existing resources (docs, issues, discussions)
  2. Provide context about your goal
  3. Include relevant code samples and error messages
  4. Be specific about the problem
  5. Format code properly using markdown code blocks

Recognition

Contributors are recognized through:

  • Contributors section in README.md
  • Release notes crediting significant contributions
  • GitHub contributor graphs and statistics
  • Special mentions for major contributions
  • Maintainer invitations for consistent contributors

License

By contributing to host-http, you agree that your contributions will be licensed under the same MIT License that covers the project.


Quick Links

Thank you for contributing to host-http! Your contributions help make this project better for everyone.