stillbox/pkg/cmd/serve/serve.go

66 lines
1.1 KiB
Go
Raw Normal View History

2024-11-03 07:19:03 -05:00
package serve
2024-07-14 13:47:48 -04:00
import (
2024-10-21 13:49:20 -04:00
"context"
"os"
"os/signal"
2024-07-14 13:47:48 -04:00
"dynatron.me/x/stillbox/internal/common"
2024-11-03 07:19:03 -05:00
"dynatron.me/x/stillbox/pkg/config"
"dynatron.me/x/stillbox/pkg/server"
2024-07-14 13:47:48 -04:00
"github.com/spf13/cobra"
)
type ServeOptions struct {
cfg *config.Config
}
func Command(cfg *config.Config) *cobra.Command {
opts := makeOptions(cfg)
serveCmd := &cobra.Command{
2024-10-17 11:28:43 -04:00
Use: "serve",
2024-11-03 07:19:03 -05:00
Short: "starts the" + common.AppName + " server",
2024-10-17 11:28:43 -04:00
PersistentPreRunE: cfg.PreRunE(),
RunE: common.RunE(opts),
2024-07-14 13:47:48 -04:00
}
return serveCmd
}
func makeOptions(cfg *config.Config) *ServeOptions {
return &ServeOptions{
cfg: cfg,
}
}
func (o *ServeOptions) Options(_ *cobra.Command, args []string) error {
return nil
}
func (o *ServeOptions) Execute() error {
2024-10-21 13:49:20 -04:00
ctx, cancel := context.WithCancel(context.Background())
2024-07-14 13:47:48 -04:00
2024-10-21 13:49:20 -04:00
sig := make(chan os.Signal, 1)
signal.Notify(sig, os.Interrupt)
defer func() {
signal.Stop(sig)
cancel()
}()
go func() {
select {
case <-sig:
cancel()
case <-ctx.Done():
}
}()
2024-10-21 14:11:08 -04:00
srv, err := server.New(ctx, o.cfg)
2024-07-14 13:47:48 -04:00
if err != nil {
return err
}
2024-10-21 13:49:20 -04:00
return srv.Go(ctx)
2024-07-14 13:47:48 -04:00
}