| 280 | } |
| 281 | |
| 282 | func proxyWS(w http.ResponseWriter, r *http.Request) { |
| 283 | ctx := r.Context() |
| 284 | log.Printf("Received WS/file-sync request %s: %s %s", r.Method, r.URL.Path, r.URL.RawQuery) |
| 285 | |
| 286 | // Accept websocket connection from client |
| 287 | c, err := websocket.Accept(w, r, &websocket.AcceptOptions{ |
| 288 | InsecureSkipVerify: true, |
| 289 | OriginPatterns: []string{"*"}, |
| 290 | }) |
| 291 | if err != nil { |
| 292 | log.Printf("Failed to accept connection: %v", err) |
| 293 | return |
| 294 | } |
| 295 | defer c.Close(websocket.StatusInternalError, "") |
| 296 | |
| 297 | // (def WS-URL "wss://ws.logseq.com/file-sync?graphuuid=%s") |
| 298 | remote, _, err := websocket.Dial(ctx, "wss://ws.logseq.com/file-sync?graphuuid="+r.URL.Query().Get("graphuuid"), nil) |
| 299 | if err != nil { |
| 300 | log.Printf("Failed to connect to remote server: %v", err) |
| 301 | return |
| 302 | } |
| 303 | defer remote.Close(websocket.StatusInternalError, "") |
| 304 | |
| 305 | // Bi-directional copying |
| 306 | errorCh := make(chan error, 2) |
| 307 | go func() { |
| 308 | typ, rr, err := c.Reader(ctx) |
| 309 | if err != nil { |
| 310 | errorCh <- fmt.Errorf("failed to read from client: %w", err) |
| 311 | return |
| 312 | } |
| 313 | dat, err := io.ReadAll(rr) |
| 314 | if err != nil { |
| 315 | errorCh <- fmt.Errorf("failed to read WS message body from client: %w", err) |
| 316 | return |
| 317 | } |
| 318 | log.Printf("Received WS message from client: %+v", string(dat)) |
| 319 | if err := remote.Write(ctx, typ, dat); err != nil { |
| 320 | errorCh <- fmt.Errorf("failed to write message to remote: %w", err) |
| 321 | return |
| 322 | } |
| 323 | }() |
| 324 | |
| 325 | go func() { |
| 326 | typ, rr, err := remote.Reader(ctx) |
| 327 | if err != nil { |
| 328 | errorCh <- fmt.Errorf("failed to read from backend: %w", err) |
| 329 | return |
| 330 | } |
| 331 | dat, err := io.ReadAll(rr) |
| 332 | if err != nil { |
| 333 | errorCh <- fmt.Errorf("failed to read WS message body from backend: %w", err) |
| 334 | return |
| 335 | } |
| 336 | log.Printf("Received WS message from backend: %+v", string(dat)) |
| 337 | if err := c.Write(ctx, typ, dat); err != nil { |
| 338 | errorCh <- fmt.Errorf("failed to write message to client: %w", err) |
| 339 | return |