1
0
mirror of https://github.com/schollz/cowyo.git synced 2023-08-10 21:13:00 +03:00
cowyo/websockets.go
Zack Scholl b09f2b71c8 Updated
Former-commit-id: 5334654001d9d96fa995187d82bc10ccac5bd950 [formerly 11b0ac0b130ab9496e0e1e8d9977061dae775121] [formerly 2c315ca9bf979584cd9508e875e074adc2732c81 [formerly 5c75398737169774eed3a9acd12798e4dc1c71ec [formerly 40537cd672]]]
Former-commit-id: d1284ed619f11418c424951b1719a0a8ce36ca9b [formerly d140aafc13a72a5643b5fdd36cf2fb281c67d1af]
Former-commit-id: c0b1a32dfe847e64080642d0f2ed2de864f24ff4
Former-commit-id: 3da9ba3027
2016-02-10 18:37:30 -05:00

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)
}
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)
}
}