-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
268 lines (220 loc) · 6.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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package main
import (
"context"
"embed"
"errors"
"fmt"
"net"
"net/http"
"os"
"os/signal"
"strings"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/basicauth"
"github.com/gofiber/fiber/v2/middleware/csrf"
"github.com/gofiber/fiber/v2/middleware/filesystem"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/utils"
"github.com/gofiber/template/html"
"github.com/joho/godotenv"
"github.com/spf13/cobra"
"gopkg.in/gomail.v2"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
func init() {
if err := godotenv.Load(); err != nil {
panic("can't load .env: " + err.Error())
}
}
type App struct {
server *fiber.App
db *gorm.DB
mailer gomail.SendCloser
log *Logger
disk Disk
config *Config
}
func (a *App) Init(config *Config, log *Logger) error {
//db, err := gorm.Open(mysql.Open(config.DatabaseURL), &gorm.Config{})
db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
if err != nil {
return fmt.Errorf("can't open database: %w", err)
}
log.Infof("Connected to database: %s", config.DatabaseURL)
if err := db.AutoMigrate(&Participant{}); err != nil {
return fmt.Errorf("can't apply migrations to database: %w", err)
}
log.Info("Migrations applied")
// m, err := gomail.NewDialer(config.SMTP.Host, config.SMTP.Port, config.SMTP.User, config.SMTP.Password).Dial()
// if err != nil {
// return fmt.Errorf("can't authenticate to an SMTP server: %w", err)
// }
// log.Infof("Authenticated to SMTP server: %s:%d", config.SMTP.Host, config.SMTP.Port)
disk, err := NewOsDisk(config.DiskPath)
if err != nil {
return fmt.Errorf("can't init disk at '%s': %w", config.DiskPath, err)
}
log.Infof("Disk initialized at: %s", disk.Path)
server := fiber.New(fiber.Config{
Views: html.New("./views", ".html"),
ViewsLayout: "main",
ServerHeader: "Content-Security-Policy",
})
a.server = server
a.db = db
//a.mailer = m
a.log = log
a.disk = disk
a.config = config
a.registerRoutes()
return nil
}
func (a *App) Run() {
if a.config.HTTPAddressUnix != "" {
ln, err := net.Listen("unix", a.config.HTTPAddressUnix)
if err != nil {
a.log.Fatal("Listen error: ", err)
}
a.server.Listener(ln)
} else if a.config.HTTPAddress != "" {
a.server.Listen(a.config.HTTPAddress)
} else {
a.server.Listen(":" + os.Getenv("PORT"))
}
}
func (a *App) Shutdown(_ context.Context) error {
e := make([]string, 0)
if err := a.server.Shutdown(); err != nil {
e = append(e, fmt.Errorf("can't shutdown server: %w", err).Error())
}
db, err := a.db.DB()
if err != nil {
e = append(e, fmt.Errorf("can't receive an underling sql.DB instance: %w", err).Error())
}
if err := db.Close(); err != nil {
e = append(e, fmt.Errorf("can't close database connection: %w", err).Error())
}
if err := a.mailer.Close(); err != nil {
e = append(e, fmt.Errorf("can't close connection to an SMTP server").Error())
}
if len(e) > 0 {
return errors.New(strings.Join(e, "/n"))
}
return nil
}
//go:embed assets/*
var AssetsFS embed.FS
func (a *App) registerRoutes() {
s := a.server
s.Use(logger.New()) // NewLoggerMiddleware(Config{Logger: a.log.Desugar(), Next: nil}),
s.Use("/a", filesystem.New(filesystem.Config{
Root: http.FS(AssetsFS),
PathPrefix: "assets",
Browse: true,
}))
// s.Static("/a", "./assets")
s.Use(
func(c *fiber.Ctx) error {
c.Bind(fiber.Map{
"Links": links([]string{"Programme Overview", "Keynote Speakers", "Registration and submission", "Requirements", "General information", "Open upload"}),
})
c.Set("X-Content-Type-Options", "nosniff")
c.Set("Content-Security-Policy", "default-src 'self' /a/css/tailwind.css /a/css/app.css; frame-ancestors 'self'")
c.Set("Strict-Transport-Security", "max-age=86400")
c.Set("X-XSS-Protection", "1; mode=block")
return c.Next()
},
csrf.New(csrf.Config{
KeyLookup: "header:X-Csrf-Token",
CookieName: "csrf",
CookieSameSite: "Lax",
Expiration: 1 * time.Hour,
KeyGenerator: utils.UUID,
CookieHTTPOnly: true,
}),
)
s.Get("/", a.mainView)
s.Get("/programme-overview", a.programOverviewView)
s.Get("/keynote-speakers", a.keynoteSpeakersView)
s.Get("/requirements", a.requirementsView)
s.Get("/general-information", a.generalInfoView)
s.Get("/registration-and-submission", a.registrationView)
s.Post("/registration-and-submission", a.registerNewParticipant)
s.Get("/upload/:type", a.uploadView)
s.Post("/upload/:type", a.uploadFile)
s.Get("/open-upload", a.openUploadView)
s.Post("/open-upload", a.openUpload)
admin := s.Group("/admin",
basicauth.New(
basicauth.Config{
Users: map[string]string{
"admin": a.config.AdminPassword,
},
},
),
func(c *fiber.Ctx) error {
c.Bind(fiber.Map{
"Title": "Admin",
})
return c.Next()
},
)
admin.Get("/", a.adminView)
admin.Post("/mailing", a.sendNewsletter)
admin.Get("/download/:file", a.downloadFiles)
s.Use(a.notFoundView)
}
func main() {
logger := new(Logger)
config := new(Config)
serveCmd := &cobra.Command{
Use: "serve",
PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
if err := logger.Init(); err != nil {
return fmt.Errorf("error in serve init app: %w", err)
}
if err := config.LoadEnv(); err != nil {
return fmt.Errorf("error in load env serve: %w", err)
}
fmt.Println(config)
return nil
},
RunE: func(cmd *cobra.Command, args []string) error {
app := new(App)
if err := app.Init(config, logger); err != nil {
return fmt.Errorf("init app: %w", err)
}
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
// Todo: wait for gorutine to see the output
go func() {
<-stop
logger.Info("Received an interrupt signal, shutdown")
// ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
// defer cancel()
if err := app.Shutdown(context.TODO()); err != nil {
// Do recovery???
logger.Errorf("Application shutdown failed: %v", err.Error())
}
logger.Info("Seccessfully stoped application")
}()
app.Run()
return nil
},
}
serveCmd.Flags().StringVar(&config.HTTPAddressUnix, "unix", "", "")
serveCmd.Flags().StringVar(&config.HTTPAddress, "http", "", "")
serveCmd.MarkFlagsMutuallyExclusive("unix", "http")
command := &cobra.Command{
Use: "amtc",
Version: "0.0.0",
}
command.PersistentFlags().StringVar(&config.DatabaseURL, "db-url", "", "")
command.PersistentFlags().StringVar(&config.DiskPath, "disk-path", "", "")
command.MarkPersistentFlagRequired("db-url")
command.MarkPersistentFlagRequired("disk-path")
command.AddCommand(serveCmd)
command.Execute()
}