mirror of
https://github.com/schollz/cowyo.git
synced 2023-08-10 21:13:00 +03:00
a7066dd68c
Former-commit-id: bec2c180ee17800de01a6a082d74fd9968e2b55c [formerly bb4d29806f89b26fb1413ec2e68f48f8cb2983f7] [formerly 86c852521132a70a2e83a1e1622b7844bdba20d6 [formerly 1432660990
]]
Former-commit-id: 3e2642f169712c3c4e8d18ade497bf7c2a107ea9 [formerly 929f8679ffddd6bb609b11bec10f3dd024ea6349]
Former-commit-id: 84a0347714c097f0b5ecba0541259be456183678
69 lines
1.1 KiB
Go
69 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,
|
|
CheckOrigin: func(r *http.Request) bool {
|
|
return true
|
|
},
|
|
}
|
|
|
|
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 WikiData
|
|
err = p.load(strings.ToLower(m.Title))
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if m.UpdateServer {
|
|
err := p.save(m.TextData)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
m.TextData = "saved"
|
|
}
|
|
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)
|
|
}
|
|
}
|