This repository has been archived by the owner on Jul 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
handler.go
99 lines (83 loc) · 2.18 KB
/
handler.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 api
import (
"context"
"encoding/base64"
"fmt"
"github.com/google/uuid"
pb "github.com/iguagile/iguagile-room-proto/room"
"github.com/labstack/echo/v4"
"google.golang.org/grpc"
)
var (
exceedResponse = RoomAPIResponse{
Success: false,
Error: "MaxUser exceeds the maximum value",
}
errNoServer = fmt.Errorf("server not exists")
)
func (s *RoomAPIServer) roomCreateHandler(c echo.Context) error {
request := &CreateRoomRequest{}
if err := c.Bind(request); err != nil {
return err
}
if request.MaxUser > s.MaxUser {
return c.JSON(400, exceedResponse)
}
server := s.serverManager.PickupLowLoadServer()
if server == nil {
return errNoServer
}
grpcHost := fmt.Sprintf("%v:%v", server.Host, server.APIPort)
grpcConn, err := grpc.Dial(grpcHost, grpc.WithInsecure())
if err != nil {
return err
}
defer func() { _ = grpcConn.Close() }()
roomToken := uuid.New()
grpcClient := pb.NewRoomServiceClient(grpcConn)
grpcRequest := &pb.CreateRoomRequest{
ApplicationName: request.ApplicationName,
Version: request.Version,
Password: request.Password,
MaxUser: int32(request.MaxUser),
ServerToken: server.Token,
RoomToken: roomToken[:],
Information: request.Information,
}
grpcResponse, err := grpcClient.CreateRoom(context.Background(), grpcRequest)
if err != nil {
return err
}
room := &Room{
RoomID: int(grpcResponse.Room.RoomId),
MaxUser: int(grpcResponse.Room.MaxUser),
RequirePassword: grpcResponse.Room.RequirePassword,
Server: Server{
Host: server.Host,
Port: server.Port,
},
ApplicationName: request.ApplicationName,
Version: request.Version,
Token: base64.StdEncoding.EncodeToString(roomToken[:]),
Information: request.Information,
}
res := RoomAPIResponse{
Success: true,
Result: room,
}
defer func() {
room.Token = ""
s.roomManager.Store(room)
}()
return c.JSON(201, res)
}
func (s *RoomAPIServer) roomListHandler(c echo.Context) error {
name := c.QueryParam("name")
version := c.QueryParam("version")
rooms := s.roomManager.Search(name, version)
res := RoomAPIResponse{
Success: true,
Result: rooms,
}
return c.JSON(200, res)
}