-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
199 lines (169 loc) · 4.09 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
package main
import (
"context"
"database/sql"
"flag"
"log"
"math/rand"
"net/http"
"os"
"os/signal"
"strings"
"time"
"github.com/jdaiv/px-server/rpg"
"github.com/BurntSushi/toml"
middleware "github.com/gorilla/handlers"
"github.com/gorilla/mux"
_ "github.com/lib/pq"
)
var JWTSecret []byte
var DB *sql.DB
type Config struct {
Addr string
DBConnStr string
JWTSecret string
}
var configLocation = flag.String("config", "config.toml", "location of config file")
var resLocation = flag.String("res", "resources", "location of static resources")
var game *rpg.RPG
func main() {
flag.Parse()
config := Config{}
if _, err := toml.DecodeFile(*configLocation, &config); err != nil {
log.Printf("[server] error parsing config: %v", err)
os.Exit(1)
}
JWTSecret = []byte(config.JWTSecret)
rand.Seed(time.Now().UTC().UnixNano())
r := mux.NewRouter()
r.Use(middleware.RecoveryHandler())
r.Use(middleware.CORS())
r.HandleFunc("/api/ws", join).Methods("GET")
r.HandleFunc("/api/auth/login", login).Methods("POST")
r.HandleFunc("/api/auth/create", createUser).Methods("POST")
var err error
DB, err = sql.Open("postgres", config.DBConnStr)
if err != nil {
log.Fatal(err)
}
log.Println("[server] connected to DB")
resPath := *resLocation
if !strings.HasSuffix(resPath, "/") {
resPath += "/"
}
game, err = rpg.NewRPG(resPath, DB)
if err != nil {
log.Fatal(err)
}
log.Println("[server] made game")
go ClientMaintenace()
go incomingMessages()
go outgoingMessages()
go game.HandleMessages()
go func() {
for {
outgoing := <-game.Outgoing
zone, ok := game.Zones.Get(outgoing.Zone)
if !ok {
continue
}
switch outgoing.Type {
case rpg.ACTION_UPDATE:
game.BuildDisplayData(zone)
clientsMutex.Lock()
for id := range zone.Players {
authenticatedClients[id].Write(WSResponse{
Error: 0,
Action: ACTION_GAME_STATE,
Data: game.BuildDisplayFor(id),
})
}
clientsMutex.Unlock()
case rpg.ACTION_CHAT:
message, ok := outgoing.Params["message"]
if !ok {
continue
}
messageStr, ok := message.(string)
if !ok {
continue
}
if outgoing.PlayerId >= 0 {
client, ok := authenticatedClients[outgoing.PlayerId]
if !ok {
continue
}
client.Write(WSResponse{
Error: 0,
Action: ACTION_CHAT_MESSAGE,
Data: messageSend{
Content: messageStr,
From: "server",
Class: MESSAGE_CLASS_SERVER,
},
})
} else {
clientsMutex.Lock()
for id := range zone.Players {
authenticatedClients[id].Write(WSResponse{
Error: 0,
Action: ACTION_CHAT_MESSAGE,
Data: messageSend{
Content: messageStr,
From: "server",
Class: MESSAGE_CLASS_SERVER,
},
})
}
clientsMutex.Unlock()
}
default:
clientsMutex.Lock()
for id := range zone.Players {
authenticatedClients[id].Write(WSResponse{
Error: 0,
Action: ActionStr(outgoing.Type),
Data: outgoing.Params,
})
}
clientsMutex.Unlock()
}
}
}()
go func() {
for {
game.Incoming <- rpg.IncomingMessage{
Data: rpg.IncomingMessageData{Type: rpg.ACTION_TICK},
}
time.Sleep(125 * time.Millisecond)
}
}()
srv := &http.Server{
Addr: config.Addr,
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: r,
}
log.Printf("[server] starting on %s", config.Addr)
go func() {
if err := srv.ListenAndServe(); err != nil {
log.Println(err)
}
}()
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
<-c
game.SaveAll()
// Create a deadline to wait for.
ctx, cancel := context.WithTimeout(context.Background(), time.Second*2)
defer cancel()
// Doesn't block if no connections, but will otherwise wait
// until the timeout deadline.
srv.Shutdown(ctx)
// Optionally, you could run srv.Shutdown in a goroutine and block on
// <-ctx.Done() if your application should wait for other services
// to finalize based on context cancellation.
log.Println("[server] shutting down")
os.Exit(0)
}