mirror of
https://github.com/schollz/cowyo.git
synced 2023-08-10 21:13:00 +03:00
021e5d5a8e
Former-commit-id: ce50508705b9727b310059116a2c07d2154d7a80 [formerly 5a63af13359b5a8a3d963c014517c709151312cc] [formerly 0703fe06fc408947ca4d70b97cba99e02c75879f [formerly 965989530c
]]
Former-commit-id: 9575b9b87113bd6a2ff0186464671666bbac18cf [formerly f825477fd790918e8d9247e3a540da391dbc687a]
Former-commit-id: 0c1e92517cc0e5ad864135711535021b4c170f19
68 lines
1.1 KiB
Go
68 lines
1.1 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
|
|
"github.com/gorilla/websocket"
|
|
)
|
|
|
|
var wsupgrader = websocket.Upgrader{
|
|
ReadBufferSize: 1024,
|
|
WriteBufferSize: 1024,
|
|
}
|
|
|
|
func wshandler(w http.ResponseWriter, r *http.Request) {
|
|
conn, err := wsupgrader.Upgrade(w, r, nil)
|
|
if err != nil {
|
|
fmt.Println("Failed to set websocket upgrade: %+v", err)
|
|
return
|
|
}
|
|
|
|
for {
|
|
t, msg, err := conn.ReadMessage()
|
|
if err != nil {
|
|
break
|
|
}
|
|
|
|
type Message struct {
|
|
TextData string
|
|
Title string
|
|
UpdateServer bool
|
|
UpdateClient bool
|
|
}
|
|
|
|
var m Message
|
|
err = json.Unmarshal(msg, &m)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
var p CowyoData
|
|
err = p.load(m.Title)
|
|
fmt.Println("LOADED")
|
|
fmt.Println(p)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if m.UpdateServer {
|
|
err := p.save(m.TextData)
|
|
fmt.Println("SAVED")
|
|
fmt.Println(p)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
if m.UpdateClient {
|
|
m.UpdateClient = len(m.TextData) != len(p.CurrentText)
|
|
m.TextData = p.CurrentText
|
|
}
|
|
newMsg, err := json.Marshal(m)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
conn.WriteMessage(t, newMsg)
|
|
}
|
|
}
|