-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
91 lines (74 loc) · 2.18 KB
/
Copy pathapi.go
File metadata and controls
91 lines (74 loc) · 2.18 KB
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
package echos
import (
"encoding/json"
"net/http"
"slices"
)
type HTTPresponse map[string]string
func (e *Echos) cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
allowed := slices.Contains(allowedOrigins, origin)
if allowed {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Credentials", "true")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
}
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
func (e *Echos) CreateRoom(w http.ResponseWriter, r *http.Request) {
roomID, err := GenerateMeetRoomID(3, 3)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
}
// TODO: hande room id collisions
if _, ok := e.Rooms.Load(roomID); ok {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusConflict)
json.NewEncoder(w).Encode(HTTPresponse{
"error": "failed to create a room, try again",
})
return
}
deletech := make(chan bool, 1)
e.Rooms.Store(roomID, NewRoom(roomID, deletech))
go e.killRoomIfEmpty(roomID, deletech)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
json.NewEncoder(w).Encode(HTTPresponse{
"message": "room created successfully",
"room": roomID,
})
}
func (e *Echos) CheckRoom(w http.ResponseWriter, r *http.Request) {
roomID := r.URL.Query().Get("room")
if roomID == "" {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(HTTPresponse{
"error": "missing room id",
})
return
}
_, exists := e.Rooms.Load(roomID)
if exists {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(HTTPresponse{
"message": "room exists",
"room": roomID,
})
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusNotFound)
json.NewEncoder(w).Encode(HTTPresponse{
"error": "room not found",
})
}