summaryrefslogtreecommitdiff
path: root/back/Socket/Pool.go
diff options
context:
space:
mode:
Diffstat (limited to 'back/Socket/Pool.go')
-rw-r--r--back/Socket/Pool.go60
1 files changed, 60 insertions, 0 deletions
diff --git a/back/Socket/Pool.go b/back/Socket/Pool.go
new file mode 100644
index 0000000..f3d4687
--- /dev/null
+++ b/back/Socket/Pool.go
@@ -0,0 +1,60 @@
+package socket
+
+import (
+ "encoding/base64"
+ "crypto/rand"
+
+ "golang.org/x/net/websocket"
+)
+
+type Connection struct {
+ UUID string
+ WS *websocket.Conn
+}
+
+var connPool map[string]*Connection
+
+func generateSecureString(length int) (string, error) {
+ // Calculate required byte length to yield the requested string length after Base64 encoding
+ byteLength := (length * 3) / 4
+ if (length * 3) % 4 != 0 {
+ byteLength++
+ }
+
+ bytes := make([]byte, byteLength)
+ if _, err := rand.Read(bytes); err != nil {
+ return "", err
+ }
+
+ // Encode to string and trim to exact requested length
+ encoded := base64.URLEncoding.EncodeToString(bytes)
+ return encoded[:length], nil
+}
+
+func Init() {
+ connPool = make(map[string]*Connection)
+}
+
+
+func (self *Connection) Register() error {
+ var nameExists = true
+ var new_id string
+ for nameExists {
+ new_id, err := generateSecureString(8)
+ if err != nil {
+ return err
+ }
+ _, nameExists = connPool[new_id]
+ }
+ self.UUID = new_id
+ connPool[new_id] = self
+ return nil
+}
+
+func RemoveFromPool(name string) {
+ var _, exists = connPool[name]
+ if (!exists) {
+ return
+ }
+ delete(connPool, name)
+}