1
0
mirror of https://github.com/schollz/cowyo.git synced 2023-08-10 21:13:00 +03:00
cowyo/websockets.go
Zack Scholl 3669e8809b Renaming
Former-commit-id: ab33ec4b9e7bae76ca4cc595b5f592ce270e82da [formerly ce5634e48d51105387d3e26507b7defc9054a28b] [formerly d84debd3176eb769221034f5e01aadc0ab70fc42 [formerly 6a6b53ca0a]]
Former-commit-id: baf9031e3fc929802c670c7352d6ba5b104dfeee [formerly 6c3b7c7c0e666e8fac5890e569db8a7ca9929b05]
Former-commit-id: 50d2a8dc179e0f705a21f03283cefcf0ad82f2f0
2016-02-10 09:13:21 -05:00

65 lines
1.0 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)
}
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)
}
}
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)
}
}