├── .gitignore ├── LICENSE.md ├── README.md ├── connection.go ├── doc.go ├── hub.go ├── message.go ├── protocol.go ├── room.go ├── room_manager.go └── router.go /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | tags 3 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | golem _v0.4.4_ 2 | ================================ 3 | A lightweight extendable Go WebSocket-framework with [client library](https://github.com/trevex/golem_client). 4 | 5 | Status 6 | ------------------------- 7 | The project can be considered __dead__. There has been no development in recent years. It is still available on github for research and archiving purposes. 8 | 9 | License 10 | ------------------------- 11 | Golem is available under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0.html) 12 | 13 | Installation 14 | ------------------------- 15 | ``` 16 | go get github.com/trevex/golem 17 | ``` 18 | 19 | Client 20 | ------------------------- 21 | A [client](https://github.com/trevex/golem_client) is also available and heavily used in the [examples](https://github.com/trevex/golem_examples). 22 | More information on how the client is used can be found in the [client repository](https://github.com/trevex/golem_client). 23 | 24 | Simple Example 25 | ------------------------- 26 | Server: 27 | ```go 28 | type Hello struct { 29 | From string `json:"from"` 30 | } 31 | type Answer struct { 32 | Msg string `json:"msg"` 33 | } 34 | func hello(conn *golem.Connection, data *Hello) { 35 | conn.Emit("answer", &Answer{"Thanks, "+ data.From + "!"}) 36 | } 37 | func main() { 38 | myrouter := golem.NewRouter() 39 | myrouter.On("hello", hello) 40 | http.HandleFunc("/ws", myrouter.Handler()) 41 | http.ListenAndServe(":8080", nil) 42 | } 43 | ``` 44 | Client: 45 | ```javascript 46 | var conn = new golem.Connection("ws://127.0.0.1:8080/ws", true); 47 | conn.on("answer", function(data) { 48 | console.log("Answer: "+data.msg); 49 | }); 50 | conn.on("open", function() { 51 | conn.emit("hello", { from: "Client" }); 52 | }); 53 | ``` 54 | Output in client console would be `Thanks, Client!`. 55 | 56 | Documentation 57 | ------------------------- 58 | The documentation is provided via [godoc](http://godoc.org/github.com/trevex/golem). 59 | 60 | Wiki & Tutorials 61 | ------------------------- 62 | More informations and insights can be found on the [wiki page](https://github.com/trevex/golem/wiki) along with a tutorial series to learn how to use golem: 63 | * [Getting started](https://github.com/trevex/golem/wiki/Getting-started) 64 | * [Using rooms](https://github.com/trevex/golem/wiki/Using-rooms) 65 | * [Building a Chat application](https://github.com/trevex/golem/wiki/Building-a-chat-application) 66 | * [Handshake authorisation using Sessions](https://github.com/trevex/golem/wiki/Handshake-authorisation-using-Sessions) 67 | * [Using flash as WebSocket fallback](https://github.com/trevex/golem/wiki/Using-flash-as-WebSocket-fallback) 68 | * [Custom protocol using BSON](https://github.com/trevex/golem/wiki/Custom-protocol-using-BSON) 69 | * [Using an extended connection type](https://github.com/trevex/golem/wiki/Using-an-extended-connection-type) 70 | 71 | More Examples 72 | ------------------------- 73 | Several examples are available in the [example repository](https://github.com/trevex/golem_examples). To use them simply checkout the 74 | repository and make sure you installed (go get) golem before. A more detailed guide on how 75 | to use them is located in their repository. 76 | 77 | History 78 | ------------------------- 79 | * _v0.1.0_ 80 | * Basic API layout and documentation 81 | * _v0.2.0_ 82 | * Evented communication system and routing 83 | * Basic room implementation (lobbies renamed to rooms for clarity) 84 | * _v0.3.0_ 85 | * Protocol extensions through Parsers 86 | * Room manager for collections of rooms 87 | * _v0.4.0_ 88 | * Protocol interchangable 89 | * Several bugfixes 90 | * Client up-to-date 91 | * _v0.4.2_ 92 | * Connection type can be extended 93 | * Close added to connection 94 | * _v0.4.3_ 95 | * RoomManager emiting create- and remove-events (remove if room has insufficient users) 96 | * _v0.4.4_ 97 | * RoomManager manages set of connection dependent options, see `example_chat_options.go` 98 | * Router provides OnConnect callback 99 | 100 | Special thanks 101 | ------------------------- 102 | * [Gary Burd](http://gary.beagledreams.com/) (for the great WebSocket protocol implementation and insights through his examples) 103 | * [Andrew Gallant](http://burntsushi.net/) (for help on golang-nuts mailing list) 104 | * [Kortschak](https://github.com/kortschak) (for help on golang-nuts mailing list) 105 | 106 | Contributors 107 | ------------------------- 108 | * [Nik Voss](https://github.com/trevex) 109 | * [Jeff Mitchell](https://github.com/jefferai) 110 | 111 | TODO 112 | ------------------------- 113 | * Verbose and configurable logging 114 | * Testing 115 | -------------------------------------------------------------------------------- /connection.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2013 Niklas Voss 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package golem 20 | 21 | import ( 22 | "github.com/gorilla/websocket" 23 | "reflect" 24 | "time" 25 | ) 26 | 27 | const ( 28 | // Time allowed to write a message to the client. 29 | writeWait = 10 * time.Second 30 | // Time allowed to read the next message from the client. 31 | readWait = 60 * time.Second 32 | // Send pings to client with this period. Must be less than readWait. 33 | pingPeriod = (readWait * 9) / 10 34 | // Maximum message size allowed from client. 35 | maxMessageSize = 512 36 | // Outgoing default channel size. 37 | sendChannelSize = 512 38 | ) 39 | 40 | var ( 41 | defaultConnectionExtension = reflect.ValueOf(nil) 42 | ) 43 | 44 | // SetDefaultConnectionExtension sets the initial extension used by all freshly instanced routers. 45 | // For more information see the Router SetConnectionExtension() - method. 46 | func SetDefaultConnectionExtension(constructor interface{}) { 47 | defaultConnectionExtension = reflect.ValueOf(constructor) 48 | } 49 | 50 | // Connection holds information about the underlying WebSocket-Connection, 51 | // the associated router and the outgoing data channel. 52 | type Connection struct { 53 | // The websocket connection. 54 | socket *websocket.Conn 55 | // Associated router. 56 | router *Router 57 | // Buffered channel of outbound messages. 58 | send chan *message 59 | // 60 | extension interface{} 61 | } 62 | 63 | // Create a new connection using the specified socket and router. 64 | func newConnection(s *websocket.Conn, r *Router) *Connection { 65 | return &Connection{ 66 | socket: s, 67 | router: r, 68 | send: make(chan *message, sendChannelSize), 69 | extension: nil, 70 | } 71 | } 72 | 73 | // Register connection and start writing and reading loops. 74 | func (conn *Connection) run() { 75 | hub.register <- conn 76 | readMode := websocket.TextMessage 77 | writeMode := websocket.TextMessage 78 | if conn.router.protocol.GetReadMode() != TextMode { 79 | readMode = websocket.BinaryMessage 80 | } 81 | if conn.router.protocol.GetWriteMode() != TextMode { 82 | writeMode = websocket.BinaryMessage 83 | } 84 | if conn.router.useHeartbeats { 85 | go conn.writePumpHeartbeat(writeMode) 86 | conn.readPumpHeartbeat(readMode) 87 | } else { 88 | go conn.writePump(writeMode) 89 | conn.readPump(readMode) 90 | } 91 | } 92 | 93 | func (conn *Connection) extend(e interface{}) { 94 | conn.extension = e 95 | } 96 | 97 | // Emit event with provided data. The data will be automatically marshalled and packed according 98 | // to the active protocol of the router the connection belongs to. 99 | func (conn *Connection) Emit(event string, data interface{}) { 100 | conn.send <- &message{ 101 | event: event, 102 | data: data, 103 | } 104 | } 105 | 106 | // Close closes and cleans up the connection. 107 | func (conn *Connection) Close() { 108 | hub.unregister <- conn 109 | } 110 | 111 | // Helper for writing to socket with deadline. 112 | func (conn *Connection) write(mode int, payload []byte) error { 113 | conn.socket.SetWriteDeadline(time.Now().Add(writeWait)) 114 | return conn.socket.WriteMessage(mode, payload) 115 | } 116 | 117 | /* 118 | * Pumps with Heartbeat. 119 | */ 120 | 121 | func (conn *Connection) readPumpHeartbeat(mode int) { 122 | defer func() { 123 | hub.unregister <- conn 124 | conn.socket.Close() 125 | conn.router.closeFunc(conn) 126 | }() 127 | conn.socket.SetReadLimit(maxMessageSize) 128 | conn.socket.SetReadDeadline(time.Now().Add(readWait)) 129 | conn.socket.SetPongHandler(func(string) error { 130 | conn.socket.SetReadDeadline(time.Now().Add(readWait)) 131 | return nil 132 | }) 133 | for { 134 | mm, message, err := conn.socket.ReadMessage() 135 | if err != nil { 136 | break 137 | } 138 | if mm == mode { 139 | conn.router.processMessage(conn, message) 140 | } 141 | } 142 | } 143 | 144 | func (conn *Connection) writePumpHeartbeat(mode int) { 145 | ticker := time.NewTicker(pingPeriod) 146 | defer func() { 147 | ticker.Stop() 148 | conn.socket.Close() // Necessary to force reading to stop 149 | }() 150 | for { 151 | select { 152 | case message, ok := <-conn.send: 153 | if ok { 154 | if data, err := conn.router.protocol.MarshalAndPack(message.event, message.data); err == nil { 155 | if err := conn.write(mode, data); err != nil { 156 | return 157 | } 158 | } else { 159 | // TODO: logging 160 | } 161 | } else { 162 | conn.write(websocket.CloseMessage, []byte{}) 163 | return 164 | } 165 | case <-ticker.C: 166 | if err := conn.write(websocket.PingMessage, []byte{}); err != nil { 167 | return 168 | } 169 | } 170 | } 171 | } 172 | 173 | /* 174 | * Pumps without Heartbeat 175 | */ 176 | 177 | func (conn *Connection) readPump(mode int) { 178 | defer func() { 179 | hub.unregister <- conn 180 | conn.socket.Close() 181 | conn.router.closeFunc(conn) 182 | }() 183 | conn.socket.SetReadLimit(maxMessageSize) 184 | for { 185 | mm, message, err := conn.socket.ReadMessage() 186 | if err != nil { 187 | break 188 | } 189 | if mm == mode { 190 | conn.router.processMessage(conn, message) 191 | } 192 | } 193 | } 194 | 195 | func (conn *Connection) writePump(mode int) { 196 | defer func() { 197 | conn.socket.Close() // Necessary to force reading to stop 198 | }() 199 | for { 200 | select { 201 | case message, ok := <-conn.send: 202 | if ok { 203 | if data, err := conn.router.protocol.MarshalAndPack(message.event, message.data); err == nil { 204 | if err := conn.write(mode, data); err != nil { 205 | return 206 | } 207 | } else { 208 | // TODO: logging 209 | } 210 | } else { 211 | conn.write(websocket.CloseMessage, []byte{}) 212 | return 213 | } 214 | } 215 | } 216 | } 217 | 218 | 219 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2013 Niklas Voss 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | // Golem is a lightweight WebSocket-framework. 20 | // it simplifies interaction with websockets by exposing an event-based system allowing 21 | // easy prototyping of WebSocket-interaction. To achieve this a simple extendable JSON-based 22 | // protocol is used by default, but custom protocol or simple protocol extensions are supported. 23 | // 24 | // For more general information, visit the wiki: 25 | // https://github.com/trevex/golem/wiki 26 | // 27 | // Examples can be found in the example repository: 28 | // https://github.com/trevex/golem_examples 29 | // 30 | // The client documentation and repository: 31 | // https://github.com/trevex/golem_client 32 | package golem 33 | -------------------------------------------------------------------------------- /hub.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2013 Niklas Voss 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package golem 20 | 21 | const ( 22 | // Broadcast Channel Size 23 | broadcastChannelSize = 16 24 | ) 25 | 26 | // The Hub manages all active connection, but should only be used directly 27 | // if broadcasting of data or an event to all connections is desired. 28 | // The Hub should not be instanced directly. Use GetHub to get the active hub 29 | // for broadcasting messages. 30 | type Hub struct { 31 | // Registered connections. 32 | connections map[*Connection]bool 33 | 34 | // Inbound messages from the connections. 35 | broadcast chan *message 36 | 37 | // Register requests from the connections. 38 | register chan *Connection 39 | 40 | // Unregister requests from connections. 41 | unregister chan *Connection 42 | 43 | // Flag to determine if running or not 44 | isRunning bool 45 | } 46 | 47 | // Remove the specified connection from the hub and drop the socket. 48 | func (hub *Hub) remove(conn *Connection) { 49 | delete(hub.connections, conn) 50 | close(conn.send) 51 | } 52 | 53 | // If the hub is not running, start it in a different goroutine. 54 | func (hub *Hub) run() { 55 | if hub.isRunning != true { // Should be safe, because only called from NewRouter and therefore a single thread. 56 | hub.isRunning = true 57 | go func() { 58 | for { 59 | select { 60 | // Register new connection 61 | case conn := <-hub.register: 62 | hub.connections[conn] = true 63 | // Unregister dropped connection 64 | case conn := <-hub.unregister: 65 | if _, ok := hub.connections[conn]; ok { 66 | hub.remove(conn) 67 | } 68 | // Broadcast 69 | case message := <-hub.broadcast: 70 | for conn := range hub.connections { 71 | select { 72 | case conn.send <- message: 73 | default: 74 | hub.remove(conn) 75 | } 76 | } 77 | } 78 | } 79 | }() 80 | } 81 | } 82 | 83 | // Create the hub instance. 84 | var hub = Hub{ 85 | broadcast: make(chan *message, broadcastChannelSize), 86 | register: make(chan *Connection), 87 | unregister: make(chan *Connection), 88 | connections: make(map[*Connection]bool), 89 | isRunning: false, 90 | } 91 | 92 | // GetHub retrieves and returns pointer to golem's active hub. 93 | func GetHub() *Hub { 94 | return &hub 95 | } 96 | 97 | // Broadcast emits an event with data to ALL active connections. 98 | func (hub *Hub) Broadcast(event string, data interface{}) { 99 | hub.broadcast <- &message{ 100 | event: event, 101 | data: data, 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /message.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2013 Niklas Voss 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package golem 20 | 21 | // Message is container for unprepared data and therefore holds the event name and the pointer to the struct holding the data. 22 | type message struct { 23 | event string 24 | data interface{} 25 | } 26 | -------------------------------------------------------------------------------- /protocol.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2013 Niklas Voss 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package golem 20 | 21 | import ( 22 | "encoding/json" 23 | "errors" 24 | "strings" 25 | ) 26 | 27 | const ( 28 | protocolSeperator = " " 29 | // BinaryMode represents binary WebSocket operations 30 | BinaryMode = 1 31 | // TextMode represents text-based WebSocket operations 32 | TextMode = 2 33 | ) 34 | 35 | var ( 36 | // protocol routers will initially be using 37 | initialProtocol Protocol = Protocol(&DefaultJSONProtocol{}) 38 | ) 39 | 40 | // Protocol-interface provides the required methods necessary for any 41 | // protocol, that should be used with golem, to implement. 42 | // The evented system of golem needs several steps to process incoming data: 43 | // 1. Unpack to extract the name of the event that was emitted. 44 | // (next golem checks if an event handler exists, if does, the next method is called with the associated structure of the event) 45 | // 2. Unmarshal the interstage product from unpack into the desired type. 46 | // For emitting data the process is reversed, but merged in a single function, 47 | // because evaluation the desired unmarshaled type is not necessary: 48 | // 1. MarshalAndPack marhals the data and the event name into an array of bytes. 49 | // The GetReadMode and GetWriteMode functions define what kind of WebSocket- 50 | // Communication will be used. 51 | type Protocol interface { 52 | // Unpack splits/extracts event name from incoming data. 53 | // Takes incoming data bytes as parameter and returns the event name, interstage data and if an error occured the error. 54 | Unpack([]byte) (string, interface{}, error) 55 | // Unmarshals leftover data into associated type of callback. 56 | // Takes interstage product and desired type as parameters and returns error if unsuccessful. 57 | Unmarshal(interface{}, interface{}) error 58 | // Marshal and pack data into byte array 59 | // Takes event name and type pointer as parameters and returns byte array or error if unsuccessful. 60 | MarshalAndPack(string, interface{}) ([]byte, error) 61 | // Returns read mode, that should be used for this protocol. 62 | GetReadMode() int 63 | // Returns write mode, that should be used for this protocol 64 | GetWriteMode() int 65 | } 66 | 67 | // SetDefaultProtocol sets the protocol that should be used by newly created routers. Therefore every router 68 | // created after changing the default protocol will use the new protocol by default. 69 | func SetDefaultProtocol(protocol Protocol) { 70 | initialProtocol = protocol 71 | } 72 | 73 | // DefaultJSONProtocol is the initial protocol used by golem. It implements the 74 | // Protocol-Interface. 75 | // (Note: there is an article about this simple protocol in golem's wiki) 76 | type DefaultJSONProtocol struct{} 77 | 78 | // Unpack splits the event name from the incoming message. 79 | func (_ *DefaultJSONProtocol) Unpack(data []byte) (string, interface{}, error) { 80 | result := strings.SplitN(string(data), protocolSeperator, 2) 81 | if len(result) != 2 { 82 | return "", nil, errors.New("Unable to extract event name from data.") 83 | } 84 | return result[0], []byte(result[1]), nil 85 | } 86 | 87 | // Unmarshals data into requested structure. If not successful the function return an error. 88 | func (_ *DefaultJSONProtocol) Unmarshal(data interface{}, typePtr interface{}) error { 89 | return json.Unmarshal(data.([]byte), typePtr) 90 | } 91 | 92 | // Marshals structure into JSON and packs event name in as well. If not successful second return value is an error. 93 | func (_ *DefaultJSONProtocol) MarshalAndPack(name string, structPtr interface{}) ([]byte, error) { 94 | if data, err := json.Marshal(structPtr); err == nil { 95 | result := []byte(name + protocolSeperator) 96 | return append(result, data...), nil 97 | } else { 98 | return nil, err 99 | } 100 | } 101 | 102 | // Return TextMode because JSON is transmitted using the text mode of WebSockets. 103 | func (_ *DefaultJSONProtocol) GetReadMode() int { 104 | return TextMode 105 | } 106 | 107 | // Return TextMode because JSON is transmitted using the text mode of WebSockets. 108 | func (_ *DefaultJSONProtocol) GetWriteMode() int { 109 | return TextMode 110 | } 111 | -------------------------------------------------------------------------------- /room.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2013 Niklas Voss 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package golem 20 | 21 | const ( 22 | roomSendChannelSize = 32 23 | ) 24 | 25 | // Rooms are groups of connections. A room provides methods to communicate with all 26 | // members of the group simultaneously. 27 | type Room struct { 28 | // Map of member connections 29 | members map[*Connection]bool 30 | // Stop channel 31 | stop chan bool 32 | // Join request 33 | join chan *Connection 34 | // Leave request 35 | leave chan *Connection 36 | // Broadcast to room members 37 | send chan *message 38 | } 39 | 40 | // Creates and initialised a room and returns pointer to it. 41 | func NewRoom() *Room { 42 | r := Room{ 43 | members: make(map[*Connection]bool), 44 | stop: make(chan bool), 45 | join: make(chan *Connection), 46 | leave: make(chan *Connection), 47 | send: make(chan *message, roomSendChannelSize), 48 | } 49 | // Run the message loop 50 | go r.run() 51 | // Return pointer 52 | return &r 53 | } 54 | 55 | // Starts the message loop of this room, should only be run once and in a different routine. 56 | func (r *Room) run() { 57 | for { 58 | select { 59 | // Join 60 | case conn := <-r.join: 61 | r.members[conn] = true 62 | // Leave 63 | case conn := <-r.leave: 64 | if _, ok := r.members[conn]; ok { // If member exists, delete it 65 | delete(r.members, conn) 66 | } 67 | // Send 68 | case message := <-r.send: 69 | for conn := range r.members { // For every connection try to send 70 | select { 71 | case conn.send <- message: 72 | default: // If sending failed, delete member 73 | delete(r.members, conn) 74 | } 75 | } 76 | // Stop 77 | case <-r.stop: 78 | return 79 | } 80 | } 81 | } 82 | 83 | // Stops and shutsdown the room. After calling Stop the room can be safely deleted. 84 | func (r *Room) Stop() { 85 | r.stop <- true 86 | } 87 | 88 | // Join adds the provided connection to the room. 89 | func (r *Room) Join(conn *Connection) { 90 | r.join <- conn 91 | } 92 | 93 | // Leave removes the connection from the room, if it previously was member of the room. 94 | func (r *Room) Leave(conn *Connection) { 95 | r.leave <- conn 96 | } 97 | 98 | // Emits message event to all members of the room. 99 | func (r *Room) Emit(event string, data interface{}) { 100 | r.send <- &message{ 101 | event: event, 102 | data: data, 103 | } 104 | } 105 | -------------------------------------------------------------------------------- /room_manager.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2013 Niklas Voss 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package golem 20 | 21 | const ( 22 | roomManagerCreateEvent = "create" 23 | roomManagerRemoveEvent = "remove" 24 | CloseConnectionOnLastRoomLeft = 1 25 | ) 26 | 27 | // Room request information holding name of the room and the connection, which requested. 28 | type roomReq struct { 29 | // Name of the lobby the request goes to. 30 | name string 31 | // Reference to the connection, which requested. 32 | conn *Connection 33 | } 34 | 35 | // Room messages contain information about to which room it is being send and the data being send. 36 | type roomMsg struct { 37 | // Name of the room the message goes to. 38 | to string 39 | // Data being send to specified room. 40 | msg *message 41 | } 42 | 43 | // Wrapper for normal lobbies to add a member counter. 44 | type managedRoom struct { 45 | // Reference to room. 46 | room *Room 47 | // Member-count to allow removing of empty lobbies. 48 | count uint 49 | } 50 | 51 | // Structure containing all necessary informations and options of 52 | // connection for the room manager instance 53 | type connectionInfo struct { 54 | rooms map[string]bool 55 | options uint32 56 | } 57 | 58 | type connectionInfoReq struct { 59 | conn *Connection 60 | options uint32 61 | overwrite bool 62 | } 63 | 64 | // Constructor for connection info struct 65 | func newConnectionInfo() *connectionInfo { 66 | return &connectionInfo{ 67 | rooms: make(map[string]bool), 68 | options: 0, 69 | } 70 | } 71 | 72 | // Handles any count of lobbies by keys. Currently only strings are supported as keys (room names). 73 | // As soon as generics are supported any key should be able to be used. The methods are used similar to 74 | // single rooms but preceded by the key. 75 | type RoomManager struct { 76 | // Map of connections mapped to lobbies joined; necessary for leave all/clean up functionality. 77 | members map[*Connection]*connectionInfo 78 | // Map of all managed lobbies with their names as keys. 79 | rooms map[string]*managedRoom 80 | // Channel of join requests. 81 | join chan *roomReq 82 | // Channel of leave requests. 83 | leave chan *roomReq 84 | // Channel of leave all requests, essentially cleaning up every trace of the specified connection. 85 | leaveAll chan *Connection 86 | // Channel of room destruction requests 87 | destroy chan string 88 | // Channel of connection option requests 89 | options chan *connectionInfoReq 90 | // Channel of messages associated with this room manager 91 | send chan *roomMsg 92 | // Stop signal channel 93 | stop chan bool 94 | // Room creation and removal callbacks 95 | callbackRoomCreation func(string) 96 | callbackRoomRemoval func(string) 97 | } 98 | 99 | // NewRoomManager initialises a new instance and returns the a pointer to it. 100 | func NewRoomManager() *RoomManager { 101 | // Create instance. 102 | rm := RoomManager{ 103 | members: make(map[*Connection]*connectionInfo), 104 | rooms: make(map[string]*managedRoom), 105 | join: make(chan *roomReq), 106 | leave: make(chan *roomReq), 107 | leaveAll: make(chan *Connection), 108 | destroy: make(chan string), 109 | options: make(chan *connectionInfoReq), 110 | send: make(chan *roomMsg, roomSendChannelSize), 111 | stop: make(chan bool), 112 | callbackRoomCreation: func(string) {}, 113 | callbackRoomRemoval: func(string) {}, 114 | } 115 | // Start message loop in new routine. 116 | go rm.run() 117 | // Return reference to this room manager. 118 | return &rm 119 | } 120 | 121 | // Helper function to leave a room by name. If specified room has 122 | // no members after leaving, it will be cleaned up. 123 | func (rm *RoomManager) leaveRoomByName(name string, conn *Connection) { 124 | if m, ok := rm.rooms[name]; ok { // Continue if getting the room was ok. 125 | if c, ok := rm.members[conn]; ok { // Continue if connection has map of joined lobbies. 126 | if _, ok := c.rooms[name]; ok { // Continue if connection actually joined specified room. 127 | m.room.leave <- conn 128 | m.count-- 129 | delete(c.rooms, name) 130 | if len(c.rooms) == 0 && (c.options&CloseConnectionOnLastRoomLeft) == CloseConnectionOnLastRoomLeft { 131 | delete(rm.members, conn) 132 | conn.Close() 133 | } 134 | if m.count == 0 { // Get rid of room if it is empty 135 | m.room.Stop() 136 | delete(rm.rooms, name) 137 | go rm.callbackRoomRemoval(name) 138 | } 139 | } 140 | } 141 | } 142 | } 143 | 144 | // Run should always be executed in a new goroutine, because it contains the 145 | // message loop. 146 | func (rm *RoomManager) run() { 147 | for { 148 | select { 149 | // Join 150 | case req := <-rm.join: 151 | m, ok := rm.rooms[req.name] 152 | if !ok { // If room was not found for join request, create it! 153 | m = &managedRoom{ 154 | room: NewRoom(), 155 | count: 1, // start with count 1 for first user 156 | } 157 | rm.rooms[req.name] = m 158 | go rm.callbackRoomCreation(req.name) 159 | } else { // If room exists increase count and join. 160 | m.count++ 161 | } 162 | m.room.join <- req.conn 163 | c, ok := rm.members[req.conn] 164 | if !ok { // If room association map for connection does not exist, create it! 165 | c = newConnectionInfo() 166 | rm.members[req.conn] = c 167 | } 168 | c.rooms[req.name] = true // Flag this room on members room map. 169 | // Leave 170 | case req := <-rm.leave: 171 | rm.leaveRoomByName(req.name, req.conn) 172 | // Leave all 173 | case conn := <-rm.leaveAll: 174 | if c, ok := rm.members[conn]; ok { 175 | for name := range c.rooms { // Iterate over all lobbies this connection joined and leave them. 176 | rm.leaveRoomByName(name, conn) 177 | } 178 | delete(rm.members, conn) // Remove map of joined lobbies 179 | } 180 | case name := <-rm.destroy: 181 | if m, ok := rm.rooms[name]; ok { 182 | // This should result inthe room being stopped/destroyed when the last 183 | // connection is dropped 184 | for conn := range m.room.members { 185 | rm.leaveRoomByName(name, conn) 186 | } 187 | } 188 | case req := <-rm.options: 189 | c, ok := rm.members[req.conn] 190 | if !ok { // If room association map for connection does not exist, create it! 191 | c = newConnectionInfo() 192 | rm.members[req.conn] = c 193 | } 194 | if req.overwrite { 195 | c.options = req.options 196 | } else { 197 | c.options = req.options | c.options 198 | } 199 | // Send 200 | case rMsg := <-rm.send: 201 | if m, ok := rm.rooms[rMsg.to]; ok { // If room exists, get it and send data to it. 202 | m.room.send <- rMsg.msg 203 | } 204 | // Stop 205 | case <-rm.stop: 206 | for k, m := range rm.rooms { // Stop all lobbies! 207 | m.room.Stop() 208 | delete(rm.rooms, k) 209 | } 210 | return 211 | } 212 | } 213 | } 214 | 215 | func (rm *RoomManager) SetConnectionOptions(conn *Connection, options uint32, overwrite bool) { 216 | rm.options <- &connectionInfoReq{ 217 | conn: conn, 218 | options: options, 219 | overwrite: overwrite, 220 | } 221 | } 222 | 223 | // Join adds the connection to the specified room. 224 | func (rm *RoomManager) Join(name string, conn *Connection) { 225 | rm.join <- &roomReq{ 226 | name: name, 227 | conn: conn, 228 | } 229 | } 230 | 231 | // Leave removes the connection from the specified room. 232 | func (rm *RoomManager) Leave(name string, conn *Connection) { 233 | rm.leave <- &roomReq{ 234 | name: name, 235 | conn: conn, 236 | } 237 | } 238 | 239 | // LeaveAll removes the connection from all joined rooms of this manager. 240 | // This is an important step and should be called OnClose for all connections, that could have joined 241 | // a room of the manager, to keep the member reference count of the manager accurate. 242 | func (rm *RoomManager) LeaveAll(conn *Connection) { 243 | rm.leaveAll <- conn 244 | } 245 | 246 | // Emit a message, that can be fetched using the golem client library. The provided 247 | // data interface will be automatically marshalled according to the active protocol. 248 | func (rm *RoomManager) Emit(to string, event string, data interface{}) { 249 | rm.send <- &roomMsg{ 250 | to: to, 251 | msg: &message{ 252 | event: event, 253 | data: data, 254 | }, 255 | } 256 | } 257 | 258 | // Stop the message loop and shutsdown the manager. It is safe to delete the instance afterwards. 259 | func (rm *RoomManager) Stop() { 260 | rm.stop <- true 261 | } 262 | 263 | // Remove connections from a particular room and delete the room 264 | func (rm *RoomManager) Destroy(name string) { 265 | rm.destroy <- name 266 | } 267 | 268 | // The room manager can emit several events. At the moment there are two events: 269 | // "create" - triggered if a room was created and 270 | // "remove" - triggered when a room was removed because of insufficient users 271 | // For both the callback needs to be of the type func(string) where the argument 272 | func (rm *RoomManager) On(eventName string, callback interface{}) { 273 | switch eventName { 274 | case roomManagerCreateEvent: 275 | rm.callbackRoomCreation = callback.(func(string)) 276 | case roomManagerRemoveEvent: 277 | rm.callbackRoomRemoval = callback.(func(string)) 278 | } 279 | } 280 | -------------------------------------------------------------------------------- /router.go: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | Copyright 2013 Niklas Voss 4 | 5 | Licensed under the Apache License, Version 2.0 (the "License"); 6 | you may not use this file except in compliance with the License. 7 | You may obtain a copy of the License at 8 | 9 | http://www.apache.org/licenses/LICENSE-2.0 10 | 11 | Unless required by applicable law or agreed to in writing, software 12 | distributed under the License is distributed on an "AS IS" BASIS, 13 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | See the License for the specific language governing permissions and 15 | limitations under the License. 16 | 17 | */ 18 | 19 | package golem 20 | 21 | import ( 22 | "errors" 23 | "github.com/gorilla/websocket" 24 | "log" 25 | "net/http" 26 | "reflect" 27 | ) 28 | 29 | // Router handles multiplexing of incoming messenges by typenames/events. 30 | // Initially a router uses heartbeats and the default protocol. 31 | type Router struct { 32 | // Map of callbacks for event types. 33 | callbacks map[string]func(*Connection, interface{}) 34 | // Protocol extensions 35 | extensions map[reflect.Type]reflect.Value 36 | // Function being called if connection is closed. 37 | closeFunc func(*Connection) 38 | // Function called after handshake when a WebSocket connection 39 | // was succesfully established. 40 | connectionFunc func(*Connection, *http.Request) 41 | // Function verifying handshake. 42 | handshakeFunc func(http.ResponseWriter, *http.Request) bool 43 | // Active protocol 44 | protocol Protocol 45 | // Flag to enable or disable heartbeats 46 | useHeartbeats bool 47 | // 48 | connExtensionConstructor reflect.Value 49 | // If set, the values the Origin header will be checked against and access is only allowed 50 | // on a match; otherwise no Origin checking is performed. *This overrides the 51 | // Access-Control-Allow-Origin header!* 52 | Origins []string 53 | } 54 | 55 | // NewRouter intialises a new instance and returns the pointer. 56 | func NewRouter() *Router { 57 | // Tries to run hub, if already running nothing will happen. 58 | hub.run() 59 | // Returns pointer to instance. 60 | return &Router{ 61 | callbacks: make(map[string]func(*Connection, interface{})), 62 | extensions: make(map[reflect.Type]reflect.Value), 63 | closeFunc: func(*Connection) {}, // Empty placeholder close function. 64 | connectionFunc: func(*Connection, *http.Request) {}, 65 | handshakeFunc: func(http.ResponseWriter, *http.Request) bool { return true }, // Handshake always allowed. 66 | protocol: initialProtocol, 67 | useHeartbeats: true, 68 | connExtensionConstructor: defaultConnectionExtension, 69 | Origins: make([]string, 0), 70 | } 71 | } 72 | 73 | // Handler creates a handler function for this router, that can be used with the 74 | // http-package to handle WebSocket-Connections. 75 | func (router *Router) Handler() func(http.ResponseWriter, *http.Request) { 76 | return func(w http.ResponseWriter, r *http.Request) { 77 | // Check if method used was GET. 78 | if r.Method != "GET" { 79 | http.Error(w, "Method not allowed", 405) 80 | return 81 | } 82 | 83 | // Disallow cross-origin connections. 84 | if len(router.Origins) > 0 { 85 | originFound := false 86 | for _, origin := range router.Origins { 87 | if r.Header.Get("Origin") == origin { 88 | originFound = true 89 | break 90 | } 91 | } 92 | if !originFound { 93 | http.Error(w, "Origin not allowed", 403) 94 | return 95 | } 96 | } else { 97 | if len(r.Header.Get("Access-Control-Allow-Origin")) > 0 { 98 | allowedOrigin := r.Header.Get("Access-Control-Allow-Origin") 99 | if allowedOrigin != "*" { 100 | if r.URL.Scheme+"://"+r.Host != allowedOrigin { 101 | http.Error(w, "Origin not allwed", 403) 102 | return 103 | } 104 | } 105 | } 106 | } 107 | 108 | // Check if handshake callback verifies upgrade. 109 | if !router.handshakeFunc(w, r) { 110 | http.Error(w, "Authorization failed", 403) 111 | return 112 | } 113 | 114 | // Upgrade websocket connection. 115 | protocols := websocket.Subprotocols(r) 116 | var responseHeader http.Header = nil 117 | if len(protocols) > 0 { 118 | responseHeader = http.Header{"Sec-Websocket-Protocol": {protocols[0]}} 119 | } 120 | socket, err := websocket.Upgrade(w, r, responseHeader, 1024, 1024) 121 | // Check if handshake was successful 122 | if _, ok := err.(websocket.HandshakeError); ok { 123 | http.Error(w, "Not a websocket handshake", 400) 124 | return 125 | } else if err != nil { 126 | log.Println(err) 127 | return 128 | } 129 | 130 | // Create the connection. 131 | conn := newConnection(socket, router) 132 | // 133 | if router.connExtensionConstructor.IsValid() { 134 | conn.extend(router.connExtensionConstructor.Call([]reflect.Value{reflect.ValueOf(conn)})[0].Interface()) 135 | } 136 | 137 | // Connection established with possible extension, so callback 138 | router.connectionFunc(conn, r) 139 | 140 | // And start reading and writing routines. 141 | conn.run() 142 | } 143 | } 144 | 145 | // The On-function adds callbacks by name of the event, that should be handled. 146 | // For type T the callback would be of type: 147 | // func (*golem.Connection, *T) 148 | // Type T can be any type. By default golem tries to unmarshal json into the 149 | // specified type. If a custom protocol is used, it will be used instead to process the data. 150 | // If type T is registered to use a protocol extension, it will be used instead. 151 | // If type T is interface{} the interstage data of the active protocol will be directly forwarded! 152 | // (Note: the golem wiki has a whole page about this function) 153 | func (router *Router) On(name string, callback interface{}) { 154 | 155 | callbackValue := reflect.ValueOf(callback) 156 | callbackType := reflect.TypeOf(callback) 157 | if router.connExtensionConstructor.IsValid() { 158 | extType := router.connExtensionConstructor.Type().Out(0) 159 | if callbackType.In(0) == extType { 160 | // EXTENSION TYPE 161 | 162 | // NO DATA 163 | if callbackType.NumIn() == 1 { 164 | router.callbacks[name] = func(conn *Connection, data interface{}) { 165 | args := []reflect.Value{reflect.ValueOf(conn.extension)} 166 | callbackValue.Call(args) 167 | } 168 | return 169 | } 170 | 171 | // INTERFACE 172 | if callbackType.In(1).Kind() == reflect.Interface { 173 | router.callbacks[name] = func(conn *Connection, data interface{}) { 174 | args := []reflect.Value{reflect.ValueOf(conn.extension), reflect.ValueOf(data)} 175 | callbackValue.Call(args) 176 | } 177 | return 178 | } 179 | 180 | // PROTOCOL EXTENSION 181 | if parser, ok := router.extensions[callbackType.In(1)]; ok { 182 | router.callbacks[name] = func(conn *Connection, data interface{}) { 183 | if result := parser.Call([]reflect.Value{reflect.ValueOf(data)}); result[1].Bool() { 184 | args := []reflect.Value{reflect.ValueOf(conn.extension), result[0]} 185 | callbackValue.Call(args) 186 | } 187 | } 188 | return 189 | } 190 | 191 | // PROTOCOL 192 | callbackDataElem := callbackType.In(1).Elem() 193 | router.callbacks[name] = func(conn *Connection, data interface{}) { 194 | result := reflect.New(callbackDataElem) 195 | 196 | err := router.protocol.Unmarshal(data, result.Interface()) 197 | if err == nil { 198 | args := []reflect.Value{reflect.ValueOf(conn.extension), result} 199 | callbackValue.Call(args) 200 | } else { 201 | // TODO: Proper debug output! 202 | } 203 | } 204 | return 205 | } 206 | } else { 207 | // DEFAULT TYPE 208 | 209 | // NO DATA 210 | if reflect.TypeOf(callback).NumIn() == 1 { 211 | router.callbacks[name] = func(conn *Connection, data interface{}) { 212 | callback.(func(*Connection))(conn) 213 | } 214 | return 215 | } 216 | 217 | // INTERFACE 218 | if cb, ok := callback.(func(*Connection, interface{})); ok { 219 | router.callbacks[name] = cb 220 | return 221 | } 222 | 223 | // PROTOCOL EXTENSION 224 | if parser, ok := router.extensions[callbackType.In(1)]; ok { 225 | router.callbacks[name] = func(conn *Connection, data interface{}) { 226 | if result := parser.Call([]reflect.Value{reflect.ValueOf(data)}); result[1].Bool() { 227 | args := []reflect.Value{reflect.ValueOf(conn), result[0]} 228 | callbackValue.Call(args) 229 | } 230 | } 231 | return 232 | } 233 | 234 | // PROTOCOL 235 | callbackDataElem := callbackType.In(1).Elem() 236 | router.callbacks[name] = func(conn *Connection, data interface{}) { 237 | result := reflect.New(callbackDataElem) 238 | 239 | err := router.protocol.Unmarshal(data, result.Interface()) 240 | if err == nil { 241 | args := []reflect.Value{reflect.ValueOf(conn), result} 242 | callbackValue.Call(args) 243 | } else { 244 | // TODO: Proper debug output! 245 | } 246 | } 247 | return 248 | } 249 | } 250 | 251 | // Unpacks incoming data and forwards it to callback. 252 | func (router *Router) processMessage(conn *Connection, in []byte) { 253 | if name, data, err := router.protocol.Unpack(in); err == nil { 254 | if callback, ok := router.callbacks[name]; ok { 255 | callback(conn, data) 256 | } 257 | } // TODO: else error logging? 258 | 259 | defer recover() 260 | } 261 | 262 | // OnClose sets the callback, that is called when the connection is closed. 263 | // It accept function of the type func(*Connection) by default or functions 264 | // taking extended connection types if previously registered. 265 | func (router *Router) OnClose(callback interface{}) error { //func(*Connection)) { 266 | if cb, ok := callback.(func(*Connection)); ok { 267 | router.closeFunc = cb 268 | } else { 269 | if router.connExtensionConstructor.IsValid() { 270 | callbackValue := reflect.ValueOf(callback) 271 | extType := router.connExtensionConstructor.Type().Out(0) 272 | if reflect.TypeOf(callback).In(0) == extType { 273 | router.closeFunc = func(conn *Connection) { 274 | callbackValue.Call([]reflect.Value{reflect.ValueOf(conn.extension)}) 275 | } 276 | } else { 277 | return errors.New("OnClose cannot accept a callback of the type " + reflect.TypeOf(callback).String() + ".") 278 | } 279 | } else { 280 | return errors.New("OnClose can only accept functions of the type func(*Connection), if no extension is registered.") 281 | } 282 | } 283 | return nil 284 | } 285 | 286 | // OnConnection sets the callback, that is called when a websocket connection 287 | // was successfully established, it is therefore called after the handshake. 288 | // It accept function of the type func(*Connection, *http.Request) by default or functions 289 | // taking extended connection types if previously registered. 290 | // The http.Request object can be used for connection metadata information. 291 | func (router *Router) OnConnect(callback interface{}) error { //func(*Connection)) { 292 | if cb, ok := callback.(func(*Connection, *http.Request)); ok { 293 | router.connectionFunc = cb 294 | } else { 295 | if router.connExtensionConstructor.IsValid() { 296 | callbackValue := reflect.ValueOf(callback) 297 | extType := router.connExtensionConstructor.Type().Out(0) 298 | if reflect.TypeOf(callback).In(0) == extType { 299 | router.connectionFunc = func(conn *Connection, hr *http.Request) { 300 | callbackValue.Call([]reflect.Value{reflect.ValueOf(conn.extension), reflect.ValueOf(hr)}) 301 | } 302 | } else { 303 | return errors.New("OnConnection cannot accept a callback of the type " + reflect.TypeOf(callback).String() + ".") 304 | } 305 | } else { 306 | return errors.New("OnConnection can only accept functions of the type func(*Connection), if no extension is registered.") 307 | } 308 | } 309 | return nil 310 | } 311 | 312 | // OnHandshake sets the callback for handshake verfication. 313 | // If the handshake function returns false the request will not be upgraded. 314 | // The http.Request object will be passed into OnConnect as well. 315 | func (router *Router) OnHandshake(callback func(http.ResponseWriter, *http.Request) bool) { 316 | router.handshakeFunc = callback 317 | } 318 | 319 | // The AddProtocolExtension-function allows adding of custom parsers for custom types. For any Type T 320 | // the parser function would look like this: 321 | // func (interface{}) (T, bool) 322 | // The interface's type is depending on the interstage product of the active protocol, by default 323 | // for the JSON-based protocol it is []byte and therefore the function could be simplified to: 324 | // func ([]byte) (T, bool) 325 | // Or in general if P is the interstage product: 326 | // func (*P) (T, bool) 327 | // The boolean return value is necessary to verify if parsing was successful. 328 | // All On-handling function accepting T as input data will now automatically use the custom 329 | // extension. For an example see the example_data.go file in the example repository. 330 | func (router *Router) AddProtocolExtension(extensionFunc interface{}) error { 331 | extensionValue := reflect.ValueOf(extensionFunc) 332 | extensionType := extensionValue.Type() 333 | 334 | if extensionType.NumIn() != 1 { 335 | return errors.New("Cannot add function(" + extensionType.String() + ") as parser: To many arguments!") 336 | } 337 | if extensionType.NumOut() != 2 { 338 | return errors.New("Cannot add function(" + extensionType.String() + ") as parser: Wrong number of return values!") 339 | } 340 | if extensionType.Out(1).Kind() != reflect.Bool { 341 | return errors.New("Cannot add function(" + extensionType.String() + ") as parser: Second return value is not Bool!") 342 | } 343 | 344 | router.extensions[extensionType.Out(0)] = extensionValue 345 | 346 | return nil 347 | } 348 | 349 | // SetConnectionExtension sets the extension for this router. A connection extension is an extended connection structure, that afterwards can be 350 | // used by On-handlers as well (use-cases: add persistent storage to connection, additional methods et cetera). 351 | // The SetConnectionExtension function takes the constructor of the custom format to be able to use and create it on 352 | // connection to the router. 353 | // For type E the constructor needs to fulfil the following requirements: 354 | // func NewE(conn *Connection) *E 355 | // Afterwards On-handler can us this extended type: 356 | // router.On(func (extendedConn E, data Datatype) { ... }) 357 | // For an example have a look at the example repository and have a look at the 'example_connection_extension.go'. 358 | func (router *Router) SetConnectionExtension(constructor interface{}) { 359 | router.connExtensionConstructor = reflect.ValueOf(constructor) 360 | } 361 | 362 | // SetProtocol sets the protocol of the router to the supplied implementation of the Protocol interface. 363 | func (router *Router) SetProtocol(protocol Protocol) { 364 | router.protocol = protocol 365 | } 366 | 367 | // 368 | 369 | // SetHeartbeat activates or deactivates the heartbeat depending on the flag parameter. By default heartbeats are activated. 370 | func (router *Router) SetHeartbeat(flag bool) { 371 | router.useHeartbeats = flag 372 | } 373 | --------------------------------------------------------------------------------