forked from scribble-rs/scribble.rs
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
99 lines (82 loc) · 2.36 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
package main
import (
"flag"
"fmt"
"log"
"math/rand"
"net/http"
"os"
"os/signal"
"runtime/pprof"
"strconv"
"strings"
"syscall"
"time"
"github.com/scribble-rs/scribble.rs/api"
"github.com/scribble-rs/scribble.rs/frontend"
"github.com/scribble-rs/scribble.rs/state"
)
const defaultPort = 8080
func determinePort(portHTTPFlag int) int {
portHTTP := -1
if portHTTPFlag != -1 {
portHTTP = portHTTPFlag
log.Printf("Listening on port %d sourced from portHTTP flag.\n", portHTTP)
} else {
//Support for heroku, as heroku expects applications to use a specific port.
envPort, portVarAvailable := os.LookupEnv("PORT")
if portVarAvailable {
log.Printf("'PORT' environment variable found: '%s'\n", envPort)
parsed, parseError := strconv.ParseInt(strings.TrimSpace(envPort), 10, 32)
if parseError == nil {
portHTTP = int(parsed)
log.Printf("Listening on port %d sourced from 'PORT' environment variable\n", portHTTP)
} else {
log.Printf("Error parsing 'PORT' variable: %s\n", parseError)
log.Println("Falling back to default port.")
}
}
}
if portHTTP != -1 && portHTTP < 0 || portHTTP > 65535 {
log.Println("Port has to be between 0 and 65535.")
log.Println("Falling back to default port.")
portHTTP = -1
}
if portHTTP < 0 {
portHTTP = defaultPort
log.Printf("Listening on default port %d\n", portHTTP)
}
return portHTTP
}
var cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")
func main() {
portHTTPFlag := flag.Int("portHTTP", -1, "defines the port to be used for http mode")
flag.Parse()
if *cpuprofile != "" {
log.Println("Starting CPU profiling ....")
f, err := os.Create(*cpuprofile)
if err != nil {
log.Fatal(err)
}
pprof.StartCPUProfile(f)
}
portHTTP := determinePort(*portHTTPFlag)
//Setting the seed in order for the petnames to be random.
rand.Seed(time.Now().UnixNano())
api.SetupRoutes()
frontend.SetupRoutes()
state.LaunchCleanupRoutine()
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, syscall.SIGTERM, syscall.SIGINT)
go func() {
defer os.Exit(0)
log.Printf("Received %s, gracefully shutting down.\n", <-signalChan)
state.ShutdownLobbiesGracefully()
if *cpuprofile != "" {
pprof.StopCPUProfile()
log.Println("Finished CPU profiling.")
}
}()
log.Println("Started.")
log.Fatalln(http.ListenAndServe(fmt.Sprintf(":%d", portHTTP), nil))
}