httpserver

package module
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2024 License: Apache-2.0 Imports: 10 Imported by: 1

README

httpserver

GitHub tag (latest SemVer) Go Reference License

Tests CodeQL Analysis GolangCI Lint Go Report Card

The httpserver package in Go offers a simple and efficient solution for creating, running, and gracefully shutting down HTTP servers. It supports context cancellation and concurrent execution, making it suitable for a wide range of web applications.

Features

  • Easy to set up and start HTTP servers
  • Graceful shutdown handling
  • Context cancellation support
  • Concurrency management with errgroup
  • Lightweight and flexible design

Installation

To install the httpserver package, use the following command:

go get github.com/dmitrymomot/httpserver

Usage

Here's a basic example of how to use the httpserver package:

package main

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

func main() {
    ctx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
    defer cancel()

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

    if err := httpserver.Run(ctx, ":8080", r); err != nil {
        panic(err)
    }
}

This will start an HTTP server on port 8080 and respond with "Hello, World!" to GET / request. The server will be gracefully shut down after 10 minutes.

The httpserver.Run function is a shortcut for creating a new HTTP server and starting it. It's equivalent to the following code:

srv := httpserver.NewServer(addr, handler)
if err := srv.Start(ctx); err != nil {
    panic(err)
}
Using with errgroup:
package main

import (
    "context"
    "net/http"
    "github.com/dmitrymomot/httpserver"
    "golang.org/x/sync/errgroup"
)

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

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

    g, ctx := errgroup.WithContext(ctx)
    g.Go(func() error {
        return httpserver.Run(ctx, ":8080", r)
    })
    g.Go(func() error {
        return httpserver.Run(ctx, ":8081", r)
    })

    if err := g.Wait(); err != nil {
        panic(err)
    }
}

The code above will start two HTTP servers on ports 8080 and 8081. Both servers will be gracefully shut down when the context is canceled.

With options:
package main

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

func main() {
    ctx, cancel := context.WithCancel(context.Background())
    defer cancel()

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

    srv := httpserver.NewServer(
        ":8080", r, 
        httpserver.WithGracefulShutdown(10*time.Second),
        httpserver.WithReadTimeout(5*time.Second),
    )
    if err := srv.Start(ctx); err != nil {
        panic(err)
    }
}

The code above will start an HTTP server on port 8080 with a graceful shutdown timeout of 10 seconds and a read timeout of 5 seconds.

Contributing

Contributions to the httpserver package are welcome! Here are some ways you can contribute:

  • Reporting bugs
  • Additional tests cases
  • Suggesting enhancements
  • Submitting pull requests
  • Sharing the love by telling others about this project

License

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

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Run

func Run(ctx context.Context, addr string, handler http.Handler) error

Run starts an HTTP server on the specified address and runs the provided handler. It returns an error if the server fails to start or encounters an error during execution. The context.Context parameter allows for graceful shutdown of the server. The addr parameter specifies the address to listen on, e.g., ":8080" for all interfaces on port 8080. The handler parameter is an http.Handler that defines the behavior of the server.

func WithErrorLog

func WithErrorLog(l *log.Logger) serverOption

WithErrorLog sets the error logger for the server. If nil, the log package's standard logger is used.

func WithGracefulShutdown added in v0.1.1

func WithGracefulShutdown(d time.Duration) serverOption

WithGracefulShutdown sets the graceful shutdown timeout. If zero, the default timeout of 5 seconds is used.

func WithIdleTimeout

func WithIdleTimeout(d time.Duration) serverOption

WithIdleTimeout sets the maximum amount of time to wait for the next request when keep-alives are enabled. If IdleTimeout is zero, the value of ReadTimeout is used. If both are zero, there is no timeout.

func WithMaxHeaderBytes

func WithMaxHeaderBytes(n int) serverOption

WithMaxHeaderBytes sets the maximum size of request headers. This prevents attacks where an attacker sends a large header to consume server resources. If zero, DefaultMaxHeaderBytes of 1MB is used.

func WithPreconfiguredServer

func WithPreconfiguredServer(s *http.Server) serverOption

WithPreconfiguredServer allows you to provide a preconfigured http.Server instance. This is useful if you want to configure TLS or other options that are not exposed by this package.

func WithReadHeaderTimeout

func WithReadHeaderTimeout(d time.Duration) serverOption

WithReadHeaderTimeout sets the amount of time allowed to read request headers. A duration of 0 means no timeout.

func WithReadTimeout

func WithReadTimeout(d time.Duration) serverOption

WithReadTimeout sets the maximum duration for reading the entire request, including the body. This also includes the time spent reading the request header. If the server does not receive a new request within this duration it will close the connection. A duration of 0 means no timeout.

func WithTLSConfig

func WithTLSConfig(t *tls.Config) serverOption

WithTLSConfig sets the TLS configuration to use when starting TLS. If nil, the default configuration is used. If non-nil, HTTP/2 support may not be enabled by default.

func WithTLSNextProto

func WithTLSNextProto(f func(*http.Server, *tls.Conn, http.Handler)) serverOption

WithTLSNextProto sets a function to be called after a TLS handshake has been completed. This is useful for protocols which require interaction immediately after the handshake. If non-nil, HTTP/2 support may not be enabled by default.

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) serverOption

WithWriteTimeout sets the maximum duration before timing out writes of the response. A duration of 0 means no timeout.

Types

type Server

type Server struct {
	// contains filtered or unexported fields
}

Server represents an HTTP server wrapper. It contains an underlying http.Server instance and provides methods to start and stop the server. It also provides a Run function to start an HTTP server with graceful shutdown. The server is stopped gracefully when the context is cancelled or a shutdown signal is received.

func New

func New(addr string, handler http.Handler, opt ...serverOption) *Server

New creates a new instance of the new HTTP server with the specified address, handler, and optional server options. The server options can be used to customize the server's behavior. The addr parameter specifies the address to listen on, e.g., ":8080" for all interfaces on port 8080. The handler parameter is an http.Handler that defines the behavior of the server. The opt parameter is a variadic list of server options. The server options are applied in order, so the last option overrides the previous ones. The server options are applied before the server is started.

func (*Server) Close

func (s *Server) Close() error

Close stops the server immediately without waiting for active connections to finish. It returns an error if the server fails to stop.

func (*Server) Start

func (s *Server) Start(ctx context.Context) error

Start starts the server and listens for incoming requests. It uses the provided context to handle graceful shutdown. The context is also used to handle shutdown signals from the OS. It returns an error if the server fails to start or encounters an error during shutdown.

func (*Server) Stop

func (s *Server) Stop(timeout time.Duration) error

Stop stops the server gracefully with the given timeout. It uses the provided timeout to gracefully shutdown the underlying HTTP server. If the timeout is reached before the server is fully stopped, an error is returned.

Jump to

Keyboard shortcuts

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