-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathapp.go
80 lines (67 loc) · 1.87 KB
/
app.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
package main
import (
"fmt"
"log"
"net"
"os"
"sync/atomic"
"github.com/gofiber/contrib/hcaptcha"
"github.com/gofiber/fiber/v3"
"github.com/gofiber/fiber/v3/middleware/cors"
"github.com/syndtr/goleveldb/leveldb"
)
func serve(sig chan os.Signal, db *leveldb.DB) error {
app := fiber.New()
// cors
if conf[allowedURL] != "unset" {
app.Use(cors.New(cors.Config{
AllowOrigins: []string{conf[allowedURL]},
AllowHeaders: []string{"Origin", "Content-Type", "Accept"},
}))
} else {
log.Println("CORS unset")
app.Use(cors.New(cors.ConfigDefault))
}
var captcha fiber.Handler
hCaptchaEnable := conf[hCaptchaSiteKey] != "unset" && conf[hCaptchaSecretKey] != "unset"
if hCaptchaEnable {
// create hCaptcha middleware if enabled
captcha = hcaptcha.New(hcaptcha.Config{
SecretKey: conf[hCaptchaSecretKey],
})
log.Printf("hCaptcha enabled with site key %q", conf[hCaptchaSiteKey])
} else {
// empty middleware if disabled
captcha = func(c fiber.Ctx) error {
return c.Next()
}
log.Printf("hCaptcha disabled because one or both of %q and %q are unset",
confEnv[hCaptchaSiteKey][0], confEnv[hCaptchaSecretKey][0])
}
count := new(atomic.Uint64)
routeHCaptchaSiteKey(app, "/api", !hCaptchaEnable, conf[hCaptchaSiteKey])
routeRegister(app, "/api/register", db, count, captcha)
if err := routeCount(app, "/api/count", db, count); err != nil {
return err
}
// graceful shutdown
go func() {
<-sig
log.Println("shutting down")
if err := app.Shutdown(); err != nil {
fmt.Printf("cannot shutdown: %v", err)
}
}()
if conf[listen] == "unset" {
return app.Listen(conf[listenAddr])
} else {
if l, err := net.Listen("unix", conf[listen]); err != nil {
return err
} else {
if err = os.Chmod(conf[listen], 0777); err != nil {
log.Printf("cannot change ownership of socket %q: %v", conf[listen], err)
}
return app.Listener(l)
}
}
}