-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
84 lines (68 loc) · 1.89 KB
/
main.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package main
import (
"fmt"
"os"
"github.com/ejagombar/SpannerBackend/config"
"github.com/ejagombar/SpannerBackend/internal/api"
"github.com/ejagombar/SpannerBackend/pkg/shutdown"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/cors"
"github.com/gofiber/fiber/v2/middleware/session"
)
// Load the configuration, create a SpannerStorage struct, and then run the server.
// This function also handls graceful shutdown and error handling.
func main() {
var exitCode int
defer func() {
os.Exit(exitCode)
}()
env, err := config.LoadConfig()
if err != nil {
fmt.Printf("error: %v", err)
exitCode = 1
return
}
cleanup, err := run(env)
defer cleanup()
if err != nil {
fmt.Printf("error: %v", err)
exitCode = 1
return
}
shutdown.Gracefully()
}
// Initialise and start the server, returning a cleanup function for graceful shutdown.
// The server is deployed on a go routine to allow the main process to listen for OS calls
func run(env config.EnvVars) (func(), error) {
app, err := buildServer(env)
if err != nil {
return nil, err
}
go func() {
fmt.Println(app.Listen("0.0.0.0:" + env.PORT))
}()
return func() {
app.Shutdown()
}, nil
}
// Sets up and configures the server by creating a Fibre app instance,
// setting up session storage using cookies, configurating CORS middleware,
// and adding the main application routes.
func buildServer(env config.EnvVars) (*fiber.App, error) {
app := fiber.New()
store := api.NewSpannerStorage(session.New(session.Config{
CookieSecure: true,
CookieHTTPOnly: true,
KeyLookup: "cookie:session_id",
}))
app.Use(cors.New(cors.Config{
AllowOrigins: "http://localhost:5173",
AllowCredentials: true,
AllowHeaders: "Origin, Content-Type, Accept",
}))
app.Get("/health", func(c *fiber.Ctx) error {
return c.SendString("Healthy!")
})
api.AddSpannerRoutes(app, env, store)
return app, nil
}