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
|
package server
import (
"apjournal/config"
"apjournal/internal/handlers"
"context"
"log/slog"
"os"
"os/signal"
"syscall"
"github.com/jmoiron/sqlx"
)
// Server interface
type Server interface {
Listen()
}
type server struct {
config config.Config
actions *handlers.Handlers
ctx context.Context
close context.CancelFunc
}
func (srv *server) stopOnSignal(close context.CancelFunc) {
// listen for termination signals
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, os.Interrupt, syscall.SIGINT)
signal.Notify(sigc, os.Interrupt, syscall.SIGTERM)
sig := <-sigc
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
log.Info("Shutting down services",
"section", "server",
"app_event", "terminate",
"signal", sig.String())
close()
os.Exit(0)
}
func NewServer(cfg config.Config, log *slog.Logger, conn *sqlx.DB) Server {
ctx, close := context.WithCancel(context.Background())
actions := handlers.NewHandlers(cfg, log, conn)
return &server{
config: cfg,
actions: actions,
ctx: ctx,
close: close,
}
}
// Listen for new events that affect the market and process them
func (srv *server) Listen() {
// start the http server
go srv.ListenToRequests()
srv.stopOnSignal(srv.close)
}
|