service

package
v1.11.0 Latest Latest
Warning

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

Go to latest
Published: May 31, 2026 License: MPL-2.0 Imports: 9 Imported by: 0

README

SonicRed Service

The service library of SonicRed facilitates the management of multiple HTTP server instances. Its intent is to lift the responsibility of managing the lifetimes of these servers to the user.

Installation

To install the SonicRed service library, you can use the following command:

go get github.com/AlphaOne1/sonicred/service

Versions of this library are bound to the semantic versioning of SonicRed. This library is intended for public use but be aware that breaking changes may occur between minor versions. No breaking changes will be introduced between patch versions.

Getting Started

The following snippet illustrates the basic usage of the SonicRed service library:

server := http.Server{}

// ... initializations of the server component

g, _ := service.NewGroup(service.WithServer(&server, "webserver"))

// creating a timeout context for demonstration purposes
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

_ = g.StartAll(ctx)

// ... the servers are running now for the specified 10 seconds

g.WaitAllServersShutdown()

As one can see, the details of managing a clean server startup and waiting for its correct shutdown are encapsulated in the Group type.

Managing Multiple Servers

Multiple servers can be managed by a single Group instance specifying multiple service.WithServer or using the service.WithServers options.

For a small number of servers the WithServer option is easier to use:

server0 := http.Server{}
server1 := http.Server{}

// ... initializations of the server components

g, _ := service.NewGroup(
    service.WithServer(&server0, "webserver"),
    service.WithServer(&server1, "instrumentation"))

// creating a timeout context for demonstration purposes
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

_ = g.StartAll(ctx)

// ... the servers are running now for the specified 10 seconds

g.WaitAllServersShutdown()

But if the numbers grow, it is recommended to use the WithServers option:

server0 := http.Server{}

servers := []*http.Server{&server0}
names := []string{"server0"} // must contain an entry for each server

// ... initializations of the server components

g, _ := service.NewGroup(service.WithServers(servers, names))

// creating a timeout context for demonstration purposes
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()

_ = g.StartAll(ctx)

// ... the servers are running now for the specified 10 seconds

g.WaitAllServersShutdown()

Further Options

As SonicRed service library is an integral part of program flow, it is useful to give it the possibility to output its own log messages. The option service.WithLogger allows to specify a slog.Logger.

To limit the time the servers have to shut down, a shutdown timeout can be specified using the service.WithShutdownTimeout option.

A typical server usecase, example could look like this (deliberately simplified, no error handling):

server := http.Server{} // generate the webserver

// using SonicRed instrumentation library to generate an instrumentation server
instrumentationServer, _ := instrumentation.Server(
    "",     // all addresses
    "8081", // port
    nil,    // no prometheus handler
    true,   // enables pprof
    slog.Default())

// create a service group with the servers and the logger
services, _ := service.NewGroup(
    service.WithLogger(slog.Default()),
    service.WithShutdownTimeout(5*time.Second),
    service.WithServer(&server, "webserver"),
    service.WithServer(instrumentationServer, "instrumentation"))

// telling to signalize on a context when the specified signals are received
signalShutdown, signalShutdownFunc := signal.NotifyContext(
    context.Background(),
    syscall.SIGINT,
    syscall.SIGTERM)

defer signalShutdownFunc() // should be called for cleanups

_ = services.StartAll(signalShutdown) // starts the servers and waits for a shutdown signal
services.WaitAllServersShutdown()     // waits for the servers to have shut down

Documentation

Overview

Package service provides a Group type for managing multiple HTTP servers.

Index

Constants

This section is empty.

Variables

View Source
var ErrNilServer = errors.New("server is nil")

ErrNilServer indicates that the server instance is nil and cannot be used.

View Source
var ErrNoServers = errors.New("no servers configured")

ErrNoServers represents an error indicating that no servers have been configured.

View Source
var ErrServerNameLenMismatch = errors.New("server and name length mismatch")

ErrServerNameLenMismatch indicates a mismatch between the lengths of the server and name values.

Functions

This section is empty.

Types

type Group

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

Group represents a collection of HTTP servers managed together with shared lifecycle controls.

func NewGroup

func NewGroup(options ...Option) (*Group, error)

NewGroup creates and returns a new Group, applying the provided options. Returns an error if any option fails.

func (*Group) ServerCount

func (g *Group) ServerCount() int

ServerCount gives the current number of running servers in the group. This value is volatile and should be used only for informational purposes, e.g. display to the user.

func (*Group) StartAll

func (g *Group) StartAll(ctx context.Context) error

StartAll starts all configured servers and returns once all listen sockets are bound. It does not block; use WaitAllServersShutdown() to wait for completion.

func (*Group) WaitAllServersShutdown

func (g *Group) WaitAllServersShutdown()

WaitAllServersShutdown waits for all running servers goroutines to complete and their shutdown processes using ShutdownWhenDone, before continuing execution.

type Option

type Option func(*Group) error

Option is a function that configures a Group by applying custom settings or modifications.

func WithLogger

func WithLogger(log *slog.Logger) Option

WithLogger sets a custom logger for the Group and returns an Option for configuration.

func WithServer

func WithServer(server *http.Server, serverName string) Option

WithServer adds an HTTP server with a specified name to the group for management and lifecycle control.

func WithServers

func WithServers(servers []*http.Server, serverNames []string) Option

WithServers adds the provided HTTP servers and their corresponding names to the Group configuration.

func WithShutdownTimeout

func WithShutdownTimeout(timeout time.Duration) Option

WithShutdownTimeout sets a timeout duration for server shutdown within the Group and returns an Option.

Jump to

Keyboard shortcuts

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