There is no reason to export these functions.

This commit is contained in:
claudemiro
2015-01-31 09:13:24 -03:00
parent e9bdc0859e
commit a3465f332e
12 changed files with 79 additions and 79 deletions
+1 -1
View File
@@ -45,7 +45,7 @@ func prepareQueryString(params url.Values) string {
// * The request path (e.g. /some/resource) // * The request path (e.g. /some/resource)
// * The query parameters sorted by key, with keys converted to lowercase, then joined as in the query string. // * The query parameters sorted by key, with keys converted to lowercase, then joined as in the query string.
// Note that the string must not be url escaped (e.g. given the keys auth_key: foo, Name: Something else, you get auth_key=foo&name=Something else) // Note that the string must not be url escaped (e.g. given the keys auth_key: foo, Name: Something else, you get auth_key=foo&name=Something else)
func RestAuthenticationHandler(h http.Handler) http.Handler { func restAuthenticationHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r) vars := mux.Vars(r)
appID := vars["app_id"] appID := vars["app_id"]
+7 -7
View File
@@ -71,7 +71,7 @@ func (c *Channel) Subscribe(a *App, conn *Connection, channelData string) error
c.Lock() c.Lock()
defer c.Unlock() defer c.Unlock()
subscription := NewSubscription(conn, channelData) subscription := newSubscription(conn, channelData)
c.Subscriptions[conn.SocketID] = subscription c.Subscriptions[conn.SocketID] = subscription
if c.IsPresence() { if c.IsPresence() {
@@ -106,7 +106,7 @@ func (c *Channel) Subscribe(a *App, conn *Connection, channelData string) error
// pusher_internal:subscription_succeeded // pusher_internal:subscription_succeeded
data := make(map[string]SubscriptionSucceeedEventPresenceData) data := make(map[string]SubscriptionSucceeedEventPresenceData)
data["presence"] = NewSubscriptionSucceedEventPresenceData(c) data["presence"] = newSubscriptionSucceedEventPresenceData(c)
js, err = json.Marshal(data) js, err = json.Marshal(data)
@@ -115,9 +115,9 @@ func (c *Channel) Subscribe(a *App, conn *Connection, channelData string) error
return err return err
} }
conn.Publish(NewSubscriptionSucceededEvent(c.ChannelID, string(js))) conn.Publish(newSubscriptionSucceededEvent(c.ChannelID, string(js)))
} else { } else {
conn.Publish(NewSubscriptionSucceededEvent(c.ChannelID, "{}")) conn.Publish(newSubscriptionSucceededEvent(c.ChannelID, "{}"))
} }
// WebHook // WebHook
@@ -179,7 +179,7 @@ func NewChannel(channelID string) *Channel {
func (c *Channel) PublishMemberAddedEvent(a *App, data string, subscription *Subscription) { func (c *Channel) PublishMemberAddedEvent(a *App, data string, subscription *Subscription) {
for _, subs := range c.Subscriptions { for _, subs := range c.Subscriptions {
if subs != subscription { if subs != subscription {
subs.Connection.Publish(NewMemberAddedEvent(c.ChannelID, data)) subs.Connection.Publish(newMemberAddedEvent(c.ChannelID, data))
} }
} }
} }
@@ -188,7 +188,7 @@ func (c *Channel) PublishMemberAddedEvent(a *App, data string, subscription *Sub
func (c *Channel) PublishMemberRemovedEvent(a *App, subscription *Subscription) { func (c *Channel) PublishMemberRemovedEvent(a *App, subscription *Subscription) {
for _, subs := range c.Subscriptions { for _, subs := range c.Subscriptions {
if subs != subscription { if subs != subscription {
subs.Connection.Publish(NewMemberRemovedEvent(c.ChannelID, subscription)) subs.Connection.Publish(newMemberRemovedEvent(c.ChannelID, subscription))
} }
} }
} }
@@ -211,7 +211,7 @@ func (c *Channel) Publish(a *App, event RawEvent, ignore string) error {
for _, subs := range c.Subscriptions { for _, subs := range c.Subscriptions {
if subs.Connection.SocketID != ignore { if subs.Connection.SocketID != ignore {
subs.Connection.Publish(NewResponseEvent(event.Event, event.Channel, v)) subs.Connection.Publish(newResponseEvent(event.Event, event.Channel, v))
} else { } else {
// Webhook // Webhook
if strings.HasPrefix(event.Event, "client-") { if strings.HasPrefix(event.Event, "client-") {
+1 -1
View File
@@ -16,7 +16,7 @@ type Connection struct {
} }
// Create a new Subscriber // Create a new Subscriber
func NewConnection(socketID string, s *websocket.Conn) *Connection { func newConnection(socketID string, s *websocket.Conn) *Connection {
log.Infof("Creating a new Subscriber %+v", socketID) log.Infof("Creating a new Subscriber %+v", socketID)
return &Connection{SocketID: socketID, Socket: s} return &Connection{SocketID: socketID, Socket: s}
+8 -8
View File
@@ -29,7 +29,7 @@ type UnsupportedProtocolVersionError struct {
BaseWebsocketError BaseWebsocketError
} }
func NewUnsupportedProtocolVersionError() UnsupportedProtocolVersionError { func newUnsupportedProtocolVersionError() UnsupportedProtocolVersionError {
return UnsupportedProtocolVersionError{ return UnsupportedProtocolVersionError{
BaseWebsocketError{Code: UNSUPPORTED_PROTOCOL_VERSION, Msg: "Unsupported protocol version"}, BaseWebsocketError{Code: UNSUPPORTED_PROTOCOL_VERSION, Msg: "Unsupported protocol version"},
} }
@@ -41,7 +41,7 @@ type ApplicationDoesNotExistsError struct {
BaseWebsocketError BaseWebsocketError
} }
func NewApplicationDoesNotExistsError() ApplicationDoesNotExistsError { func newApplicationDoesNotExistsError() ApplicationDoesNotExistsError {
return ApplicationDoesNotExistsError{ return ApplicationDoesNotExistsError{
BaseWebsocketError{Code: APPLICATION_DOES_NOT_EXISTS, Msg: "Could not found an app with the given key"}, BaseWebsocketError{Code: APPLICATION_DOES_NOT_EXISTS, Msg: "Could not found an app with the given key"},
} }
@@ -52,7 +52,7 @@ type NoProtocolVersionSuppliedError struct {
BaseWebsocketError BaseWebsocketError
} }
func NewNoProtocolVersionSuppliedError() NoProtocolVersionSuppliedError { func newNoProtocolVersionSuppliedError() NoProtocolVersionSuppliedError {
return NoProtocolVersionSuppliedError{ return NoProtocolVersionSuppliedError{
BaseWebsocketError{Code: NO_PROTOCOL_VERSION_SUPPLIED, Msg: "No protocol version supplied"}, BaseWebsocketError{Code: NO_PROTOCOL_VERSION_SUPPLIED, Msg: "No protocol version supplied"},
} }
@@ -64,7 +64,7 @@ type ApplicationDisabledError struct {
BaseWebsocketError BaseWebsocketError
} }
func NewApplicationDisabledError() NoProtocolVersionSuppliedError { func newApplicationDisabledError() NoProtocolVersionSuppliedError {
return NoProtocolVersionSuppliedError{ return NoProtocolVersionSuppliedError{
BaseWebsocketError{Code: APPLICATION_DISABLED, Msg: "Application disabled"}, BaseWebsocketError{Code: APPLICATION_DISABLED, Msg: "Application disabled"},
} }
@@ -75,7 +75,7 @@ type ApplicationOnlyAccepsSSLError struct {
BaseWebsocketError BaseWebsocketError
} }
func NewApplicationOnlyAccepsSSLError() ApplicationOnlyAccepsSSLError { func newApplicationOnlyAccepsSSLError() ApplicationOnlyAccepsSSLError {
return ApplicationOnlyAccepsSSLError{ return ApplicationOnlyAccepsSSLError{
BaseWebsocketError{Code: APPLICATION_ONLY_ACCEPTS_SSL, Msg: "Application only accepts SSL connections, reconnect using wss://"}, BaseWebsocketError{Code: APPLICATION_ONLY_ACCEPTS_SSL, Msg: "Application only accepts SSL connections, reconnect using wss://"},
} }
@@ -86,7 +86,7 @@ type InvalidVersionStringFormatError struct {
BaseWebsocketError BaseWebsocketError
} }
func NewInvalidVersionStringFormatError() InvalidVersionStringFormatError { func newInvalidVersionStringFormatError() InvalidVersionStringFormatError {
return InvalidVersionStringFormatError{ return InvalidVersionStringFormatError{
BaseWebsocketError{Code: INVALID_VERSION_STRING_FORMAT, Msg: "Invalid version string format"}, BaseWebsocketError{Code: INVALID_VERSION_STRING_FORMAT, Msg: "Invalid version string format"},
} }
@@ -99,7 +99,7 @@ type GenericReconnectImmediatelyError struct {
BaseWebsocketError BaseWebsocketError
} }
func NewGenericReconnectImmediatelyError() GenericReconnectImmediatelyError { func newGenericReconnectImmediatelyError() GenericReconnectImmediatelyError {
return GenericReconnectImmediatelyError{ return GenericReconnectImmediatelyError{
BaseWebsocketError{Code: GENERIC_RECONNECT_IMMEDIATELY, Msg: "Generic reconnect immediately"}, BaseWebsocketError{Code: GENERIC_RECONNECT_IMMEDIATELY, Msg: "Generic reconnect immediately"},
} }
@@ -111,7 +111,7 @@ type GenericError struct {
BaseWebsocketError BaseWebsocketError
} }
func NewGenericError(msg string) GenericError { func newGenericError(msg string) GenericError {
return GenericError{ return GenericError{
BaseWebsocketError{Code: GENERIC_ERROR, Msg: msg}, BaseWebsocketError{Code: GENERIC_ERROR, Msg: msg},
} }
+11 -11
View File
@@ -30,7 +30,7 @@ type SubscribeEvent struct {
} }
// Create a new subscribe event with the specified channel and data // Create a new subscribe event with the specified channel and data
func NewSubscribeEvent(channel, auth, channelData string) SubscribeEvent { func newSubscribeEvent(channel, auth, channelData string) SubscribeEvent {
data := SubscribeEventData{Channel: channel, Auth: auth, ChannelData: channelData} data := SubscribeEventData{Channel: channel, Auth: auth, ChannelData: channelData}
return SubscribeEvent{Event: "pusher:subscribe", Data: data} return SubscribeEvent{Event: "pusher:subscribe", Data: data}
} }
@@ -51,7 +51,7 @@ type UnsubscribeEvent struct {
} }
// Create a new unsubscribe event for the specified channel // Create a new unsubscribe event for the specified channel
func NewUnsubscribeEvent(channel string) UnsubscribeEvent { func newUnsubscribeEvent(channel string) UnsubscribeEvent {
data := UnsubscribeEventData{Channel: channel} data := UnsubscribeEventData{Channel: channel}
return UnsubscribeEvent{Event: "pusher:unsubscribe", Data: data} return UnsubscribeEvent{Event: "pusher:unsubscribe", Data: data}
} }
@@ -67,7 +67,7 @@ type SubscriptionSucceededEvent struct {
} }
// Create a new subscription succeed event for the specified channel // Create a new subscription succeed event for the specified channel
func NewSubscriptionSucceededEvent(channel, data string) SubscriptionSucceededEvent { func newSubscriptionSucceededEvent(channel, data string) SubscriptionSucceededEvent {
return SubscriptionSucceededEvent{Event: "pusher_internal:subscription_succeeded", Channel: channel, Data: data} return SubscriptionSucceededEvent{Event: "pusher_internal:subscription_succeeded", Channel: channel, Data: data}
} }
@@ -95,7 +95,7 @@ type SubscriptionSucceeedEventPresenceData struct {
Count int `json:"count"` Count int `json:"count"`
} }
func NewSubscriptionSucceedEventPresenceData(c *Channel) SubscriptionSucceeedEventPresenceData { func newSubscriptionSucceedEventPresenceData(c *Channel) SubscriptionSucceeedEventPresenceData {
event := SubscriptionSucceeedEventPresenceData{} event := SubscriptionSucceeedEventPresenceData{}
var ids []string var ids []string
@@ -127,7 +127,7 @@ type PongEvent struct {
} }
// Create a new pong event // Create a new pong event
func NewPongEvent() PongEvent { func newPongEvent() PongEvent {
return PongEvent{Event: "pusher:pong", Data: "{}"} return PongEvent{Event: "pusher:pong", Data: "{}"}
} }
@@ -141,7 +141,7 @@ type PingEvent struct {
} }
// Create a new ping event // Create a new ping event
func NewPingEvent() PingEvent { func newPingEvent() PingEvent {
return PingEvent{Event: "pusher:ping", Data: "{}"} return PingEvent{Event: "pusher:ping", Data: "{}"}
} }
@@ -161,7 +161,7 @@ type ErrorEvent struct {
// Pusher protocol is very strange in some parts // Pusher protocol is very strange in some parts
// It send null in some errors. // It send null in some errors.
// So I created this GENERIC_ERROR thing, just to verify if the json must have null on the error code // So I created this GENERIC_ERROR thing, just to verify if the json must have null on the error code
func NewErrorEvent(code int, message string) ErrorEvent { func newErrorEvent(code int, message string) ErrorEvent {
var data interface{} var data interface{}
if code == GENERIC_ERROR { if code == GENERIC_ERROR {
@@ -203,7 +203,7 @@ type ConnectionEstablishedEvent struct {
} }
// Create a new connection established event using the specified socketId // Create a new connection established event using the specified socketId
func NewConnectionEstablishedEvent(socketId string) ConnectionEstablishedEvent { func newConnectionEstablishedEvent(socketId string) ConnectionEstablishedEvent {
data := ConnectionEstablishedEventData{SocketId: socketId, ActivityTimeout: 120} data := ConnectionEstablishedEventData{SocketId: socketId, ActivityTimeout: 120}
b, err := json.Marshal(data) b, err := json.Marshal(data)
@@ -226,7 +226,7 @@ type MemberAddedEvent struct {
Data string `json:"data"` Data string `json:"data"`
} }
func NewMemberAddedEvent(channel, data string) MemberAddedEvent { func newMemberAddedEvent(channel, data string) MemberAddedEvent {
return MemberAddedEvent{Event: "pusher_internal:member_added", Channel: channel, Data: data} return MemberAddedEvent{Event: "pusher_internal:member_added", Channel: channel, Data: data}
} }
@@ -241,7 +241,7 @@ type MemberRemovedEvent struct {
Data string `json:"data"` Data string `json:"data"`
} }
func NewMemberRemovedEvent(channel string, s *Subscription) MemberRemovedEvent { func newMemberRemovedEvent(channel string, s *Subscription) MemberRemovedEvent {
data, err := json.Marshal(struct { data, err := json.Marshal(struct {
UserID string `json:"user_id"` UserID string `json:"user_id"`
}{ }{
@@ -273,6 +273,6 @@ type ResponseEvent struct {
} }
// The response event that is broadcasted to the client sockets // The response event that is broadcasted to the client sockets
func NewResponseEvent(name, channel string, data interface{}) ResponseEvent { func newResponseEvent(name, channel string, data interface{}) ResponseEvent {
return ResponseEvent{Event: name, Channel: channel, Data: data} return ResponseEvent{Event: name, Channel: channel, Data: data}
} }
+1 -1
View File
@@ -12,7 +12,7 @@ import (
) )
// Check if the application is disabled // Check if the application is disabled
func RestCheckAppDisabledHandler(h http.Handler) http.Handler { func restCheckAppDisabledHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r) vars := mux.Vars(r)
appID := vars["app_id"] appID := vars["app_id"]
+4 -4
View File
@@ -29,7 +29,7 @@ import (
// Response is an empty JSON hash. // Response is an empty JSON hash.
// //
// POST /apps/{app_id}/events // POST /apps/{app_id}/events
func PostEvents(w http.ResponseWriter, r *http.Request) { func postEvents(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r) vars := mux.Vars(r)
appID := vars["app_id"] appID := vars["app_id"]
@@ -95,7 +95,7 @@ func PostEvents(w http.ResponseWriter, r *http.Request) {
// } // }
// //
// GET /apps/{app_id}/channels // GET /apps/{app_id}/channels
func GetChannels(w http.ResponseWriter, r *http.Request) { func getChannels(w http.ResponseWriter, r *http.Request) {
params := r.URL.Query() params := r.URL.Query()
vars := mux.Vars(r) vars := mux.Vars(r)
@@ -176,7 +176,7 @@ func GetChannels(w http.ResponseWriter, r *http.Request) {
// } // }
// //
// GET /apps/{app_id}/channels/{channel_name} // GET /apps/{app_id}/channels/{channel_name}
func GetChannel(w http.ResponseWriter, r *http.Request) { func getChannel(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json;charset=UTF-8") w.Header().Set("Content-Type", "application/json;charset=UTF-8")
params := r.URL.Query() params := r.URL.Query()
@@ -266,7 +266,7 @@ func GetChannel(w http.ResponseWriter, r *http.Request) {
// } // }
// //
// GET /apps/{app_id}/channels/{channel_name}/users // GET /apps/{app_id}/channels/{channel_name}/users
func GetChannelUsers(w http.ResponseWriter, r *http.Request) { func getChannelUsers(w http.ResponseWriter, r *http.Request) {
vars := mux.Vars(r) vars := mux.Vars(r)
appID := vars["app_id"] appID := vars["app_id"]
+2 -2
View File
@@ -31,8 +31,8 @@ func NewRouter() *mux.Router {
handler = route.HandlerFunc handler = route.HandlerFunc
if route.RequiresRestAuth { if route.RequiresRestAuth {
handler = RestAuthenticationHandler(handler) handler = restAuthenticationHandler(handler)
handler = RestCheckAppDisabledHandler(handler) handler = restCheckAppDisabledHandler(handler)
} }
router.Methods(route.Method).Path(route.Pattern).Name(route.Name).Handler(handler) router.Methods(route.Method).Path(route.Pattern).Name(route.Name).Handler(handler)
+5 -5
View File
@@ -24,35 +24,35 @@ var routes = Routes{
"PostEvents", "PostEvents",
"POST", "POST",
"/apps/{app_id}/events", "/apps/{app_id}/events",
PostEvents, postEvents,
true, true,
}, },
Route{ Route{
"GetChannels", "GetChannels",
"GET", "GET",
"/apps/{app_id}/channels", "/apps/{app_id}/channels",
GetChannels, getChannels,
true, true,
}, },
Route{ Route{
"GetChannel", "GetChannel",
"GET", "GET",
"/apps/{app_id}/channels/{channel_name}", "/apps/{app_id}/channels/{channel_name}",
GetChannel, getChannel,
true, true,
}, },
Route{ Route{
"GetChannelUsers", "GetChannelUsers",
"GET", "GET",
"/apps/{app_id}/channels/{channel_name}/users", "/apps/{app_id}/channels/{channel_name}/users",
GetChannelUsers, getChannelUsers,
true, true,
}, },
Route{ Route{
"Websocket", "Websocket",
"GET", "GET",
"/app/{key}", "/app/{key}",
Websocket, wsHandler,
false, false,
}, },
} }
+1 -1
View File
@@ -12,6 +12,6 @@ type Subscription struct {
} }
// Create a new Subscription // Create a new Subscription
func NewSubscription(conn *Connection, data string) *Subscription { func newSubscription(conn *Connection, data string) *Subscription {
return &Subscription{Connection: conn, Data: data} return &Subscription{Connection: conn, Data: data}
} }
+10 -10
View File
@@ -47,37 +47,37 @@ type HookEvent struct {
UserId string `json:"user_id,omitempty"` UserId string `json:"user_id,omitempty"`
} }
func NewChannelOcuppiedHook(channel *Channel) HookEvent { func newChannelOcuppiedHook(channel *Channel) HookEvent {
return HookEvent{Name: "channel_occupied", Channel: channel.ChannelID} return HookEvent{Name: "channel_occupied", Channel: channel.ChannelID}
} }
func NewChannelVacatedHook(channel *Channel) HookEvent { func newChannelVacatedHook(channel *Channel) HookEvent {
return HookEvent{Name: "channel_vacated", Channel: channel.ChannelID} return HookEvent{Name: "channel_vacated", Channel: channel.ChannelID}
} }
func NewMemberAddedHook(channel *Channel, s *Subscription) HookEvent { func newMemberAddedHook(channel *Channel, s *Subscription) HookEvent {
return HookEvent{Name: "member_added", Channel: channel.ChannelID, UserId: s.Id} return HookEvent{Name: "member_added", Channel: channel.ChannelID, UserId: s.Id}
} }
func NewMemberRemovedHook(channel *Channel, s *Subscription) HookEvent { func newMemberRemovedHook(channel *Channel, s *Subscription) HookEvent {
return HookEvent{Name: "member_removed", Channel: channel.ChannelID, UserId: s.Id} return HookEvent{Name: "member_removed", Channel: channel.ChannelID, UserId: s.Id}
} }
func NewClientHook(channel *Channel, s *Subscription, event string, data interface{}) HookEvent { func newClientHook(channel *Channel, s *Subscription, event string, data interface{}) HookEvent {
return HookEvent{Name: "client_event", Channel: channel.ChannelID, Event: event, Data: data, SocketID: s.Connection.SocketID} return HookEvent{Name: "client_event", Channel: channel.ChannelID, Event: event, Data: data, SocketID: s.Connection.SocketID}
} }
// channel_occupied // channel_occupied
// { "name": "channel_occupied", "channel": "test_channel" } // { "name": "channel_occupied", "channel": "test_channel" }
func (a *App) TriggerChannelOccupiedHook(c *Channel) { func (a *App) TriggerChannelOccupiedHook(c *Channel) {
event := NewChannelOcuppiedHook(c) event := newChannelOcuppiedHook(c)
triggerHook(event.Name, a, c, event) triggerHook(event.Name, a, c, event)
} }
// channel_vacated // channel_vacated
// { "name": "channel_vacated", "channel": "test_channel" } // { "name": "channel_vacated", "channel": "test_channel" }
func (a *App) TriggerChannelVacatedHook(c *Channel) { func (a *App) TriggerChannelVacatedHook(c *Channel) {
event := NewChannelVacatedHook(c) event := newChannelVacatedHook(c)
triggerHook(event.Name, a, c, event) triggerHook(event.Name, a, c, event)
} }
@@ -90,7 +90,7 @@ func (a *App) TriggerChannelVacatedHook(c *Channel) {
// "user_id": "user_id associated with the sending socket" # Only for presence channels // "user_id": "user_id associated with the sending socket" # Only for presence channels
// } // }
func (a *App) TriggerClientEventHook(c *Channel, s *Subscription, client_event string, data interface{}) { func (a *App) TriggerClientEventHook(c *Channel, s *Subscription, client_event string, data interface{}) {
event := NewClientHook(c, s, client_event, data) event := newClientHook(c, s, client_event, data)
if c.IsPresence() { if c.IsPresence() {
event.UserId = s.Id event.UserId = s.Id
@@ -105,7 +105,7 @@ func (a *App) TriggerClientEventHook(c *Channel, s *Subscription, client_event s
// "user_id": "a_user_id" // "user_id": "a_user_id"
// } // }
func (a *App) TriggerMemberAddedHook(c *Channel, s *Subscription) { func (a *App) TriggerMemberAddedHook(c *Channel, s *Subscription) {
event := NewMemberAddedHook(c, s) event := newMemberAddedHook(c, s)
triggerHook(event.Name, a, c, event) triggerHook(event.Name, a, c, event)
} }
@@ -115,7 +115,7 @@ func (a *App) TriggerMemberAddedHook(c *Channel, s *Subscription) {
// "user_id": "a_user_id" // "user_id": "a_user_id"
// } // }
func (a *App) TriggerMemberRemovedHook(c *Channel, s *Subscription) { func (a *App) TriggerMemberRemovedHook(c *Channel, s *Subscription) {
event := NewMemberRemovedHook(c, s) event := newMemberRemovedHook(c, s)
triggerHook(event.Name, a, c, event) triggerHook(event.Name, a, c, event)
} }
+28 -28
View File
@@ -33,29 +33,29 @@ func onOpen(conn *websocket.Conn, w http.ResponseWriter, r *http.Request, sessio
protocol, err := strconv.Atoi(p) protocol, err := strconv.Atoi(p)
if err != nil { if err != nil {
return NewInvalidVersionStringFormatError() return newInvalidVersionStringFormatError()
} }
switch { switch {
case strings.TrimSpace(p) == "": case strings.TrimSpace(p) == "":
return NewNoProtocolVersionSuppliedError() return newNoProtocolVersionSuppliedError()
case protocol != SUPPORTED_PROTOCOL_VERSION: case protocol != SUPPORTED_PROTOCOL_VERSION:
return NewUnsupportedProtocolVersionError() return newUnsupportedProtocolVersionError()
case app.ApplicationDisabled: case app.ApplicationDisabled:
return NewApplicationDisabledError() return newApplicationDisabledError()
case r.TLS != nil: case r.TLS != nil:
if app.OnlySSL { if app.OnlySSL {
return NewApplicationOnlyAccepsSSLError() return newApplicationOnlyAccepsSSLError()
} }
} }
// Create the new Subscriber // Create the new Subscriber
connection := NewConnection(sessionID, conn) connection := newConnection(sessionID, conn)
app.Connect(connection) app.Connect(connection)
// Everything went fine. Huhu. // Everything went fine. Huhu.
if err := conn.WriteJSON(NewConnectionEstablishedEvent(connection.SocketID)); err != nil { if err := conn.WriteJSON(newConnectionEstablishedEvent(connection.SocketID)); err != nil {
return NewGenericReconnectImmediatelyError() return newGenericReconnectImmediatelyError()
} }
return nil return nil
@@ -84,13 +84,13 @@ func onMessage(conn *websocket.Conn, w http.ResponseWriter, r *http.Request, ses
case io.EOF: case io.EOF:
onClose(sessionID, app) onClose(sessionID, app)
default: default:
emitWSError(NewGenericReconnectImmediatelyError(), conn) emitWSError(newGenericReconnectImmediatelyError(), conn)
} }
break break
} }
if err := json.Unmarshal(message, &event); err != nil { if err := json.Unmarshal(message, &event); err != nil {
emitWSError(NewGenericReconnectImmediatelyError(), conn) emitWSError(newGenericReconnectImmediatelyError(), conn)
break break
} }
@@ -98,21 +98,21 @@ func onMessage(conn *websocket.Conn, w http.ResponseWriter, r *http.Request, ses
switch event.Event { switch event.Event {
case "pusher:ping": case "pusher:ping":
if err := conn.WriteJSON(NewPongEvent()); err != nil { if err := conn.WriteJSON(newPongEvent()); err != nil {
emitWSError(NewGenericReconnectImmediatelyError(), conn) emitWSError(newGenericReconnectImmediatelyError(), conn)
} }
case "pusher:subscribe": case "pusher:subscribe":
subscribeEvent := SubscribeEvent{} subscribeEvent := SubscribeEvent{}
if err := json.Unmarshal(message, &subscribeEvent); err != nil { if err := json.Unmarshal(message, &subscribeEvent); err != nil {
emitWSError(NewGenericReconnectImmediatelyError(), conn) emitWSError(newGenericReconnectImmediatelyError(), conn)
break break
} }
connection, err := app.FindConnection(sessionID) connection, err := app.FindConnection(sessionID)
if err != nil { if err != nil {
emitWSError(NewGenericReconnectImmediatelyError(), conn) emitWSError(newGenericReconnectImmediatelyError(), conn)
break break
} }
@@ -130,7 +130,7 @@ func onMessage(conn *websocket.Conn, w http.ResponseWriter, r *http.Request, ses
expectedAuthKey := fmt.Sprintf("%s:%s", app.Key, utils.HashMAC([]byte(strings.Join(toSign, ":")), []byte(app.Secret))) expectedAuthKey := fmt.Sprintf("%s:%s", app.Key, utils.HashMAC([]byte(strings.Join(toSign, ":")), []byte(app.Secret)))
if subscribeEvent.Data.Auth != expectedAuthKey { if subscribeEvent.Data.Auth != expectedAuthKey {
emitWSError(NewGenericError(fmt.Sprintf("Auth value for subscription to %s is invalid", channelName)), conn) emitWSError(newGenericError(fmt.Sprintf("Auth value for subscription to %s is invalid", channelName)), conn)
continue continue
} }
} }
@@ -139,60 +139,60 @@ func onMessage(conn *websocket.Conn, w http.ResponseWriter, r *http.Request, ses
log.Info(subscribeEvent.Data.ChannelData) log.Info(subscribeEvent.Data.ChannelData)
if err := app.Subscribe(channel, connection, subscribeEvent.Data.ChannelData); err != nil { if err := app.Subscribe(channel, connection, subscribeEvent.Data.ChannelData); err != nil {
emitWSError(NewGenericReconnectImmediatelyError(), conn) emitWSError(newGenericReconnectImmediatelyError(), conn)
} }
case "pusher:unsubscribe": case "pusher:unsubscribe":
unsubscribeEvent := UnsubscribeEvent{} unsubscribeEvent := UnsubscribeEvent{}
if err := json.Unmarshal(message, &unsubscribeEvent); err != nil { if err := json.Unmarshal(message, &unsubscribeEvent); err != nil {
emitWSError(NewGenericReconnectImmediatelyError(), conn) emitWSError(newGenericReconnectImmediatelyError(), conn)
} }
connection, err := app.FindConnection(sessionID) connection, err := app.FindConnection(sessionID)
if err != nil { if err != nil {
emitWSError(NewGenericError(fmt.Sprintf("Could not find a connection with the id %s", sessionID)), conn) emitWSError(newGenericError(fmt.Sprintf("Could not find a connection with the id %s", sessionID)), conn)
} }
channel, err := app.FindChannelByChannelID(unsubscribeEvent.Data.Channel) channel, err := app.FindChannelByChannelID(unsubscribeEvent.Data.Channel)
if err != nil { if err != nil {
emitWSError(NewGenericError(fmt.Sprintf("Could not find a channel with the id %s", unsubscribeEvent.Data.Channel)), conn) emitWSError(newGenericError(fmt.Sprintf("Could not find a channel with the id %s", unsubscribeEvent.Data.Channel)), conn)
} }
if err := app.Unsubscribe(channel, connection); err != nil { if err := app.Unsubscribe(channel, connection); err != nil {
emitWSError(NewGenericReconnectImmediatelyError(), conn) emitWSError(newGenericReconnectImmediatelyError(), conn)
break break
} }
default: // CLient Events ?? default: // CLient Events ??
// see http://pusher.com/docs/client_api_guide/client_events#trigger-events // see http://pusher.com/docs/client_api_guide/client_events#trigger-events
if strings.HasPrefix(event.Event, "client-") { if strings.HasPrefix(event.Event, "client-") {
if !app.UserEvents { if !app.UserEvents {
emitWSError(NewGenericError("To send client events, you must enable this feature in the Settings."), conn) emitWSError(newGenericError("To send client events, you must enable this feature in the Settings."), conn)
} }
clientEvent := RawEvent{} clientEvent := RawEvent{}
if err := json.Unmarshal(message, &clientEvent); err != nil { if err := json.Unmarshal(message, &clientEvent); err != nil {
log.Error(err) log.Error(err)
emitWSError(NewGenericReconnectImmediatelyError(), conn) emitWSError(newGenericReconnectImmediatelyError(), conn)
break break
} }
channel, err := app.FindChannelByChannelID(clientEvent.Channel) channel, err := app.FindChannelByChannelID(clientEvent.Channel)
if !channel.IsPresenceOrPrivate() { if !channel.IsPresenceOrPrivate() {
emitWSError(NewGenericError("Client event rejected - only supported on private and presence channels"), conn) emitWSError(newGenericError("Client event rejected - only supported on private and presence channels"), conn)
break break
} }
if err != nil { if err != nil {
emitWSError(NewGenericError(fmt.Sprintf("Could not find a channel with the id %s", clientEvent.Channel)), conn) emitWSError(newGenericError(fmt.Sprintf("Could not find a channel with the id %s", clientEvent.Channel)), conn)
} }
if err := app.Publish(channel, clientEvent, sessionID); err != nil { if err := app.Publish(channel, clientEvent, sessionID); err != nil {
log.Error(err) log.Error(err)
emitWSError(NewGenericReconnectImmediatelyError(), conn) emitWSError(newGenericReconnectImmediatelyError(), conn)
break break
} }
} }
@@ -202,7 +202,7 @@ func onMessage(conn *websocket.Conn, w http.ResponseWriter, r *http.Request, ses
} }
// Websocket GET /app/{key} // Websocket GET /app/{key}
func Websocket(w http.ResponseWriter, r *http.Request) { func wsHandler(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil) conn, err := upgrader.Upgrade(w, r, nil)
defer func() { defer func() {
if conn != nil { if conn != nil {
@@ -222,7 +222,7 @@ func Websocket(w http.ResponseWriter, r *http.Request) {
if err != nil { if err != nil {
log.Error(err) log.Error(err)
emitWSError(NewApplicationDoesNotExistsError(), conn) emitWSError(newApplicationDoesNotExistsError(), conn)
return return
} }
@@ -239,7 +239,7 @@ func Websocket(w http.ResponseWriter, r *http.Request) {
// Emit an Websocket ErrorEvent // Emit an Websocket ErrorEvent
func emitWSError(err WebsocketError, conn *websocket.Conn) { func emitWSError(err WebsocketError, conn *websocket.Conn) {
event := NewErrorEvent(err.GetCode(), err.GetMsg()) event := newErrorEvent(err.GetCode(), err.GetMsg())
if err := conn.WriteJSON(event); err != nil { if err := conn.WriteJSON(event); err != nil {
log.Error(err) log.Error(err)