Skip to content

The httpserver package in Go offers a simple and efficient solution for creating, running, and gracefully shutting down HTTP servers, with support for context cancellation and concurrent execution.

License

Notifications You must be signed in to change notification settings

dmitrymomot/httpserver

Repository files navigation

httpserver

GitHub tag (latest SemVer) Go Reference License

Tests CodeQL Analysis GolangCI Lint Go Report Card

The httpserver package provides a robust and feature-rich HTTP server implementation in Go, offering graceful shutdown, static file serving, and extensive configuration options. It's designed to be both simple to use and powerful enough for production environments.

Features

  • Easy server setup and configuration
  • Graceful shutdown with configurable timeout
  • Context-based cancellation
  • Static file serving with caching support
  • Embedded filesystem support
  • Comprehensive server options
  • Structured logging support
  • TLS configuration
  • Concurrent execution with errgroup
  • Production-ready defaults

Installation

go get github.com/dmitrymomot/httpserver

Basic Usage

Simple HTTP Server

package main

import (
    "context"
    "net/http"
    "github.com/dmitrymomot/httpserver"
)

func main() {
    // Create a new router
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, World!"))
    })

    // Start the server with default configuration
    if err := httpserver.Run(context.Background(), ":8080", mux); err != nil {
        panic(err)
    }
}

Advanced Server Configuration

package main

import (
    "context"
    "net/http"
    "time"
    "github.com/dmitrymomot/httpserver"
)

func main() {
    mux := http.NewServeMux()
    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        w.Write([]byte("Hello, World!"))
    })

    // Create a new server with custom options
    server, err := httpserver.New(":8080", mux,
        httpserver.WithReadTimeout(5*time.Second),
        httpserver.WithWriteTimeout(10*time.Second),
        httpserver.WithIdleTimeout(15*time.Second),
        httpserver.WithGracefulShutdown(30*time.Second),
        httpserver.WithMaxHeaderBytes(1<<20), // 1MB
    )
    if err != nil {
        panic(err)
    }

    // Start the server with context
    ctx := context.Background()
    if err := server.Start(ctx); err != nil {
        panic(err)
    }
}

Serving Static Files

package main

import (
    "context"
    "net/http"
    "time"
    "github.com/dmitrymomot/httpserver"
)

func main() {
    mux := http.NewServeMux()

    // Serve files from physical directory
    mux.HandleFunc("/static/", httpserver.StaticHandler(
        "/static",
        http.Dir("./static"),
        10*time.Minute, // Cache TTL
    ))

    // Serve files from embedded filesystem
    //go:embed static/*
    var embedFS embed.FS
    mux.HandleFunc("/assets/", httpserver.EmbeddedStaticHandler(
        embedFS,
        24*time.Hour, // Cache TTL
    ))

    if err := httpserver.Run(context.Background(), ":8080", mux); err != nil {
        panic(err)
    }
}

Graceful Shutdown

package main

import (
    "context"
    "net/http"
    "time"
    "github.com/dmitrymomot/httpserver"
)

func main() {
    // Create context with timeout
    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
    defer cancel()

    mux := http.NewServeMux()
    server, _ := httpserver.New(":8080", mux)

    // Server will shut down gracefully when context is canceled
    if err := server.Start(ctx); err != nil {
        panic(err)
    }
}

Server Options

The package provides numerous options to configure the server:

  • WithPreconfiguredServer - Use a pre-configured http.Server
  • WithReadTimeout - Set maximum duration for reading requests
  • WithWriteTimeout - Set maximum duration for writing responses
  • WithIdleTimeout - Set maximum time to wait for the next request
  • WithMaxHeaderBytes - Set maximum size of request headers
  • WithTLSConfig - Configure TLS settings
  • WithGracefulShutdown - Set graceful shutdown timeout
  • WithLogger - Set custom logger

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

This project is licensed under the Apache 2.0 - see the LICENSE file for details.

About

The httpserver package in Go offers a simple and efficient solution for creating, running, and gracefully shutting down HTTP servers, with support for context cancellation and concurrent execution.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages