This repository has been archived by the owner on Feb 8, 2024. It is now read-only.
/
server.go
67 lines (59 loc) · 1.63 KB
/
server.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
package backend
import (
"fmt"
"log"
"net/http"
"time"
)
// Version returns the version of Hakkero Project.
const Version = "v1.0"
// Server represents a Server.
type Server struct {
http.Server
c Config
op OpenSentencer
q *Queue
r RoomManager
}
// Welcome returns a welcome message.
func (s *Server) Welcome(w http.ResponseWriter, r *http.Request) {
s.q.mu.Lock()
defer s.q.mu.Unlock()
w.Write([]byte(
fmt.Sprintf("\"Welcome to Hakkero Project %s! You will join a %d-player room with a timeout of %d seconds.\\nThere are %d users online waiting for a room...\"", Version, s.c.PlayerLimit, int64(s.c.Timeout/time.Second), len(s.q.Players)),
))
}
func enableCORS(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
// w.Header().Set("Content-Type", "application/json; charset=utf-8")
h.ServeHTTP(w, r)
})
}
func logRequest(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
log.Printf("%s %s\n", r.Method, r.URL.String())
h.ServeHTTP(w, r)
})
}
func handlerApply(h http.Handler, funcs ...func(http.Handler) http.Handler) http.Handler {
for i := len(funcs) - 1; i >= 0; i-- {
h = funcs[i](h)
}
return h
}
// NewServer returns a new server.
func NewServer(c Config, op OpenSentencer, r RoomManager) *Server {
srv := &Server{
c: c,
op: op,
r: r,
q: NewQueue(r, c, op),
}
mux := http.NewServeMux()
srv.Handler = handlerApply(mux, logRequest, enableCORS)
mux.HandleFunc("/", srv.Welcome)
mux.Handle("/rooms/", srv.r)
mux.Handle("/queue", srv.q)
return srv
}