1
0
mirror of https://github.com/schollz/cowyo.git synced 2023-08-10 21:13:00 +03:00
cowyo/websockets.go
Zack Scholl d1c4a0b1f3 Major additions. Only updates if has changes
Former-commit-id: 3e0a208c0264f303cefaaa1ff38dcabc2de368a7 [formerly 404c1e940d33da42a5b8178fe769227e3b2c7f70] [formerly 179ebb2430889ecf0d2d6f48c647ff3391030983 [formerly a6d89e5585]]
Former-commit-id: d8e2f5594b62ab4f1f0a64688d808258bf08ebf4 [formerly a850ea2f7ececc9ac74b1eebcf06e3a4a520828a]
Former-commit-id: 607f80005f5126ea4012e99bd15fdd312525607c
2016-02-07 08:45:42 -05:00

66 lines
1.1 KiB
Go
Executable File

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