mirror of
https://github.com/schollz/cowyo.git
synced 2023-08-10 21:13:00 +03:00
9fd17f5f03
Former-commit-id: af2ba688dac0d0b970d2c5fe060c0cfbdea2aacf [formerly 3ffec2cba795a7cdc1d24993ec39de29f01e0a92] [formerly a9e84aa28cd48712673233d02a2053a7f79f84af [formerly f8268bd5b158131b56c437eddc91901670327a5b [formerly179cf911ca
]]] Former-commit-id: 996d7c30b7d1ea60ca3ea1ba5bb560464e1d12e0 [formerly 9f8c7111ba6a6b7fdb44fb511d439b9acebcf0bf] Former-commit-id: 39b5044fd6917f9f146fe0fdd431ceda8bb096cb Former-commit-id:f43b34d5ff
64 lines
1.0 KiB
Go
64 lines
1.0 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)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if m.UpdateServer {
|
|
err := p.save(m.TextData)
|
|
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)
|
|
}
|
|
}
|