-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
122 lines (101 loc) · 2.57 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package main
import (
"context"
"flag"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"strings"
"time"
"github.com/itohio/collective/backend/pkg/api"
"github.com/itohio/collective/backend/pkg/auth"
"github.com/itohio/collective/backend/pkg/db"
"github.com/itohio/collective/backend/pkg/rpc"
"github.com/itohio/collective/backend/pkg/spa"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/go-chi/cors"
)
const defaultPort = "8080"
type arrayFlags []string
func (i *arrayFlags) String() string {
return strings.Join(*i, ", ")
}
func (i *arrayFlags) Set(value string) error {
*i = append(*i, value)
return nil
}
//
func main() {
migrate := flag.Bool("migrate", true, "Migrate DB")
flag.Parse()
frontendPath := os.Getenv("FRONTEND_PATH")
origins := strings.Split(os.Getenv("ALLOWED_ORIGINS"), ";")
if len(origins) == 0 {
log.Fatal("At least one origin must be provided")
return
}
db, err := db.New(*migrate)
if err != nil {
log.Fatal("Initializing database failed: ", err)
}
// if *migrate {
// log.Println("Migrations done")
// return
// }
router := chi.NewRouter()
router.Use(middleware.Logger)
router.Use(middleware.Recoverer)
cors := cors.New(cors.Options{
AllowedOrigins: origins,
AllowedMethods: []string{"POST", "OPTIONS"},
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-CSRF-Token"},
ExposedHeaders: []string{"Link"},
AllowCredentials: true,
MaxAge: 300, // Maximum value not ignored by any of major browsers
})
router.Use(cors.Handler)
router.Route("/", func(r chi.Router) {
if frontendPath != "" {
router.Mount("/", spa.New(frontendPath))
}
router.Mount("/api", api.New(db))
router.Mount("/rpc", rpc.New(db))
router.Mount("/auth", auth.New(db))
})
port := os.Getenv("PORT")
if port == "" {
port = defaultPort
}
srv := &http.Server{
Handler: router,
Addr: fmt.Sprintf(":%s", port),
// Good practice: enforce timeouts for servers you create!
WriteTimeout: 15 * time.Second,
ReadTimeout: 15 * time.Second,
}
ctx, cancel := context.WithCancel(context.Background())
go func() {
if err := srv.ListenAndServe(); err != nil {
log.Println("Failed to listen: ", err)
cancel()
}
}()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, os.Kill)
log.Println("Running")
select {
case <-c:
log.Println("Signal")
case <-ctx.Done():
log.Println("Failure")
}
ctx, cancel = context.WithTimeout(context.Background(), time.Second*15)
defer cancel()
srv.Shutdown(ctx)
log.Println("shutting down")
os.Exit(0)
}