aboutsummaryrefslogtreecommitdiff
path: root/server/server.go
blob: cd63820f81814b8a814269df57b103cc607f289c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// Copyright 2026 Terin Stock
// SPDX-License-Identifier: EUPL-1.2

package server

import (
	"cmp"
	"context"
	"errors"
	"log/slog"
	"net/http"
	"time"
)

// HTTPServer implements a service that serves the [http.Server] returned by NewServer.
type HTTPServer struct {
	// NewServer is called each time the HTTPServer is started. Do not return the
	// same instance, as an [http.Server] can not be reused after shutdown.
	NewServer func() *http.Server

	// ShutdownTimeout is the amount of time to gracefully shutdown, defaults
	// to 5 seconds. Should be less than the supervisor's Timeout.
	ShutdownTimeout *time.Duration
}

// Serve starts the [http.Server] returned by NewServer. The function blocks until the HTTP server
// is stopped. On context cancellation the HTTP server's Shutdown method is called for a graceful
// shutdown of at least ShutdownTimeout.
func (s *HTTPServer) Serve(ctx context.Context) error {
	srv := s.NewServer()
	errCh := make(chan error, 1)

	go func() { errCh <- srv.ListenAndServe() }()

	select {
	case err := <-errCh:
		if errors.Is(err, http.ErrServerClosed) {
			return nil
		}
		return err
	case <-ctx.Done():
	}

	timeout := cmp.Or(*s.ShutdownTimeout, 5*time.Second)
	shutdownCtx, cancel := context.WithTimeout(context.Background(), timeout)
	defer cancel()

	if err := srv.Shutdown(shutdownCtx); err != nil {
		slog.Error("error shutting down server", "error", err)
		_ = srv.Close()
	}
	<-errCh
	return nil
}