Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: powerhouse
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 70 lines (63 sloc) 1.224 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
package main

import (
"io"
"json"
"log"
"os"
"reflect"
"websocket"
)

var SockHandler = websocket.Handler(SockServer)

func SockServer(ws *websocket.Conn) {
// create and send channel to muxer
ch := make(MessageChannel)
Incoming <- ch
// get id from muxer
id, ok := (<-ch).(int)
if !ok {
log.Println("got unexpected type waiting for id")
return
}
// send welcome message
go func() { ch <- Welcome{Id: id} }()
// start read/write loops
go readMessages(id, ws, ContentLayer(ch))
writeMessages(ws, ch)
}

type inMsg struct {
Update *Update
Message *Message
}

func readMessages(id int, r io.Reader, ch MessageChannel) {
dec := json.NewDecoder(r)
for {
var blob inMsg
err := dec.Decode(&blob)
if err != nil {
if err == os.EOF {
ch <- Closed{Id: id}
return
}
log.Println("decode error:", err)
continue
}
if blob.Update != nil {
blob.Update.Id = id
ch <- *blob.Update
}
if blob.Message != nil {
blob.Message.Id = id
ch <- *blob.Message
}
}
}

func writeMessages(w io.Writer, ch chan interface{}) {
enc := json.NewEncoder(w)
for m := range ch {
t := reflect.Typeof(m)
enc.Encode(map[string]interface{}{
"type": t.Name(),
"data": m,
})
}
}
Something went wrong with that request. Please try again.