-
Notifications
You must be signed in to change notification settings - Fork 2k
/
Copy pathmain.go
82 lines (69 loc) · 1.68 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
package main
import (
"fasthttp/app/handlers"
"flag"
"runtime"
"github.com/savsgio/gotils/strconv"
"github.com/valyala/fasthttp"
fastprefork "github.com/valyala/fasthttp/prefork"
)
var (
bindHost string
prefork bool
)
func init() {
flag.StringVar(&bindHost, "bind", ":8080", "set bind host")
flag.BoolVar(&prefork, "prefork", false, "use prefork")
flag.Parse()
}
func main() {
isNotPreforkOrIsChild := !prefork || fastprefork.IsChild()
handler := func(ctx *fasthttp.RequestCtx) {}
if isNotPreforkOrIsChild {
maxConn := runtime.NumCPU() * 4
if fastprefork.IsChild() {
maxConn = 5
}
// init database
if err := handlers.InitDB(maxConn); err != nil {
panic(err)
}
defer handlers.CloseDB()
// init and populate worlds cache
handlers.PopulateWorldsCache()
// init handler
handler = func(ctx *fasthttp.RequestCtx) {
switch strconv.B2S(ctx.Request.URI().Path()) {
case "/json":
handlers.JSON(ctx)
case "/db":
handlers.DB(ctx)
case "/queries":
handlers.Queries(ctx)
case "/cached-worlds":
handlers.CachedWorlds(ctx)
case "/fortunes":
handlers.FortunesQuick(ctx)
case "/updates":
handlers.Updates(ctx)
case "/plaintext":
handlers.Plaintext(ctx)
default:
ctx.Error(fasthttp.StatusMessage(fasthttp.StatusNotFound), fasthttp.StatusNotFound)
}
}
}
// init fasthttp server
server := &fasthttp.Server{
Name: "Go",
Handler: handler,
DisableHeaderNamesNormalizing: true,
}
listenAndServe := server.ListenAndServe
if prefork {
listenAndServe = fastprefork.New(server).ListenAndServe
}
if err := listenAndServe(bindHost); err != nil {
panic(err)
}
}