Repository navigation
Expand file tree
/
Copy pathmain.go
More file actions
87 lines (83 loc) · 2.32 KB
/
Copy pathmain.go
File metadata and controls
87 lines (83 loc) · 2.32 KB
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package main
import (
"context"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"virtual-tour/db"
"virtual-tour/internal/database"
"virtual-tour/internal/derivatives"
"virtual-tour/internal/httpapi"
"virtual-tour/internal/storage"
)
func main() {
if err := run(); err != nil {
slog.Error("API stopped", "error", err)
os.Exit(1)
}
}
func run() error {
chunkMode, err := httpapi.ParseChunkRollout(os.Getenv("ASSET_CHUNK_STREAMING"))
if err != nil {
return err
}
splatMode, err := httpapi.ParseSplatRollout(os.Getenv("ASSET_SPLAT_SUPPORT"))
if err != nil {
return err
}
walking, err := httpapi.ParseSplatFeature("ASSET_SPLAT_WALKING", os.Getenv("ASSET_SPLAT_WALKING"))
if err != nil {
return err
}
streaming, err := httpapi.ParseSplatFeature("ASSET_SPLAT_STREAMING", os.Getenv("ASSET_SPLAT_STREAMING"))
if err != nil {
return err
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
pool, err := pgxpool.New(ctx, os.Getenv("DATABASE_URL"))
if err != nil {
return err
}
defer pool.Close()
startup, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel()
if err := pool.Ping(startup); err != nil {
return err
}
if err := db.Migrate(startup, pool); err != nil {
return err
}
addr := os.Getenv("HTTP_ADDR")
if addr == "" {
addr = ":8080"
}
objects, err := storage.FromEnv()
if err != nil {
return err
}
queries := database.New(pool)
if script := os.Getenv("ASSET_PROCESSOR_SCRIPT"); script != "" {
workerDone := make(chan struct{})
go func() { defer close(workerDone); derivatives.Run(ctx, queries, objects, script) }()
defer func() { stop(); <-workerDone }()
}
server := &http.Server{Addr: addr, Handler: httpapi.NewWithOptions(queries, pool.Ping, httpapi.Options{ChunkStreaming: chunkMode, SplatSupport: splatMode, SplatWalking: walking, SplatStreaming: streaming}, objects), ReadHeaderTimeout: 5 * time.Second}
result := make(chan error, 1)
go func() { slog.Info("API listening", "address", addr); result <- server.ListenAndServe() }()
select {
case err := <-result:
if err == http.ErrServerClosed {
return nil
}
return err
case <-ctx.Done():
shutdown, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
return server.Shutdown(shutdown)
}
}