server

package
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2025 License: BSD-3-Clause Imports: 14 Imported by: 2

README

HTTP Server Package

The HTTP Server package provides production-ready HTTP server utilities with graceful shutdown, zero-downtime deployment support, and sensible defaults for Go web applications.

Features

  • Graceful Shutdown: Clean handling of shutdown signals (SIGTERM, SIGINT)
  • Zero-Downtime Deployment: Support for seamless server upgrades
  • Connection Management: Proper management of existing connections during shutdown
  • Timeout Configuration: Sensible defaults for read, write, and idle timeouts
  • Max Request Size: Protection against oversized payloads
  • Wait Groups: Built-in waitgroup support for coordinated shutdowns
  • Cross-Package Integration: Works with health, chain, and middleware packages

Quick Start

package main

import (
    "net/http"
    "github.com/alextanhongpin/core/http/server"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/ping", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("pong"))
    })
    // Simple server with graceful shutdown
    server.ListenAndServe(":8080", mux)
    // OR use advanced configuration
    srv := server.New(":8080", mux)
    server.WaitGroup(srv)
}

API Reference

Basic Server
ListenAndServe(addr string, handler http.Handler) error

Creates and starts an HTTP server with graceful shutdown support.

Advanced Configuration
New(addr string, handler http.Handler, options ...Option) *http.Server

Creates a new HTTP server with custom configuration options.

WaitGroup(srv *http.Server)

Waits for server shutdown and coordinates cleanup.

Best Practices

  • Always use graceful shutdown for production servers.
  • Configure timeouts and max request size for security and reliability.
  • Integrate health endpoints for orchestration and monitoring.

License

MIT

Documentation

Overview

Package server provides production-ready HTTP server utilities with graceful shutdown and zero-downtime upgrades.

Package server provides production-ready HTTP server utilities with graceful shutdown.

This package simplifies the creation of HTTP servers with sensible defaults for production use, including proper timeouts, graceful shutdown handling, and signal management.

Key features: - Sensible timeout defaults for production use - Graceful shutdown on SIGINT/SIGTERM signals - Proper error handling and logging - Support for running multiple servers concurrently

Example usage:

// Simple server with default settings
server.ListenAndServe(":8080", myHandler)

// Multiple servers with custom configuration
server1 := server.New(":8080", apiHandler)
server2 := server.New(":8081", adminHandler)
server.WaitGroup(server1, server2)

The servers will automatically handle SIGINT (Ctrl+C) and SIGTERM signals for graceful shutdown, allowing in-flight requests to complete before terminating the process.

Index

Constants

View Source
const (
	// MB represents 1 megabyte in bytes
	MB = 1 << 20 // 1 MB

)

Variables

This section is empty.

Functions

func ListenAndServe

func ListenAndServe(port string, handler http.Handler)

ListenAndServe starts an HTTP server with default settings and graceful shutdown.

This is a convenience function that creates a new server with sensible defaults and waits for it to complete. The server will handle SIGINT and SIGTERM signals for graceful shutdown.

Parameters:

  • port: The port to listen on (e.g., ":8080", ":443")
  • handler: The HTTP handler to serve requests

This function blocks until the server shuts down or encounters an error.

Example:

server.ListenAndServe(":8080", myHandler)

func ListenAndServeForever

func ListenAndServeForever(port string, handler http.Handler)

ListenAndServeForever allows zero-downtime upgrade using file descriptor inheritance.

This function implements a zero-downtime upgrade mechanism by using Unix signals and file descriptor inheritance. When a SIGUSR2 signal is received, the process forks a child process that inherits the listener file descriptor, allowing the new version to start serving requests while the old version gracefully shuts down.

The upgrade process works as follows: 1. The running server listens for SIGUSR2 signals 2. On receiving SIGUSR2, it forks a new process with the same binary 3. The new process inherits the listener file descriptor 4. The old process gracefully shuts down after completing in-flight requests 5. The new process continues serving requests without dropping connections

Parameters:

  • port: The port to listen on (e.g., ":8080")
  • handler: The HTTP handler to serve requests

Usage example:

// Start the server
go build -o myapp main.go
./myapp

// In another terminal, trigger zero-downtime upgrade:
kill -SIGUSR2 $(lsof -ti:8080)

// Or using process ID:
kill -SIGUSR2 <pid>

The function blocks until the server is shut down. It's designed for production environments where you need to upgrade the application binary without dropping active connections or experiencing downtime.

Requirements: - Unix-like operating system (Linux, macOS, etc.) - The binary must be accessible at the same path when upgrading - Sufficient system resources to run both old and new processes briefly

Note: This function uses low-level Unix system calls and file descriptor manipulation, making it unsuitable for Windows environments.

func New

func New(port string, handler http.Handler) *http.Server

New creates a new HTTP server with production-ready default settings.

The server is configured with appropriate timeouts for production use: - Read timeout: 5 seconds - Write timeout: 5 seconds - Read header timeout: 5 seconds

These defaults help prevent resource exhaustion and provide good performance characteristics for most HTTP services.

Parameters:

  • port: The port to listen on (e.g., ":8080", "localhost:3000")
  • handler: The HTTP handler to serve requests

Returns:

  • A configured *http.Server ready to start

Example:

server := server.New(":8080", myHandler)
log.Fatal(server.ListenAndServe())

Note: The commented-out middleware (TimeoutHandler, MaxBytesHandler) can be uncommented if needed, but may interfere with streaming responses or SSE.

func WaitGroup

func WaitGroup(servers ...*http.Server)

WaitGroup starts multiple HTTP servers concurrently and waits for them to shut down gracefully.

This function handles the lifecycle of multiple HTTP servers: 1. Starts all servers in separate goroutines 2. Sets up signal handling for SIGINT and SIGTERM 3. On signal reception, initiates graceful shutdown of all servers 4. Waits for all servers to complete shutdown or timeout 5. Logs any errors that occur during startup or shutdown

Parameters:

  • servers: Variable number of *http.Server instances to run

The function blocks until all servers have shut down or the process is terminated.

Example:

apiServer := server.New(":8080", apiHandler)
adminServer := server.New(":8081", adminHandler)
metricsServer := server.New(":9090", metricsHandler)

server.WaitGroup(apiServer, adminServer, metricsServer)

Signal handling: - SIGINT (Ctrl+C): Initiates graceful shutdown - SIGTERM: Initiates graceful shutdown (common in container environments)

Types

This section is empty.

Jump to

Keyboard shortcuts

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