blob: 088e7ff5011a080a63f354067c91507350a6561e [file] [log] [blame]
iomodob6d9eb92025-07-24 20:54:45 +04001package commands
2
3import (
4 "log/slog"
5 "os"
6 "os/signal"
7 "syscall"
8
9 "github.com/iomodo/staff/server"
10 "github.com/spf13/cobra"
11)
12
13// Command is an abstraction of the cobra Command
14type Command = cobra.Command
15
16// Run function starts the application
17func Run(args []string) error {
18 rootCmd.SetArgs(args)
19 return rootCmd.Execute()
20}
21
22// rootCmd is a command to run the server.
23var rootCmd = &cobra.Command{
24 Use: "server",
25 Short: "Runs a server",
26 Long: `Runs a server. Killing the process will stop the server`,
27 RunE: serverCmdF,
28}
29
30func serverCmdF(_ *cobra.Command, _ []string) error {
31 srv, err := runServer()
32 if err != nil {
33 return err
34 }
35 defer srv.Shutdown()
36
37 // wait for kill signal before attempting to gracefully shutdown
38 // the running service
39 interruptChan := make(chan os.Signal, 1)
40 signal.Notify(interruptChan, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
41 <-interruptChan
42 return nil
43}
44
45func runServer() (*server.Server, error) {
46 logger := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
47 Level: slog.LevelDebug,
48 }))
49
50 srv, err := server.NewServer(logger)
51 if err != nil {
52 logger.Error(err.Error())
53 return nil, err
54 }
55
56 serverErr := srv.Start()
57 if serverErr != nil {
58 logger.Error(serverErr.Error())
59 return nil, serverErr
60 }
61 return srv, nil
62}