http

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 15, 2025 License: MIT Imports: 5 Imported by: 0

README

host-http

Go HTTP framework built on net/http with RMR pattern support.

Go Reference Go Report Card

Quick Start

package main

import hosthttp "github.com/Bofry/host-http"

type HelloRequest struct{}

func (r *HelloRequest) Get(w http.ResponseWriter, req *http.Request) {
    response.Text.Success(w, "Hello, World!")
}

type RequestManager struct {
    *HelloRequest `url:"/hello"`
}

type App struct{}

func main() {
    app := &App{}
    hosthttp.Startup(app).
        Middlewares(hosthttp.UseRequestManager(&RequestManager{})).
        Run()
}
Installation
go get github.com/Bofry/host-http

Documentation

Examples

Complete working examples in _examples/basic/:

Run examples:

# Health check with lifecycle methods
cd _examples/basic/health-check && go run .

# Test endpoints
curl http://localhost:8080/health        # JSON status with uptime
curl http://localhost:8080/health/ping   # Basic connectivity test

Key Features

  • Standard Library: Built on net/http for ecosystem compatibility
  • RMR Pattern: Resource-Method-Representation architecture
  • App Lifecycle: Complete application lifecycle management
  • Zero Configuration: Works with sensible defaults
  • Middleware Chain: Composable request processing
  • Performance Optimized: Zero-allocation operations and object pooling

Core Concepts

RMR Architecture
  • Resource: URL paths (/users, /products)
  • Method: HTTP verbs map to Go methods (Get() → GET, Post() → POST)
  • Representation: Structured response formatting (JSON/Text)
App Lifecycle Methods
type App struct {
    Host            *hosthttp.Host   `host:""`
    Config          *Config          `config:""`
    ServiceProvider *ServiceProvider `serviceProvider:""`
}

func (app *App) Init() { /* Basic initialization */ }
func (app *App) OnInit() { /* Service setup */ }
func (app *App) OnInitComplete() { /* Finalization */ }
func (app *App) OnStart(ctx context.Context) { /* Server ready */ }
func (app *App) OnStop(ctx context.Context) { /* Graceful shutdown */ }
Request Handling
type UserRequest struct {
    UserService *service.UserService `service:"UserService"`
}

func (r *UserRequest) Get(w http.ResponseWriter, req *http.Request) {
    userID := req.URL.Query().Get("id")
    user, err := r.UserService.GetUser(userID)
    if err != nil {
        response.JSON.Failure(w, err, http.StatusNotFound)
        return
    }
    response.JSON.Success(w, user)
}

Performance Analysis & Stress Testing

This project includes comprehensive performance analysis tools combining stress testing with profiling capabilities.

Integrated Performance Analysis
# Comprehensive stress test with pprof profiling (Recommended)
./stress_test.pl --pprof --hours 1 --verbose --stats-interval 5

# Extended analysis with detailed profiling
./stress_test.pl --pprof --hours 6 --pprof-interval 300

# CPU and memory focused profiling
./stress_test.pl --pprof --profile-cpu --profile-memory --hours 2
Traditional Stress Testing
# Default 3-hour stress test
./stress_test.pl

# Custom duration and concurrency
./stress_test.pl --hours 1 --concurrency 50 --verbose

# Test specific example
./stress_test.pl --server-dir _examples/basic/json-api --verbose

Recommended Test Server: The script automatically uses _examples/basic/tracing-example as the test target, which includes comprehensive endpoints for both functional and performance testing:

  • /hello - Basic greeting endpoint
  • /api/users - User management API (supports ?stress=memory|cpu)
  • /api/orders - Order processing API
  • /error?type=400|404|500|timeout - HTTP error scenario testing
  • /health - Health check endpoint
  • /profile/stats - Runtime statistics and pprof endpoints
  • /memory?size=1024 - Memory allocation testing
Key Features
  • Automatic Server Management: Auto-start and stop test targets
  • Multi-threaded Concurrency: Configurable concurrent thread count
  • Performance Profiling: Automated pprof data collection (heap, CPU, goroutine, block)
  • Jaeger Integration: Automatic distributed tracing analysis
  • Multi-format Reports: Generate Markdown, JSON, CSV detailed reports with pprof analysis
  • Real-time Monitoring: Performance metrics output every 5-10 seconds
  • Stress Test Endpoints: Memory and CPU stress testing capabilities
System Requirements
# Install Perl dependencies
cpan HTTP::Tiny JSON::PP Time::HiRes List::Util threads threads::shared
Test Reports

All reports are saved in stress_reports/ directory, including:

  • stress_report_TIMESTAMP.md - Comprehensive stress test report
  • stress_report_TIMESTAMP.json - Detailed JSON data
  • stress_timeline_TIMESTAMP.csv - CSV timeline data
  • stress_errors_TIMESTAMP.log - Error logs
  • pprof_analysis_TIMESTAMP.md - Performance profiling analysis (when --pprof enabled)
  • pprof_TIMESTAMP/ - Directory containing profile data files
  • jaeger_analysis.json - Jaeger trace analysis (if available)
Performance Analysis Commands

When pprof is enabled, the reports include ready-to-use analysis commands:

# Memory analysis
go tool pprof -http=:8081 pprof_*/heap_001.pprof

# CPU profiling
go tool pprof -top pprof_*/cpu_001.pprof

# Goroutine analysis
go tool pprof -http=:8083 pprof_*/goroutine_001.pprof

# Blocking operations
go tool pprof -top pprof_*/block_001.pprof
Command Line Arguments
Parameter Default Description
--hours 3 Test execution time (hours)
--concurrency 25 Number of concurrent threads
--url http://localhost:8080 Target server URL
--server-dir Auto-detect Server program directory
--stats-interval 10 Statistics output interval (seconds)
--output-dir ./stress_reports Report output directory
--no-auto-server - Disable automatic server management
--no-jaeger - Disable Jaeger integration
--jaeger-url http://127.0.0.1:16686 Jaeger service URL
--verbose - Enable verbose output
--pprof - Enable pprof profiling integration
--no-pprof - Disable pprof profiling
--pprof-port 6060 pprof server port
--pprof-interval 300 Profile capture interval (seconds)
--profile-cpu - Enable CPU profiling
--profile-memory - Enable memory profiling
--profile-goroutine - Enable goroutine profiling
Troubleshooting
Server startup failure
# Check Go environment
go version

# Manual test example
cd _examples/basic/hello-world && go run .
Missing Perl modules
# Check module installation
perl -MHTTP::Tiny -e "print 'OK'"
perl -MJSON::PP -e "print 'OK'"

Environment Variables

Variable Description Default
HTTP_LISTEN_ADDRESS Server listen address :8080
ENABLE_COMPRESS Enable HTTP compression false
SERVER_NAME Server identification host-http-app

Contributing

  1. Fork the repository
  2. Create feature branch
  3. Add tests for new functionality
  4. Run go test ./... and golangci-lint run
  5. Submit pull request

License

MIT License - see LICENSE file for details.

Documentation

Index

Constants

View Source
const (
	StatusContinue           = 100 // RFC 7231, 6.2.1
	StatusSwitchingProtocols = 101 // RFC 7231, 6.2.2
	StatusProcessing         = 102 // RFC 2518, 10.1
	StatusEarlyHints         = 103 // RFC 8297

	StatusOK                   = 200 // RFC 7231, 6.3.1
	StatusCreated              = 201 // RFC 7231, 6.3.2
	StatusAccepted             = 202 // RFC 7231, 6.3.3
	StatusNonAuthoritativeInfo = 203 // RFC 7231, 6.3.4
	StatusNoContent            = 204 // RFC 7231, 6.3.5
	StatusResetContent         = 205 // RFC 7231, 6.3.6
	StatusPartialContent       = 206 // RFC 7233, 4.1
	StatusMultiStatus          = 207 // RFC 4918, 11.1
	StatusAlreadyReported      = 208 // RFC 5842, 7.1
	StatusIMUsed               = 226 // RFC 3229, 10.4.1

	StatusMultipleChoices  = 300 // RFC 7231, 6.4.1
	StatusMovedPermanently = 301 // RFC 7231, 6.4.2
	StatusFound            = 302 // RFC 7231, 6.4.3
	StatusSeeOther         = 303 // RFC 7231, 6.4.4
	StatusNotModified      = 304 // RFC 7232, 4.1
	StatusUseProxy         = 305 // RFC 7231, 6.4.5

	StatusTemporaryRedirect = 307 // RFC 7231, 6.4.7
	StatusPermanentRedirect = 308 // RFC 7538, 3

	StatusBadRequest                   = 400 // RFC 7231, 6.5.1
	StatusUnauthorized                 = 401 // RFC 7235, 3.1
	StatusPaymentRequired              = 402 // RFC 7231, 6.5.2
	StatusForbidden                    = 403 // RFC 7231, 6.5.3
	StatusNotFound                     = 404 // RFC 7231, 6.5.4
	StatusMethodNotAllowed             = 405 // RFC 7231, 6.5.5
	StatusNotAcceptable                = 406 // RFC 7231, 6.5.6
	StatusProxyAuthRequired            = 407 // RFC 7235, 3.2
	StatusRequestTimeout               = 408 // RFC 7231, 6.5.7
	StatusConflict                     = 409 // RFC 7231, 6.5.8
	StatusGone                         = 410 // RFC 7231, 6.5.9
	StatusLengthRequired               = 411 // RFC 7231, 6.5.10
	StatusPreconditionFailed           = 412 // RFC 7232, 4.2
	StatusRequestEntityTooLarge        = 413 // RFC 7231, 6.5.11
	StatusRequestURITooLong            = 414 // RFC 7231, 6.5.12
	StatusUnsupportedMediaType         = 415 // RFC 7231, 6.5.13
	StatusRequestedRangeNotSatisfiable = 416 // RFC 7233, 4.4
	StatusExpectationFailed            = 417 // RFC 7231, 6.5.14
	StatusTeapot                       = 418 // RFC 7168, 2.3.3
	StatusMisdirectedRequest           = 421 // RFC 7540, 9.1.2
	StatusUnprocessableEntity          = 422 // RFC 4918, 11.2
	StatusLocked                       = 423 // RFC 4918, 11.3
	StatusFailedDependency             = 424 // RFC 4918, 11.4
	StatusUpgradeRequired              = 426 // RFC 7231, 6.5.15
	StatusPreconditionRequired         = 428 // RFC 6585, 3
	StatusTooManyRequests              = 429 // RFC 6585, 4
	StatusRequestHeaderFieldsTooLarge  = 431 // RFC 6585, 5
	StatusUnavailableForLegalReasons   = 451 // RFC 7725, 3

	StatusInternalServerError           = 500 // RFC 7231, 6.6.1
	StatusNotImplemented                = 501 // RFC 7231, 6.6.2
	StatusBadGateway                    = 502 // RFC 7231, 6.6.3
	StatusServiceUnavailable            = 503 // RFC 7231, 6.6.4
	StatusGatewayTimeout                = 504 // RFC 7231, 6.6.5
	StatusHTTPVersionNotSupported       = 505 // RFC 7231, 6.6.6
	StatusVariantAlsoNegotiates         = 506 // RFC 2295, 8.1
	StatusInsufficientStorage           = 507 // RFC 4918, 11.5
	StatusLoopDetected                  = 508 // RFC 5842, 7.2
	StatusNotExtended                   = 510 // RFC 2774, 7
	StatusNetworkAuthenticationRequired = 511 // RFC 6585, 6
)

HTTP status codes from net/http standard library.

Variables

This section is empty.

Functions

func AsNetHTTPHost

func AsNetHTTPHost(h *Host) *internal.NetHTTPHost

AsNetHTTPHost converts host.Host to NetHTTPHost for configuration.

func ConfigureConfiguration

func ConfigureConfiguration(configurator ConfigurationServiceConfigurator)

ConfigureConfiguration configures the configuration management service. Called by host.Starter to set up configuration loading.

func CreateHost

func CreateHost() *internal.NetHTTPHost

CreateHost creates a NetHTTPHost instance.

func UseCorsHeader

func UseCorsHeader(headers ...string) host.Middleware

UseCorsHeader creates CORS handling middleware with optional custom headers. Enables cross-origin requests and adds specified headers to allowed list.

func UseErrorHandler

func UseErrorHandler(handler ErrorHandler) host.Middleware

UseErrorHandler creates error handling middleware with custom handler. The handler processes panics and errors during request processing.

func UseLogging

func UseLogging(services ...LoggingService) host.Middleware

UseLogging creates logging middleware with optional services. If no services provided, uses no-op logging. Multiple services are composed together.

func UseRequestManager

func UseRequestManager(requestManager any) host.Middleware

UseRequestManager creates request routing middleware with request manager. The manager handles automatic routing based on struct methods and tags.

func UseTracing

func UseTracing(options ...TracingOption) host.Middleware

UseTracing creates comprehensive tracing middleware with OpenTelemetry and slog fallback. Automatically traces HTTP requests with configurable options for skipping certain paths/methods.

Types

type ConfigurationServiceConfigurator

type ConfigurationServiceConfigurator func(service *config.ConfigurationService)

ConfigurationServiceConfigurator is the configuration service configurator function type.

type ErrorHandler

type ErrorHandler = internal.ErrorHandler

Handler function types.

type EventEvidence

type EventEvidence = middleware.EventEvidence

Middleware interfaces.

type EventLog

type EventLog = middleware.EventLog

Middleware interfaces.

type HTTPStarter

type HTTPStarter struct {
	*host.Starter
}

HTTPStarter wraps host.Starter to provide access to NetHTTPHost

func Startup

func Startup(app any) *HTTPStarter

Startup creates a host.Starter with NetHttpHost module configured. This is the main entry point for starting HTTP applications.

func (*HTTPStarter) GetRequestWorker

func (s *HTTPStarter) GetRequestWorker() *internal.RequestWorker

GetRequestWorker returns the RequestWorker for advanced middleware configuration

type Host

type Host = internal.NetHTTPHost

Core structs.

type LoggingService

type LoggingService = middleware.LoggingService

Middleware interfaces.

type Middleware

type Middleware interface {
	Invoke(w http.ResponseWriter, r *http.Request, next func(http.ResponseWriter, *http.Request))
}

Middleware interface for use with RequestWorker

type Request

type Request = internal.Request

Core type aliases.

type RequestCtx

type RequestCtx = internal.RequestCtx

Core type aliases.

type RequestHandler

type RequestHandler = internal.RequestHandler

Core type aliases.

type RequestWorker

type RequestWorker struct {
	*internal.RequestWorker
}

RequestWorker provides a public interface to the internal RequestWorker

func NewRequestWorker

func NewRequestWorker() *RequestWorker

NewRequestWorker creates a new RequestWorker for direct use

func (*RequestWorker) AddMiddleware

func (w *RequestWorker) AddMiddleware(middleware Middleware)

AddMiddleware adds a regular middleware that executes after routing

func (*RequestWorker) AddPreMiddleware

func (w *RequestWorker) AddPreMiddleware(middleware Middleware)

AddPreMiddleware adds a pre-middleware that executes before routing

func (*RequestWorker) AddRoute

func (w *RequestWorker) AddRoute(
	method, path string, handler func(http.ResponseWriter, *http.Request), componentID string,
)

AddRoute adds a route to the worker

type ResponseWriter

type ResponseWriter = internal.ResponseWriter

Core type aliases.

type RewriteHandler

type RewriteHandler = internal.RewriteHandler

Handler function types.

type RoutePath

type RoutePath = internal.RoutePath

Core structs.

type Server

type Server = internal.Server

Core type aliases.

type TracingOption

type TracingOption func(*middleware.TracingMiddleware)

TracingOption allows customization of tracing middleware behavior

func WithCORSMerging

func WithCORSMerging(enable bool) TracingOption

WithCORSMerging enables or disables merging of CORS preflight traces with actual requests

func WithSkipMethods

func WithSkipMethods(methods ...string) TracingOption

WithSkipMethods configures HTTP methods to skip during tracing

func WithSkipPaths

func WithSkipPaths(paths ...string) TracingOption

WithSkipPaths configures paths to skip during tracing (e.g., health checks)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL