-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
68 lines (56 loc) · 1.5 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
package main
// main.go
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"fmt"
"net/http"
"sync"
"github.com/senorbeast/atlas-backend/internal/game_room"
"github.com/senorbeast/atlas-backend/internal/web_socket"
)
var (
gameRooms = make(map[string]*game_room.GameRoom)
gameRoomsMux sync.Mutex
)
func generateRoomID() (string, error) {
const roomIDLength = 6
randomBytes := make([]byte, roomIDLength)
_, err := rand.Read(randomBytes)
if err != nil {
return "", err
}
hash := sha256.Sum256(randomBytes)
return base64.URLEncoding.EncodeToString(hash[:roomIDLength]), nil
}
func createGameRoomHandler(w http.ResponseWriter, r *http.Request) {
roomID, err := generateRoomID()
if err != nil {
http.Error(w, "Failed to generate RoomID", http.StatusInternalServerError)
return
}
gameRoom := &game_room.GameRoom{
RoomID: roomID,
PlayerData: make(map[string]*game_room.PlayerConnection),
}
gameRoomsMux.Lock()
gameRooms[roomID] = gameRoom
gameRoomsMux.Unlock()
// Start WebSocket handling for the created game room
go func() {
web_socket.HandleWebSocketConnections(gameRoom)
}()
// Respond with the game room ID to the frontend
fmt.Fprintf(w, "{\"roomId\": \"%s\"}", gameRoom.RoomID)
}
func main() {
http.HandleFunc("/create", createGameRoomHandler)
// Start the HTTP server
fmt.Println("Running atlas-backend")
fmt.Println("Visit http://localhost:8080/create")
err := http.ListenAndServe(":8080", nil)
if err != nil {
fmt.Println("Error starting HTTP server:", err)
}
}