2016-02-07 16:45:42 +03:00
|
|
|
package main
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
2016-02-08 04:37:46 +03:00
|
|
|
"strings"
|
2016-02-07 16:45:42 +03:00
|
|
|
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
)
|
|
|
|
|
|
|
|
var wsupgrader = websocket.Upgrader{
|
|
|
|
ReadBufferSize: 1024,
|
|
|
|
WriteBufferSize: 1024,
|
|
|
|
}
|
|
|
|
|
|
|
|
func wshandler(w http.ResponseWriter, r *http.Request) {
|
2016-12-13 06:55:36 +03:00
|
|
|
w.Header().Set("Access-Control-Allow-Origin", "*")
|
2016-02-07 16:45:42 +03:00
|
|
|
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)
|
|
|
|
}
|
|
|
|
|
2016-02-10 17:13:21 +03:00
|
|
|
var p WikiData
|
2016-02-08 04:37:46 +03:00
|
|
|
err = p.load(strings.ToLower(m.Title))
|
2016-02-08 02:31:47 +03:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2016-02-07 16:45:42 +03:00
|
|
|
if m.UpdateServer {
|
2016-02-08 02:31:47 +03:00
|
|
|
err := p.save(m.TextData)
|
2016-02-07 16:45:42 +03:00
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2016-02-11 02:37:30 +03:00
|
|
|
m.TextData = "saved"
|
2016-02-07 16:45:42 +03:00
|
|
|
}
|
|
|
|
if m.UpdateClient {
|
2016-02-08 02:31:47 +03:00
|
|
|
m.UpdateClient = len(m.TextData) != len(p.CurrentText)
|
|
|
|
m.TextData = p.CurrentText
|
2016-02-07 16:45:42 +03:00
|
|
|
}
|
|
|
|
newMsg, err := json.Marshal(m)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
conn.WriteMessage(t, newMsg)
|
|
|
|
}
|
|
|
|
}
|