-
Notifications
You must be signed in to change notification settings - Fork 1
/
rest.go
93 lines (79 loc) · 2.39 KB
/
rest.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
package rest
import (
"context"
"errors"
"net/http"
"strconv"
"github.com/go-chi/chi"
"go.uber.org/zap"
"github.com/Icerzack/excalidraw-ws-go/internal/rest/ws"
"github.com/Icerzack/excalidraw-ws-go/internal/storage/room"
inmemRoom "github.com/Icerzack/excalidraw-ws-go/internal/storage/room/inmemory"
"github.com/Icerzack/excalidraw-ws-go/internal/storage/user"
inmemUser "github.com/Icerzack/excalidraw-ws-go/internal/storage/user/inmemory"
)
type Rest struct {
config *Config
server *http.Server
}
func NewRest(config *Config) *Rest {
return &Rest{
config: config,
}
}
func (rest *Rest) Start() {
router := chi.NewRouter()
// Define the /ping endpoint
router.Get("/ping", func(w http.ResponseWriter, _ *http.Request) {
_, err := w.Write([]byte("pong"))
if err != nil {
return
}
})
// Define the /ws endpoint
usersStorage, roomsStorage := rest.defineStorage()
wsServer := ws.NewWebSocketHandler(
usersStorage,
roomsStorage,
rest.config.JwtHeaderName,
rest.config.JwtValidationURL,
rest.config.BoardValidationURL,
rest.config.Logger,
)
router.HandleFunc("/ws", wsServer.Handle)
rest.server = &http.Server{
Addr: ":" + strconv.Itoa(rest.config.Port),
Handler: router,
ReadHeaderTimeout: 0,
}
if err := rest.server.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
rest.config.Logger.Error("server error", zap.Error(err))
return
}
}
func (rest *Rest) Stop() {
if err := rest.server.Shutdown(context.Background()); err != nil {
rest.config.Logger.Error("server error", zap.Error(err))
}
}
func (rest *Rest) defineStorage() (*inmemUser.Storage, *inmemRoom.Storage) {
var usersStorage *inmemUser.Storage
var roomsStorage *inmemRoom.Storage
switch rest.config.UsersStorageType {
case user.InMemoryStorageType:
rest.config.Logger.Info("Using in-memory storage for users")
usersStorage = inmemUser.NewStorage(rest.config.Logger)
default:
rest.config.Logger.Info("Using in-memory storage for users")
usersStorage = inmemUser.NewStorage(rest.config.Logger)
}
switch rest.config.RoomsStorageType {
case room.InMemoryStorageType:
rest.config.Logger.Info("Using in-memory storage for rooms")
roomsStorage = inmemRoom.NewStorage(rest.config.Logger)
default:
rest.config.Logger.Info("Using in-memory storage for rooms")
roomsStorage = inmemRoom.NewStorage(rest.config.Logger)
}
return usersStorage, roomsStorage
}