-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
521 lines (452 loc) · 13.2 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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
package main
import (
"context"
"crypto/tls"
"fmt"
"net/http"
"net/http/httputil"
"os"
"strings"
"time"
"golang.org/x/crypto/acme/autocert"
_ "github.com/joho/godotenv/autoload"
"github.com/rs/zerolog"
"github.com/rs/zerolog/log"
"github.com/urfave/cli/v2"
"github.com/dfang/qor-demo/app/account"
adminapp "github.com/dfang/qor-demo/app/admin"
"github.com/dfang/qor-demo/app/aftersale"
"github.com/dfang/qor-demo/app/api"
"github.com/dfang/qor-demo/app/home"
"github.com/dfang/qor-demo/app/orders"
"github.com/dfang/qor-demo/app/products"
"github.com/dfang/qor-demo/cmd"
"github.com/dfang/qor-demo/app/reports"
"github.com/dfang/qor-demo/app/stores"
"github.com/dfang/qor-demo/config"
"github.com/dfang/qor-demo/config/auth"
"github.com/dfang/qor-demo/config/db"
"github.com/dfang/qor-demo/config/i18n"
"github.com/dfang/qor-demo/utils/funcmapmaker"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/qor/admin"
"github.com/qor/application"
"github.com/qor/publish2"
"github.com/qor/qor"
"github.com/qor/qor/utils"
"github.com/rs/cors"
// https://github.com/qor/qor-example/issues/129
"github.com/dfang/qor-demo/config/db/migrations"
"github.com/dfang/qor-demo/config/db/seeds"
)
var version = "0.0.1" // must follow semver spec, https://github.com/motemen/gobump
var buildVersion = "development"
var (
// Router Chi Router
Router *chi.Mux
// Admin Qor Admin (后台管理页面)
Admin *admin.Admin
// Application Qor Application (前端)
Application *application.Application
// Tenant ID
TenantID string
)
func checkAvailableEnvs() {
envs := []string{
"QOR_ENV",
"DEBUG",
"HTTPS",
"DOMAIN",
"PORT",
"DBAdapter",
"DBName",
"DBPort",
"DBHost",
"DBUser",
"DBPassword",
"REDIS_HOST",
"REDIS_PORT",
"DEMO_MODE",
}
for _, e := range envs {
if os.Getenv(e) != "" {
log.Debug().Msgf("\tfound env var %s=%s", e, os.Getenv(e))
}
}
}
func setLogLevel(level int) {
var l zerolog.Level
switch level {
case -1:
l = zerolog.InfoLevel
case 0:
l = zerolog.DebugLevel
case 1:
l = zerolog.InfoLevel
case 2:
l = zerolog.WarnLevel
case 3:
l = zerolog.ErrorLevel
case 4:
l = zerolog.FatalLevel
case 5:
l = zerolog.PanicLevel
default:
l = zerolog.NoLevel
}
log.Info().Msgf("set log level to %s ......", l.String())
zerolog.SetGlobalLevel(l)
}
func initialzeConfigs() {
config.Initialize()
db.Initialize()
i18n.Initialize()
auth.Initialize()
}
func setupMiddlewaresAndRoutes() {
Router = chi.NewRouter()
Admin = admin.New(&admin.AdminConfig{
SiteName: "QOR DEMO",
Auth: auth.AdminAuth{},
DB: db.DB.Set(publish2.VisibleMode, publish2.ModeOff).Set(publish2.ScheduleMode, publish2.ModeOff),
})
Application = application.New(&application.Config{
Router: Router,
Admin: Admin,
DB: Admin.DB,
})
funcmapmaker.AddFuncMapMaker(auth.Auth.Config.Render)
// Health check for k8s pod
Router.Use(middleware.Heartbeat("/health"))
// TODO: implement Graceful shutdown
// https://medium.com/over-engineering/graceful-shutdown-with-go-http-servers-and-kubernetes-rolling-updates-6697e7db17cf
// https://github.com/qor/qor-example/commit/06835622f5feeeb90aee4f02574abbae29e40e10
Router.Use(func(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
req.Header.Del("Authorization")
handler.ServeHTTP(w, req)
})
})
Router.Use(middleware.RealIP)
Router.Use(middleware.RequestID)
Router.Use(middleware.Logger)
Router.Use(middleware.Recoverer)
Router.Use(middleware.Timeout(3 * time.Second))
// Router.Use(middleware.WithValue("k", "v"))
// Router.Use(middleware.NoCache)
// Router.Use(middleware.StripSlashes)
// Use default options
Router.Use(cors.Default().Handler)
Router.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
var (
tx = db.DB
qorContext = &qor.Context{Request: req, Writer: w}
)
if locale := utils.GetLocale(qorContext); locale != "" {
tx = tx.Set("l10n:locale", locale)
} else {
// set default locale to zh-CN
// tx = tx.Set("l10n:locale", "zh-CN")
expire := time.Now().AddDate(0, 1, 0) // one month later
cookie := http.Cookie{Name: "locale", Value: "zh-CN", Path: "/", Expires: expire, MaxAge: 90000}
http.SetCookie(w, &cookie)
}
ctx := context.WithValue(req.Context(), utils.ContextDBName, publish2.PreviewByDB(tx, qorContext))
next.ServeHTTP(w, req.WithContext(ctx))
})
})
if os.Getenv("DEBUG") == "true" {
Router.Use(func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
DumpHTTPRequest(req)
next.ServeHTTP(w, req)
})
})
}
Application.Use(aftersale.NewWithDefault())
Application.Use(api.New(&api.Config{}))
Application.Use(adminapp.New(&adminapp.Config{}))
// Application.Use(home.New(&home.Config{}))
Application.Use(account.NewWithDefault())
Application.Use(home.NewWithDefault())
Application.Use(products.NewWithDefault())
Application.Use(orders.NewWithDefault())
// Application.Use(pages.NewWithDefault())
Application.Use(stores.NewWithDefault())
Application.Use(reports.NewWithDefault())
// Application.Use(enterprise.New(&enterprise.Config{}))
// views := []string{
// "app/home/views",
// "app/account/views",
// "app/order/views",
// "app/page/views",
// "app/products/views",
// "app/views",
// }
// for _, v := range views {
// // bindatafs.AssetFS.NameSpace("views").RegisterPath(filepath.Join(config.Root, v))
// bindatafs.AssetFS.RegisterPath(filepath.Join(config.Root, v))
// }
Router.Mount("/debug", middleware.Profiler())
Router.Get("/ping", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("PONG"))
})
// fs := http.FileServer(http.Dir("public"))
// Router.Handle("/", fs)
// http.Handle("/", http.StripPrefix("/", fs))
// Router.Handle("/static/", http.StripPrefix("/static/", fs))
// Router.Handle("/static/", http.RedirectHandler("http://baidu.com", 303))
// Router.Handle("/public/", http.StripPrefix("/public/", fs))
// https://www.alexedwards.net/blog/serving-static-sites-with-go
// https://github.com/go-chi/chi/blob/master/middleware/nocache.go
// https://github.com/go-chi/chi/blob/master/middleware/profiler.go
// workDir, _ := os.Getwd()
// filesDir := filepath.Join(workDir, "public")
// FileServer(Router, "/", http.Dir(filesDir))
// 用NotFound 来替代前面的三句
// Serve public 文件夹里的 favicon.ico 等文件
// 确保 /favicon.ico 等能直接访问
// 注意 NotFound 和 pages 模块冲突,所以注释了pages
// 因为貌似开启了pages模块 永远不会执行到NotFound里来
Router.NotFound(func(w http.ResponseWriter, r *http.Request) {
// w.WriteHeader(404)
// w.Write([]byte(r.URL.Path))
// w.Write([]byte("nothing here"))
log.Debug().Msg("request path: " + r.URL.Path)
// workDir, _ := os.Getwd()
// filesDir := filepath.Join(workDir, "public")
fs := http.FileServer(http.Dir("./public"))
fs.ServeHTTP(w, r)
// http.ServeFile(w, r, "./public/favicon.ico")
})
}
// DumpHTTPRequest for debugging
func DumpHTTPRequest(r *http.Request) {
output, err := httputil.DumpRequest(r, true)
if err != nil {
fmt.Println("Error when dumping request:", err)
return
}
fmt.Println(string(output))
}
// FileServer conveniently sets up a http.FileServer handler to serve
// static files from a http.FileSystem.
// https://github.com/go-chi/chi/blob/master/_examples/fileserver/main.go
func FileServer(r chi.Router, path string, root http.FileSystem) {
if strings.ContainsAny(path, "{}*") {
panic("FileServer does not permit URL parameters.")
}
// https://stackoverflow.com/questions/27945310/why-do-i-need-to-use-http-stripprefix-to-access-my-static-files
fs := http.StripPrefix(path, http.FileServer(root))
// fmt.Println("fuck")
// fmt.Println(path)
// fmt.Println(len(path) - 1)
// fmt.Println(path[len(path)-1])
if path != "/" && path[len(path)-1] != '/' {
r.Get(path, http.RedirectHandler(path+"/", 301).ServeHTTP)
path += "/"
}
path += "*"
r.Get(path, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Debug().Msg("FALLBACK")
fmt.Println("fallback to file server")
fmt.Println(path)
fs.ServeHTTP(w, r)
}))
}
func listenAndServe() {
if os.Getenv("HTTPS") == "true" && os.Getenv("DOMAIN") == "" {
log.Info().Msg("If set HTTPS=true, this app will get ssl certificates automatically and serve on 443, so you must also set DOMAIN")
log.Info().Msg("By default (HTTPS not set), you need to config caddy as reverse proxy to serve https requests")
log.Info().Msg("If you plan to use caddy as frontend (reverse proxy), you don't need to set HTTPS, or just set to false")
os.Exit(1)
}
// fmt.Println("NOW is ", time.Now().Format("2006-01-02 15:04:05"))
elapsed := time.Since(*config.StartUpStartTime)
log.Debug().Msgf("Startup took %s\n", elapsed)
log.Info().Msgf("Listening on: %v\n", config.Config.Port)
if config.Config.HTTPS {
certManager := autocert.Manager{
Prompt: autocert.AcceptTOS,
Cache: autocert.DirCache("cert-cache"),
// Put your domain here:
HostPolicy: autocert.HostWhitelist(os.Getenv("DOMAIN")),
}
server := &http.Server{
Addr: ":443",
Handler: Router,
TLSConfig: &tls.Config{
GetCertificate: certManager.GetCertificate,
},
}
go http.ListenAndServe(fmt.Sprintf(":%d", config.Config.Port), certManager.HTTPHandler(nil))
server.ListenAndServeTLS("", "")
} else {
if err := http.ListenAndServe(fmt.Sprintf(":%d", config.Config.Port), Application.NewServeMux()); err != nil {
panic(err)
}
}
}
func runMainAction(c *cli.Context) error {
log.Info().Msg("check availables enviroments variables ......")
checkAvailableEnvs()
log.Info().Msg("initialze configurations ......")
initialzeConfigs()
log.Info().Msg("start faktory worker")
go cmd.StartFaktoryWorker()
log.Info().Msg("start gocraft/work workerPool ......")
go cmd.StartWorkerPool()
if c.Bool("ui") || os.Getenv("UI") == "true" {
log.Info().Msg("start gocraft/work web ui ......")
go cmd.StartWorkWebUI()
}
log.Info().Msg("start health check ......")
go cmd.StartHealthCheck()
log.Info().Msg("start webhookd")
go cmd.StartWebhookd()
log.Info().Msg("setup middlewares and routes ......")
setupMiddlewaresAndRoutes()
listenAndServe()
return nil
}
func printVersion() {
fmt.Printf("Version %s, BuildVersion %s\n", version, buildVersion)
}
func runMigrations() {
log.Info().Msg("just run migrations and exit ......")
migrations.Migrate()
}
func runSeeds() {
log.Info().Msg("start truncate tables ......")
seeds.TruncateTables()
log.Info().Msg("start seeding samples data for testing ......")
seeds.Run()
log.Info().Msg("seeding done, exit ......")
}
func fail(err error) {
log.Fatal().Msg(err.Error())
os.Exit(-1)
}
func main() {
log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stderr})
log.Logger = log.With().Caller().Logger()
app := &cli.App{
Name: "qox",
Usage: "make an explosive entrance",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "uuid",
Aliases: []string{"i"},
Value: "",
Usage: "Set tenant uuid",
},
&cli.BoolFlag{
Name: "migrate",
Aliases: []string{"m"},
Value: false,
Usage: "Run migrations",
},
&cli.BoolFlag{
Name: "seeds",
Aliases: []string{"s"},
Value: false,
Usage: "Run seeds",
},
&cli.BoolFlag{
Name: "compile",
Aliases: []string{"c"},
Value: false,
Usage: "Compile grool templates",
},
&cli.BoolFlag{
Name: "eval",
Value: false,
Usage: "Eval grool templates",
},
&cli.BoolFlag{
Name: "ui",
Value: false,
Usage: "Start go worker ui",
},
&cli.BoolFlag{
Name: "debug",
Value: false,
Usage: "DEBUG MODE (v=0)",
},
&cli.IntFlag{
Name: "verbose",
Aliases: []string{"v"},
Value: 1,
Usage: "Set log level",
},
&cli.BoolFlag{
Name: "version",
Aliases: []string{"V"},
Usage: "Show version",
},
},
Commands: []*cli.Command{
{
Name: "version",
Aliases: []string{"v"},
Usage: "Show version",
Action: func(c *cli.Context) error {
printVersion()
return nil
},
},
{
Name: "migrate",
Aliases: []string{"m"},
Usage: "Run migrations",
Action: func(c *cli.Context) error {
initialzeConfigs()
runMigrations()
return nil
},
},
{
Name: "seed",
Aliases: []string{"s"},
Usage: "Run seeding",
Action: func(c *cli.Context) error {
initialzeConfigs()
runSeeds()
return nil
},
},
{
Name: "start",
Aliases: []string{"s"},
Usage: "start",
Action: func(c *cli.Context) error {
if c.String("uuid") != "" {
TenantID = c.String("uuid")
log.Info().Msgf("set tenant id to %s", c.String("uuid"))
}
if c.Bool("V") {
fmt.Printf("Version %s, BuildVersion %s\n", version, buildVersion)
os.Exit(0)
}
level := c.Int("v")
setLogLevel(level)
if c.Bool("debug") {
setLogLevel(0)
}
runMainAction(c)
return nil
},
},
},
Action: func(c *cli.Context) error {
cli.ShowAppHelp(c)
return nil
},
}
err := app.Run(os.Args)
if err != nil {
log.Fatal().Msg(err.Error())
}
}