-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
60 lines (51 loc) · 1.31 KB
/
server.go
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 main
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"time"
"github.com/DavidNix/indie/ent"
"github.com/DavidNix/indie/server"
_ "github.com/mattn/go-sqlite3"
"github.com/spf13/cobra"
)
func rootCmd() *cobra.Command {
root := cobra.Command{
RunE: runServer,
}
root.Flags().StringP("addr", "a", ":3000", "Address to listen on")
return &root
}
func runServer(cmd *cobra.Command, args []string) error {
const driver = "sqlite3"
client, err := ent.Open(driver, os.Getenv("DATABASE_URL"))
if err != nil {
return fmt.Errorf("failed top open connection to %s: %w", driver, err)
}
defer client.Close()
// Auto-database migrations
if err = client.Schema.Create(cmd.Context()); err != nil {
return fmt.Errorf("failed creating schema resources: %w", err)
}
// TODO: Remove for production, for example demo only.
if err = ent.Seed(cmd.Context(), client); err != nil {
return fmt.Errorf("failed seeding database: %w", err)
}
app := server.NewApp(client)
go func() {
<-cmd.Context().Done()
slog.Info("Shutting down server")
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
_ = app.Shutdown(ctx)
}()
addr, _ := cmd.Flags().GetString("addr")
err = app.Start(addr)
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return err
}