-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
69 lines (63 loc) · 1.4 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
package main
import (
"context"
"github.com/Tnze/go-mc/net"
"github.com/shiena/ansicolor"
log "github.com/sirupsen/logrus"
"github.com/spf13/viper"
"os"
"os/signal"
"sync"
)
const UnitedServerVersion = "UnitedServer Alpha"
const ProtocolVersion = 578
func main() {
parseConf()
if viper.GetBool("DebugMode") {
log.SetLevel(log.DebugLevel)
log.SetFormatter(&log.TextFormatter{ForceColors: true})
log.SetOutput(ansicolor.NewAnsiColorWriter(os.Stdout))
log.Warn("Starting in debug mode")
}
l, err := net.ListenMC(viper.GetString("ListenAddr"))
if err != nil {
log.WithError(err).Fatal("Start listening fail")
}
ctx, cancel := context.WithCancel(context.Background())
go gracefulShutdown(func() {
cancel()
if err := l.Close(); err != nil {
log.WithError(err).Error("Close listener error")
}
})
var wg sync.WaitGroup
for {
conn, err := l.Accept()
if err != nil {
if ctx.Err() == nil {
log.WithError(err).Error("Accept connection error")
}
break
}
wg.Add(1)
go func() {
handleConn(ctx, &conn)
wg.Done()
}()
}
wg.Wait() // wait for all connection close
}
func gracefulShutdown(shutdown func()) {
sig := make(chan os.Signal)
signal.Notify(sig, os.Interrupt)
for i := 0; i < 4; i++ {
<-sig
if i == 0 {
log.Warn("Server is stopping, please wait.")
shutdown()
} else {
log.Warnf("Press %d times more to force stop this server", 4-i)
}
}
os.Exit(2)
}