Start is used to start the application. The application will run until either the given context is cancelled, or the application is ended.
(ctx context.Context)
| 37 | // will run until either the given context is cancelled, or |
| 38 | // the application is ended. |
| 39 | func (a *App) Start(ctx context.Context) error { |
| 40 | db, err := database.Connect(ctx, a.logger, a.files) |
| 41 | if err != nil { |
| 42 | return fmt.Errorf("failed to connect to database: %w", err) |
| 43 | } |
| 44 | |
| 45 | a.db = db |
| 46 | |
| 47 | router, err := a.loadRoutes() |
| 48 | if err != nil { |
| 49 | return fmt.Errorf("failed when loading routes: %w", err) |
| 50 | } |
| 51 | |
| 52 | port := 8080 |
| 53 | srv := &http.Server{ |
| 54 | Addr: fmt.Sprintf(":%d", port), |
| 55 | Handler: router, |
| 56 | } |
| 57 | |
| 58 | errCh := make(chan error, 1) |
| 59 | |
| 60 | go func() { |
| 61 | err := srv.ListenAndServe() |
| 62 | if err != nil && !errors.Is(err, http.ErrServerClosed) { |
| 63 | errCh <- fmt.Errorf("failed to listen and serve: %w", err) |
| 64 | } |
| 65 | |
| 66 | close(errCh) |
| 67 | }() |
| 68 | |
| 69 | a.logger.Info("server running", slog.Int("port", port)) |
| 70 | |
| 71 | select { |
| 72 | // Wait until we receive SIGINT (ctrl+c on cli) |
| 73 | case <-ctx.Done(): |
| 74 | break |
| 75 | case err := <-errCh: |
| 76 | return err |
| 77 | } |
| 78 | |
| 79 | sCtx, cancel := context.WithTimeout(context.Background(), time.Second*15) |
| 80 | defer cancel() |
| 81 | |
| 82 | srv.Shutdown(sCtx) |
| 83 | |
| 84 | return nil |
| 85 | } |
no test coverage detected