wide/util/websocket.go

74 lines
1.9 KiB
Go
Raw Normal View History

2015-01-18 08:59:10 +03:00
// Copyright (c) 2014-2015, b3log.org
2014-11-19 19:17:59 +03:00
//
2014-11-12 18:13:14 +03:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
2014-11-19 19:17:59 +03:00
//
2014-11-12 18:13:14 +03:00
// http://www.apache.org/licenses/LICENSE-2.0
2014-11-19 19:17:59 +03:00
//
2014-11-12 18:13:14 +03:00
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2014-09-16 11:06:52 +04:00
package util
import (
2014-11-20 08:59:08 +03:00
"errors"
2014-09-16 11:06:52 +04:00
"net/http"
"time"
"github.com/gorilla/websocket"
)
2014-12-07 06:42:34 +03:00
// WSChannel represents a WebSocket channel.
2014-09-16 11:06:52 +04:00
type WSChannel struct {
2014-10-29 13:15:18 +03:00
Sid string // wide session id
Conn *websocket.Conn // websocket connection
Request *http.Request // HTTP request related
Time time.Time // the latest use time
2014-09-16 11:06:52 +04:00
}
2014-09-20 06:39:29 +04:00
2014-11-20 08:59:08 +03:00
// WriteJSON writes the JSON encoding of v to the channel.
func (c *WSChannel) WriteJSON(v interface{}) (ret error) {
if nil == c.Conn {
return errors.New("connection is nil, channel has been closed")
}
defer func() {
if r := recover(); nil != r {
ret = errors.New("channel has been closed")
}
}()
return c.Conn.WriteJSON(v)
}
2014-11-20 09:11:54 +03:00
// ReadJSON reads the next JSON-encoded message from the channel and stores it in the value pointed to by v.
func (c *WSChannel) ReadJSON(v interface{}) (ret error) {
if nil == c.Conn {
return errors.New("connection is nil, channel has been closed")
}
defer func() {
if r := recover(); nil != r {
ret = errors.New("channel has been closed")
}
}()
return c.Conn.ReadJSON(v)
}
2014-10-29 13:15:18 +03:00
// Close closed the channel.
2014-09-20 06:39:29 +04:00
func (c *WSChannel) Close() {
2014-11-19 19:17:59 +03:00
if nil != c.Conn {
c.Conn.Close()
}
2014-09-20 06:39:29 +04:00
}
2014-10-28 19:04:46 +03:00
2014-10-29 13:15:18 +03:00
// Refresh refreshes the channel by updating its use time.
2014-10-28 19:04:46 +03:00
func (c *WSChannel) Refresh() {
c.Time = time.Now()
}