about summary refs log tree commit diff stats
path: root/internal/server/server.go
blob: 77163d380364c8d0ecac7174d6b73479d89daaa4 (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
55
56
57
58
59
60
61
62
package server

import (
	"context"
	"log"
	"log/slog"
	"net"
	"net/http"
	"searchix/internal/config"
	"time"

	"github.com/pkg/errors"
)

type Server struct {
	*http.Server
}

func New(conf *config.Config, liveReload bool) (*Server, error) {
	mux, err := NewMux(conf, liveReload)
	if err != nil {
		return nil, err
	}
	listenAddress := net.JoinHostPort(conf.Web.ListenAddress, conf.Web.Port)

	return &Server{
		&http.Server{
			Addr:              listenAddress,
			Handler:           mux,
			ReadHeaderTimeout: 20 * time.Second,
		},
	}, nil
}

func (s *Server) Start() error {
	if err := s.ListenAndServe(); err != http.ErrServerClosed {
		return errors.WithMessage(err, "could not start server")
	}

	return nil
}

func (s *Server) Stop() chan struct{} {
	slog.Debug("stop called")

	idleConnsClosed := make(chan struct{})

	go func() {
		slog.Debug("shutting down server")
		ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
		defer cancel()
		err := s.Server.Shutdown(ctx)
		slog.Debug("server shut down")
		if err != nil {
			// Error from closing listeners, or context timeout:
			log.Printf("HTTP server Shutdown: %v", err)
		}
		close(idleConnsClosed)
	}()

	return idleConnsClosed
}