mirror of
https://github.com/schollz/cowyo.git
synced 2023-08-10 21:13:00 +03:00
6f445a7668
Former-commit-id: a9b40f31f0753157af8500353395274b474642a2 [formerly 57875519283c5bfbfa6d852a27d72dc091157faa] [formerly bc0dde2306cf0e189d69349f344dffda393de1cc [formerly 19aaf7bb44
]]
Former-commit-id: eb77f04e333250fef6799da788b460b77468dddf [formerly c3ddbc51302fbb8fc89410f114013b3a19f33cb8]
Former-commit-id: 814d1b257f6529e8ec45ba7acfa7269967900397
66 lines
1.1 KiB
Go
66 lines
1.1 KiB
Go
package main
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
|
|
"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)
|
|
}
|
|
|
|
if m.UpdateServer {
|
|
p := CowyoData{strings.ToLower(m.Title), m.TextData}
|
|
err := p.save()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
if m.UpdateClient {
|
|
p := CowyoData{strings.ToLower(m.Title), ""}
|
|
err := p.load()
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
m.UpdateClient = len(m.TextData) != len(p.Text)
|
|
m.TextData = p.Text
|
|
}
|
|
newMsg, err := json.Marshal(m)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
conn.WriteMessage(t, newMsg)
|
|
}
|
|
}
|