|
| 1 | +package api |
| 2 | + |
| 3 | +import ( |
| 4 | + "context" |
| 5 | + "errors" |
| 6 | + "fmt" |
| 7 | + "log/slog" |
| 8 | + "net" |
| 9 | + "net/http" |
| 10 | + "os" |
| 11 | + "os/signal" |
| 12 | + |
| 13 | + "github.com/talgat-ruby/lessons-go/lesson4/example1/configs" |
| 14 | + "github.com/talgat-ruby/lessons-go/lesson4/example1/internal/api/router" |
| 15 | + apiT "github.com/talgat-ruby/lessons-go/lesson4/example1/internal/api/types" |
| 16 | +) |
| 17 | + |
| 18 | +type server struct { |
| 19 | + conf *configs.ApiConfig |
| 20 | +} |
| 21 | + |
| 22 | +func New(conf *configs.ApiConfig) apiT.Api { |
| 23 | + s := &server{ |
| 24 | + conf: conf, |
| 25 | + } |
| 26 | + |
| 27 | + return s |
| 28 | +} |
| 29 | + |
| 30 | +func (s *server) Config() *configs.ApiConfig { |
| 31 | + return s.conf |
| 32 | +} |
| 33 | + |
| 34 | +func (s *server) Start(ctx context.Context, cancel context.CancelFunc) { |
| 35 | + mux := http.NewServeMux() |
| 36 | + router.SetupRoutes(mux, s) |
| 37 | + |
| 38 | + // start up HTTP |
| 39 | + srv := &http.Server{ |
| 40 | + Addr: fmt.Sprintf(":%d", s.conf.Port), |
| 41 | + Handler: mux, |
| 42 | + BaseContext: func(_ net.Listener) context.Context { |
| 43 | + return ctx |
| 44 | + }, |
| 45 | + } |
| 46 | + |
| 47 | + // Listen from s different goroutine |
| 48 | + go func() { |
| 49 | + if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 50 | + slog.ErrorContext(ctx, "server error", "error", err) |
| 51 | + } |
| 52 | + |
| 53 | + cancel() |
| 54 | + }() |
| 55 | + |
| 56 | + slog.InfoContext( |
| 57 | + ctx, |
| 58 | + "starting api service", |
| 59 | + "port", s.conf.Port, |
| 60 | + "playground", fmt.Sprintf("http://localhost:%d/", s.conf.Port), |
| 61 | + ) |
| 62 | + |
| 63 | + shutdown := make(chan os.Signal, 1) // Create channel to signify s signal being sent |
| 64 | + signal.Notify(shutdown, os.Interrupt) // When an interrupt is sent, notify the channel |
| 65 | + |
| 66 | + go func() { |
| 67 | + sig := <-shutdown |
| 68 | + |
| 69 | + slog.WarnContext(ctx, "signal received - shutting down...", "signal", sig) |
| 70 | + if err := srv.Shutdown(ctx); err != nil { |
| 71 | + slog.ErrorContext(ctx, "server shutdown error", "error", err) |
| 72 | + } |
| 73 | + }() |
| 74 | +} |
0 commit comments