This repository has no description
0

Configure Feed

Select the types of activity you want to include in your feed.

core / spindle / mill / proto / ws.go
1.1 kB 58 lines
1package millproto 2 3import ( 4 "io" 5 "sync" 6 7 "github.com/gorilla/websocket" 8) 9 10// adapts a gorilla websocket connection to an io.ReadWriteCloser so the 11// length-prefixed fleet framing rides over it. each Encode produces exactly one 12// binary frame. the reader reassembles the byte stream across frames 13type WSStream struct { 14 conn *websocket.Conn 15 16 rmu sync.Mutex 17 r io.Reader // current message reader, advanced as frames are consumed 18 19 wmu sync.Mutex 20} 21 22func NewWSStream(conn *websocket.Conn) *WSStream { 23 return &WSStream{conn: conn} 24} 25 26func (s *WSStream) Read(p []byte) (int, error) { 27 s.rmu.Lock() 28 defer s.rmu.Unlock() 29 for { 30 if s.r == nil { 31 _, r, err := s.conn.NextReader() 32 if err != nil { 33 return 0, err 34 } 35 s.r = r 36 } 37 n, err := s.r.Read(p) 38 if err == io.EOF { 39 s.r = nil 40 if n > 0 { 41 return n, nil 42 } 43 continue 44 } 45 return n, err 46 } 47} 48 49func (s *WSStream) Write(p []byte) (int, error) { 50 s.wmu.Lock() 51 defer s.wmu.Unlock() 52 if err := s.conn.WriteMessage(websocket.BinaryMessage, p); err != nil { 53 return 0, err 54 } 55 return len(p), nil 56} 57 58func (s *WSStream) Close() error { return s.conn.Close() }