-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
159 lines (134 loc) · 2.92 KB
/
main.go
File metadata and controls
159 lines (134 loc) · 2.92 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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
package main
import (
"encoding/json"
"fmt"
"net/http"
"os"
"sync"
"github.com/go-redis/redis/v8"
"github.com/gorilla/websocket"
)
type Edit struct {
Position int `json:"position"`
Length int `json:"length"`
Text string `json:"text"`
Type string `json:"type"`
ClientID string `json:"clientId"`
}
var (
text string
mu sync.Mutex
rdb *redis.Client
)
func init() {
redisAddr := os.Getenv("REDIS_ADDR")
if redisAddr == "" {
redisAddr = "localhost:6379"
}
rdb = redis.NewClient(&redis.Options{
Addr: redisAddr,
})
}
func applyEdit(text *string, edit Edit) error {
if edit.Position < 0 || edit.Position > len(*text) {
return fmt.Errorf("invalid position")
}
switch edit.Type {
case "insert":
*text = (*text)[:edit.Position] + edit.Text + (*text)[edit.Position:]
case "delete":
if edit.Position+edit.Length > len(*text) {
return fmt.Errorf("invalid length")
}
*text = (*text)[:edit.Position] + (*text)[edit.Position+edit.Length:]
default:
return fmt.Errorf("unknown edit type")
}
return nil
}
func publishDelta(edit Edit) error {
data, err := json.Marshal(edit)
if err != nil {
return err
}
broadcastToClients(data)
return nil
}
var clients = make(map[*websocket.Conn]bool)
var clientsMu sync.Mutex
func addClient(conn *websocket.Conn) {
clientsMu.Lock()
defer clientsMu.Unlock()
clients[conn] = true
}
func removeClient(conn *websocket.Conn) {
clientsMu.Lock()
defer clientsMu.Unlock()
delete(clients, conn)
}
func broadcastToClients(message []byte) {
clientsMu.Lock()
defer clientsMu.Unlock()
for client := range clients {
err := client.WriteMessage(websocket.TextMessage, message)
if err != nil {
client.Close()
delete(clients, client)
}
}
}
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func wsHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
return
}
defer conn.Close()
addClient(conn)
for {
_, _, err := conn.ReadMessage()
if err != nil {
break
}
}
removeClient(conn)
}
func handleEdit(w http.ResponseWriter, r *http.Request) {
var edit Edit
err := json.NewDecoder(r.Body).Decode(&edit)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
mu.Lock()
defer mu.Unlock()
err = applyEdit(&text, edit)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = publishDelta(edit)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write([]byte(text))
}
func handleGetText(w http.ResponseWriter, r *http.Request) {
mu.Lock()
defer mu.Unlock()
w.Write([]byte(text))
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
http.ServeFile(w, r, "index.html")
})
http.HandleFunc("/edit", handleEdit)
http.HandleFunc("/text", handleGetText)
http.HandleFunc("/ws", wsHandler)
http.ListenAndServe(":8080", nil)
}