├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── client-script.go ├── client.go ├── clientOps.go ├── doc.go ├── examples ├── groups │ ├── index.html │ └── main.go ├── shape-move │ ├── index.html │ └── main.go └── time-push │ ├── index.html │ └── main.go ├── exchange.go ├── groupOps.go ├── longpoll-transport.go ├── operation.go ├── relay.go ├── transport.go ├── util.go └── websocket-transport.go /.gitignore: -------------------------------------------------------------------------------- 1 | *.swp 2 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## RelayR changelog 2 | 3 | #### v0.2.1 - v0.3.0 4 | 5 | * FEATURE: Added Long Polling transport - allowing all browsers that support AJAX requests to work with RelayR. RelayR will test 6 | for WebSocket support and if not found, will fall back to Long Polling. 7 | * BUGFIX: Removed renegotiation bug. 8 | * BUGFIX: Stop `RelayRConnection.ready` being called more than once. 9 | 10 | ---------------- 11 | 12 | #### v0.2.0 - v0.2.1 13 | 14 | * Added `clientScript` caching variable, which allows the RelayR client-side script to be cached in a `[]byte` slice and served each time. 15 | * Added `DisableScriptCache()` package-level function to disable the above functionality and regenerate the script each page refresh (mostly for debug purposes). 16 | 17 | ---------------- 18 | 19 | #### v0.1.0 - v0.2.0 20 | 21 | There are are four necessary breaking changes in the update from 0.1.0 to 0.2.0 to make it more "Go-like" and consumer friendly. 22 | 23 | * The package name now has a lowercase r; "relayr" instead of "relayR". This was one of the only gripes from the community about this package. 24 | * You no longer need to embed `*relayr.Relay` .. but you now need to have all of your relay methods accept a `*relayr.Relay` as their first argument. 25 | * Groups are now an object in themselves and no longer "hang off" of the `Clients` property of a Relay. The examples have been updated to reflect this. 26 | * relayr.Exchange now implements `ServeHTTP`, which means it can now handle a route directly, instead of using `relayr.Handle` .. you can use `http.Handle`. 27 | 28 | The rest should _mostly_ work as it did. I have completely re-written most of the underlying code for easier maintenance and better documentation. The public API now has better documentation and should make a lot more sense. 29 | 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## RelayR 2 | 3 | RelayR is a Go package that provides easy-to-use real time communication APIs for Go web applications. 4 | 5 | #### Current version: 0.3.0 6 | 7 | Please see CHANGELOG.md for details about the changes between versions. 8 | 9 | ### Installation 10 | 11 | #### IMPORTANT: 12 | 13 | RelayR relies on the [Gorilla WebSocket package](https://github.com/gorilla/websocket) for WebSocket support. Please head over to that repository, give it a star, and ``go get` it into your `GOPATH`. 14 | 15 | RelayR itself however, will fall back to Long Polling for any browsers that do not support Web Sockets (you just need the above package so that your server supports Web Sockets). 16 | 17 | #### Installing RelayR 18 | 19 | After you have installed the [Gorilla WebSocket package](https://github.com/gorilla/websocket), you can run the following: 20 | 21 | go get -u github.com/simon-whitehead/relayr 22 | 23 | ### Examples 24 | 25 | The `/examples` directory contains three examples. 26 | 27 | The first one is a simple Server -> Client timestamp push. The server will push the current time down to all connected clients every second. 28 | 29 | It looks like this: 30 | 31 | ![relayr-time-push](https://cloud.githubusercontent.com/assets/2499070/6539845/2a2d7d0a-c4d5-11e4-8ace-9f619769dca9.gif) 32 | 33 | The second one is a replica of the famous SignalR sample, "High-Frequency Realtime with SignalR" where a shape can be dragged around a browser and broadcast to all clients. 34 | 35 | It looks like this: 36 | 37 | ![relayr-shape-move](https://cloud.githubusercontent.com/assets/2499070/6540051/ac091b60-c4dd-11e4-9115-9debcd836136.gif) 38 | 39 | The third one demonstrates Groups and membership. It allows clients to subscribe to groups and receive notifications that are pushed to groups they are subscribed to. 40 | 41 | ### Project status 42 | 43 | This is very much a work in progress - some might say, pre-alpha. The code is horrible .. but it works. I am opening it up to the world early for feedback and contributions (in any form). 44 | 45 | ### Contributing 46 | 47 | Please! Fork away .. improve it .. create a PR .. whatever you want to do. I am open to any and all help. 48 | 49 | ### Licence 50 | 51 | This code is released under the Apache 2.0 licence. 52 | -------------------------------------------------------------------------------- /client-script.go: -------------------------------------------------------------------------------- 1 | /* 2 | * 3 | * This file contains client side Javascript that is rendered 4 | * when a client hits the RelayR route with a GET request. 5 | * 6 | */ 7 | 8 | package relayr 9 | 10 | const connectionClassScript = ` 11 | 12 | var RelayRConnection = {}; 13 | 14 | RelayRConnection = (function() { 15 | var readyCalled = false; 16 | var web, transport; 17 | var route = '%v'; 18 | transport = { 19 | websocket: { 20 | connect: function(c) { 21 | var s = this; 22 | s.socket = new WebSocket("ws://" + window.location.host + route + "/ws?connectionId=" + transport.ConnectionId); 23 | s.socket.onclose = function(evt) { 24 | setTimeout(function() { 25 | web.n(); // renegotiate 26 | }, 2000); 27 | }; 28 | 29 | s.socket.onmessage = function(evt) { 30 | c(evt.data); 31 | }; 32 | 33 | s.socket.onerror = function(evt) { 34 | setTimeout(function() { 35 | s.connect(cId, c); 36 | }); 37 | }; 38 | 39 | s.socket.onopen = function(evt) { 40 | if (!readyCalled) { 41 | RelayRConnection.r(); 42 | readyCalled = true; 43 | } 44 | }; 45 | }, 46 | send: function(data) { 47 | var s = this; 48 | s.socket.send(data); 49 | } 50 | }, 51 | longpoll: { 52 | connect: function(c) { 53 | if (!readyCalled) { 54 | RelayRConnection.r(); 55 | readyCalled = true; 56 | } 57 | var retry; 58 | retry = function() { 59 | web.gj(route + '/longpoll?connectionId=' + transport.ConnectionId + '&_=' + new Date().getTime(), function(data) { 60 | if (data.responseText) { 61 | var reconn = JSON.parse(data.responseText); 62 | if (reconn.Z) { 63 | web.n(); 64 | } else { 65 | c(data); 66 | retry(); 67 | } 68 | } else { 69 | web.n(); 70 | } 71 | }); 72 | }; 73 | 74 | retry(); 75 | }, 76 | send: function(data) { 77 | var s = this; 78 | web.p(route + '/call?connectionId=' + transport.ConnectionId + '&_=' + new Date().getTime(), data, null, "json", null); 79 | } 80 | } 81 | }; 82 | web = (function() { 83 | return { 84 | x: function() { 85 | var xd; 86 | 87 | if (window.XMLHttpRequest) { 88 | xd = new XMLHttpRequest(); 89 | } 90 | else { 91 | xd = new ActiveXObject("Microsoft.XMLHTTP"); 92 | } 93 | 94 | return xd; 95 | }, 96 | g: function(u, c) { 97 | var s = this; 98 | 99 | var xd = s.x(); 100 | 101 | xd.open('GET', u, true); 102 | 103 | xd.onreadystatechange = function() { 104 | if (xd.readyState === 4 && xd.status === 200) { 105 | c(xd); 106 | } 107 | }; 108 | 109 | xd.send(); 110 | }, 111 | gj: function(u, c) { 112 | var s = this; 113 | 114 | var xd = s.x(); 115 | 116 | xd.open('GET', u, true); 117 | xd.setRequestHeader("Content-type", "application/json"); 118 | 119 | xd.onreadystatechange = function() { 120 | if (xd.readyState === 4) { 121 | if (xd.status === 200) { 122 | c(xd); 123 | } 124 | } 125 | }; 126 | 127 | xd.send(); 128 | }, 129 | p: function(u, d, c, t, e) { 130 | var s = this; 131 | 132 | var xd = s.x(); 133 | 134 | xd.open('POST', u, true); 135 | xd.setRequestHeader("Content-type", "application/" + t); 136 | 137 | xd.onreadystatechange = function() { 138 | if (xd.readyState === 4) { 139 | if (xd.status === 200) { 140 | if (c) { 141 | c(xd); 142 | } 143 | } 144 | } 145 | }; 146 | 147 | xd.onerror = function() { 148 | if (e) { 149 | e(xd); 150 | } 151 | }; 152 | 153 | xd.send(d); 154 | 155 | window.onbeforeunload = function() { 156 | delete xd; 157 | xd = null; 158 | }; 159 | }, 160 | t: function() { 161 | if (!!window.WebSocket) { 162 | return "websocket"; 163 | } else { 164 | return "longpoll"; 165 | } 166 | 167 | // TODO: Implement SSE Circuit 168 | /*if (typeof EventSource !== 'undefined') { 169 | return "SSE"; 170 | }*/ 171 | }, 172 | n: function() { 173 | var s = this; 174 | var t = s.t(); 175 | web.p(route + "/negotiate?_=" + new Date().getTime(), JSON.stringify({ t: t }), function(result) { 176 | var obj = JSON.parse(result.responseText); 177 | transport.ConnectionId = obj.ConnectionID; 178 | setTimeout(function() { 179 | transport[t].connect(function(data) { 180 | var cobj; 181 | if (data.responseText && data.status && data.responseXML) { 182 | cobj = JSON.parse(data.responseText); 183 | } else { 184 | if (data.responseText == "") return; 185 | cobj = JSON.parse(data); 186 | } 187 | var lobj = RelayR[cobj.R].client; 188 | var args = []; 189 | for (var i = 0; i < cobj.A.length; i++) { 190 | args.push(cobj.A[i]); 191 | } 192 | lobj[cobj.M].apply(lobj||window, args); 193 | }); 194 | }, 0); 195 | }, "json", 196 | function(result) { 197 | // error .. try again 198 | setTimeout(function() { 199 | s.n(); 200 | }, 2000); 201 | }); 202 | } 203 | }; 204 | })(); 205 | 206 | return { 207 | ready: function(r) { 208 | RelayRConnection.r = r; 209 | 210 | web.n(); 211 | }, 212 | callServer: function(r, f, a) { 213 | transport[web.t()].send(JSON.stringify({ S: true, C: transport.ConnectionId, R: r, M: f, A: a})); 214 | } 215 | }; 216 | })(); 217 | 218 | ` 219 | 220 | const relayClassBegin = ` 221 | 222 | var RelayR = (function() { 223 | return { 224 | 225 | ` 226 | 227 | const relayBegin = ` 228 | 229 | %v: { 230 | 231 | client: {}, 232 | 233 | server: { 234 | 235 | ` 236 | 237 | // {0} == function name 238 | // {1} == Relay name 239 | // {2} == function name 240 | const relayMethod = ` 241 | 242 | %v: function() { 243 | RelayRConnection.callServer('%v', '%v', Array.prototype.slice.call(arguments)); 244 | }, 245 | 246 | ` 247 | 248 | const relayEnd = ` 249 | 250 | }, 251 | 252 | }, 253 | 254 | ` 255 | 256 | const relayClassEnd = ` 257 | 258 | }; 259 | })(); 260 | 261 | ` 262 | -------------------------------------------------------------------------------- /client.go: -------------------------------------------------------------------------------- 1 | package relayr 2 | 3 | type client struct { 4 | ConnectionID string 5 | exchange *Exchange 6 | transport Transport 7 | } 8 | 9 | type clientMessage struct { 10 | Relay string `json:"R"` 11 | Function string `json:"F"` 12 | Arguments string `json:"A"` 13 | } 14 | -------------------------------------------------------------------------------- /clientOps.go: -------------------------------------------------------------------------------- 1 | package relayr 2 | 3 | // ClientOperations provides helper methods for 4 | // interacting with Clients connected to a Relay. 5 | type ClientOperations struct { 6 | e *Exchange 7 | relay *Relay 8 | } 9 | 10 | // All invokes a client side method on all clients for the 11 | // given relay. 12 | func (c *ClientOperations) All(fn string, args ...interface{}) { 13 | c.e.callGroupMethod(c.relay, "Global", fn, args...) 14 | } 15 | 16 | // Others invokes a client side method on all clients except the 17 | // one who calls it. 18 | func (c *ClientOperations) Others(fn string, args ...interface{}) { 19 | c.e.callGroupMethodExcept(c.relay, "Global", fn, args...) 20 | } 21 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Package relayr provides high level functionality for 2 | // real-time web communication. It allows communication 3 | // between front-end clients and back-end servers via 4 | // easy-to-use constructs. 5 | package relayr 6 | -------------------------------------------------------------------------------- /examples/groups/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Groups 6 | 7 | 8 | 9 | 10 | 35 | 36 | 37 |

38 | Select a group below to toggle membership 39 |

40 |
41 | 42 | 43 |
44 | 45 | 46 | -------------------------------------------------------------------------------- /examples/groups/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | "net/http" 6 | "time" 7 | 8 | "github.com/simon-whitehead/relayR" 9 | ) 10 | 11 | var group int = 1 12 | 13 | type NotificationRelay struct { 14 | } 15 | 16 | func (nr NotificationRelay) SendNotification(relay *relayr.Relay, g string) { 17 | relay.Groups(g).Call("notificationReceive", "Notification for group "+g) 18 | } 19 | 20 | func (nr NotificationRelay) Subscribe(relay *relayr.Relay, g string) { 21 | relay.Groups(g).Add(relay.ConnectionID) 22 | } 23 | 24 | func (nr NotificationRelay) Unsubscribe(relay *relayr.Relay, g string) { 25 | relay.Groups(g).Remove(relay.ConnectionID) 26 | } 27 | 28 | func main() { 29 | exchange := relayr.NewExchange() 30 | exchange.RegisterRelay(NotificationRelay{}) 31 | 32 | go func() { 33 | for { 34 | select { 35 | case <-time.After(time.Second * 2): 36 | exchange.Relay(NotificationRelay{}).Call("SendNotification", fmt.Sprintf("Group %d", group)) 37 | if group == 1 { 38 | group = 2 39 | } else { 40 | group = 1 41 | } 42 | } 43 | } 44 | }() 45 | 46 | http.Handle("/relayr/", exchange) 47 | http.Handle("/", http.FileServer(http.Dir("."))) 48 | 49 | http.ListenAndServe(":8080", nil) 50 | } 51 | -------------------------------------------------------------------------------- /examples/shape-move/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Shape move 6 | 14 | 15 | 16 | 17 | 42 | 43 | 44 |
45 | 46 | 47 | -------------------------------------------------------------------------------- /examples/shape-move/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "net/http" 5 | 6 | "github.com/simon-whitehead/relayR" 7 | ) 8 | 9 | type ShapeRelay struct { 10 | } 11 | 12 | func (sr ShapeRelay) UpdateShape(relay *relayr.Relay, s map[string]interface{}) { 13 | relay.Clients.Others("shapeUpdated", s) // Only send to other clients 14 | } 15 | 16 | func main() { 17 | exchange := relayr.NewExchange() 18 | exchange.RegisterRelay(ShapeRelay{}) 19 | 20 | http.Handle("/relayr/", exchange) 21 | http.Handle("/", http.FileServer(http.Dir("."))) 22 | 23 | http.ListenAndServe(":8080", nil) 24 | } 25 | -------------------------------------------------------------------------------- /examples/time-push/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Time Push 6 | 7 | 14 | 15 | 16 |
17 | 18 | 19 | -------------------------------------------------------------------------------- /examples/time-push/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "net/http" 5 | "time" 6 | 7 | "github.com/simon-whitehead/relayR" 8 | ) 9 | 10 | type TimeRelay struct { 11 | } 12 | 13 | func (tr TimeRelay) PushTime(relay *relayr.Relay) { 14 | relay.Clients.All("timeUpdated", time.Now().Local().Format("Mon Jan 2 2006 03:04:05 PM")) 15 | } 16 | 17 | func main() { 18 | exchange := relayr.NewExchange() 19 | exchange.RegisterRelay(TimeRelay{}) 20 | 21 | go func() { 22 | for { 23 | select { 24 | case <-time.After(time.Second * 1): 25 | exchange.Relay(TimeRelay{}).Call("PushTime") 26 | } 27 | } 28 | }() 29 | 30 | http.Handle("/relayr/", exchange) 31 | http.Handle("/", http.FileServer(http.Dir("."))) 32 | http.ListenAndServe(":8080", nil) 33 | } 34 | -------------------------------------------------------------------------------- /exchange.go: -------------------------------------------------------------------------------- 1 | package relayr 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | "io" 8 | "net/http" 9 | "reflect" 10 | "strings" 11 | 12 | "github.com/gorilla/websocket" 13 | ) 14 | 15 | // ClientScriptFunc is a callback for altering the client side 16 | // generated Javascript. This can be used to minify/alter the 17 | // generated client-side RelayR library before it gets to the browser. 18 | var ClientScriptFunc func([]byte) []byte 19 | 20 | // A cache for the client script to avoid regenerating it every 21 | // single page load 22 | var clientScript []byte 23 | var cacheEnabled = true 24 | 25 | // DisableScriptCache forces the RelayR client-side script to 26 | // be regenerated on each request, rather than serving it from 27 | // an internal cache. 28 | func DisableScriptCache() { 29 | cacheEnabled = false 30 | } 31 | 32 | var upgrader = &websocket.Upgrader{ReadBufferSize: 1024, WriteBufferSize: 1024} 33 | 34 | type longPollServerCall struct { 35 | Server bool `json:"S"` 36 | Relay string `json:"R"` 37 | Method string `json:"M"` 38 | Arguments []interface{} `json:"A"` 39 | ConnectionID string `json:"C"` 40 | } 41 | 42 | // Exchange represents a hub where clients exchange information 43 | // via Relays. Relays registered with the Exchange expose methods 44 | // that can be invoked by clients. 45 | type Exchange struct { 46 | relays []Relay 47 | groups map[string][]*client 48 | transports map[string]Transport 49 | } 50 | 51 | type negotiation struct { 52 | T string // the transport that the client is comfortable using (e.g, websockets) 53 | } 54 | 55 | type negotiationResponse struct { 56 | ConnectionID string 57 | } 58 | 59 | // NewExchange initializes and returns a new Exchange 60 | func NewExchange() *Exchange { 61 | e := &Exchange{} 62 | e.groups = make(map[string][]*client) 63 | e.transports = map[string]Transport{ 64 | "websocket": newWebSocketTransport(e), 65 | "longpoll": newLongPollTransport(e), 66 | } 67 | 68 | return e 69 | } 70 | 71 | func (e *Exchange) ServeHTTP(w http.ResponseWriter, r *http.Request) { 72 | route := extractRouteFromURL(r) 73 | op := extractOperationFromURL(r) 74 | 75 | switch op { 76 | case opWebSocket: 77 | e.upgradeWebSocket(w, r) 78 | case opNegotiate: 79 | e.negotiateConnection(w, r) 80 | case opLongPoll: 81 | e.awaitLongPoll(w, r) 82 | case opCallServer: 83 | e.callServer(w, r) 84 | default: 85 | e.writeClientScript(w, route) 86 | } 87 | } 88 | 89 | func extractRouteFromURL(r *http.Request) string { 90 | lastSlash := strings.LastIndex(r.URL.Path, "/") 91 | return r.URL.Path[:lastSlash] 92 | } 93 | 94 | func extractOperationFromURL(r *http.Request) string { 95 | lastSlash := strings.LastIndex(r.URL.Path, "/") 96 | return r.URL.Path[lastSlash+1:] 97 | } 98 | 99 | func (e *Exchange) upgradeWebSocket(w http.ResponseWriter, r *http.Request) { 100 | ws, err := upgrader.Upgrade(w, r, nil) 101 | if err != nil { 102 | return 103 | } 104 | c := &connection{e: e, out: make(chan []byte, 256), ws: ws, c: e.transports["websocket"].(*webSocketTransport), id: r.URL.Query()["connectionId"][0]} 105 | c.c.connected <- c 106 | defer func() { c.c.disconnected <- c }() 107 | go c.write() 108 | c.read() 109 | } 110 | 111 | func (e *Exchange) negotiateConnection(w http.ResponseWriter, r *http.Request) { 112 | jsonResponse(w) 113 | decoder := json.NewDecoder(r.Body) 114 | 115 | var neg negotiation 116 | 117 | decoder.Decode(&neg) 118 | 119 | encoder := json.NewEncoder(w) 120 | encoder.Encode(negotiationResponse{ConnectionID: e.addClient(neg.T)}) 121 | } 122 | 123 | func (e *Exchange) awaitLongPoll(w http.ResponseWriter, r *http.Request) { 124 | jsonResponse(w) 125 | cid := e.extractConnectionIDFromURL(r) 126 | longPoll := e.transports["longpoll"].(*longPollTransport) 127 | longPoll.wait(w, cid) 128 | } 129 | 130 | func (e *Exchange) callServer(w http.ResponseWriter, r *http.Request) { 131 | var msg longPollServerCall 132 | decoder := json.NewDecoder(r.Body) 133 | decoder.Decode(&msg) 134 | cid := e.extractConnectionIDFromURL(r) 135 | relay := e.getRelayByName(msg.Relay, cid) 136 | go e.callRelayMethod(relay, msg.Method, msg.Arguments...) 137 | } 138 | 139 | func (e *Exchange) extractConnectionIDFromURL(r *http.Request) string { 140 | return r.URL.Query()["connectionId"][0] 141 | } 142 | 143 | func (e *Exchange) addClient(t string) string { 144 | cID := generateConnectionID() 145 | e.groups["Global"] = append(e.groups["Global"], &client{ConnectionID: cID, exchange: e, transport: e.transports[t]}) 146 | return cID 147 | } 148 | 149 | func (e *Exchange) writeClientScript(w http.ResponseWriter, route string) { 150 | if len(clientScript) > 0 && cacheEnabled { 151 | io.Copy(w, bytes.NewBuffer(clientScript)) 152 | } else { 153 | resultBuff := bytes.Buffer{} 154 | buff := bytes.Buffer{} 155 | 156 | buff.WriteString(fmt.Sprintf(connectionClassScript, route)) 157 | 158 | buff.WriteString(relayClassBegin) 159 | 160 | for _, relay := range e.relays { 161 | buff.WriteString(fmt.Sprintf(relayBegin, relay.Name)) 162 | 163 | for _, method := range relay.methods { 164 | buff.WriteString(fmt.Sprintf(relayMethod, lowerFirst(method), relay.Name, method)) 165 | 166 | } 167 | buff.WriteString(relayEnd) 168 | } 169 | 170 | buff.WriteString(relayClassEnd) 171 | 172 | if ClientScriptFunc != nil { 173 | resultBuff.Write(ClientScriptFunc(buff.Bytes())) 174 | } else { 175 | resultBuff.Write(buff.Bytes()) 176 | } 177 | 178 | if cacheEnabled { 179 | clientScript = resultBuff.Bytes() 180 | } 181 | 182 | io.Copy(w, &resultBuff) 183 | } 184 | } 185 | 186 | // RegisterRelay registers a struct as a Relay with the Exchange. This allows clients 187 | // to invoke server methods on a Relay and allows the Exchange to invoke 188 | // methods on a Relay on the server side. 189 | func (e *Exchange) RegisterRelay(x interface{}) { 190 | t := reflect.TypeOf(x) 191 | 192 | methods := e.getMethodsForType(t) 193 | 194 | e.relays = append(e.relays, Relay{Name: t.Name(), t: t, methods: methods, exchange: e}) 195 | } 196 | 197 | func (e *Exchange) getMethodsForType(t reflect.Type) []string { 198 | r := []string{} 199 | for i := 0; i < t.NumMethod(); i++ { 200 | r = append(r, t.Method(i).Name) 201 | } 202 | 203 | return r 204 | } 205 | 206 | func (e *Exchange) getRelayByName(name string, cID string) *Relay { 207 | // Create an instance of Relay 208 | for _, r := range e.relays { 209 | if r.Name == name { 210 | relay := &Relay{ 211 | Name: name, 212 | ConnectionID: cID, 213 | t: r.t, 214 | exchange: e, 215 | } 216 | 217 | relay.Clients = &ClientOperations{ 218 | e: e, 219 | relay: relay, 220 | } 221 | 222 | return relay 223 | } 224 | } 225 | 226 | return nil 227 | } 228 | 229 | func (e *Exchange) callRelayMethod(relay *Relay, fn string, args ...interface{}) error { 230 | newInstance := reflect.New(relay.t) 231 | method := newInstance.MethodByName(fn) 232 | empty := reflect.Value{} 233 | if method == empty { 234 | return fmt.Errorf("Method '%v' does not exist on relay '%v'", fn, relay.Name) 235 | } 236 | method.Call(buildArgValues(relay, args...)) 237 | 238 | return nil 239 | } 240 | 241 | func buildArgValues(relay *Relay, args ...interface{}) []reflect.Value { 242 | r := []reflect.Value{reflect.ValueOf(relay)} 243 | for _, a := range args { 244 | r = append(r, reflect.ValueOf(a)) 245 | } 246 | 247 | return r 248 | } 249 | 250 | // Relay generates an instance of a Relay, allowing calls to be made to 251 | // it on the server side. It is generated a random ConnectionID for the duration 252 | // of the call and it does not represent an actual client. 253 | func (e *Exchange) Relay(x interface{}) *Relay { 254 | return e.getRelayByName(reflect.TypeOf(x).Name(), generateConnectionID()) 255 | } 256 | 257 | func (e *Exchange) callClientMethod(r *Relay, fn string, args ...interface{}) { 258 | if r.ConnectionID == "" { 259 | e.callGroupMethod(r, "Global", fn, args...) 260 | return 261 | } 262 | 263 | c := e.getClientByConnectionID(r.ConnectionID) 264 | if c != nil { 265 | c.transport.CallClientFunction(r, fn, args...) 266 | } 267 | } 268 | 269 | func (e *Exchange) callGroupMethod(relay *Relay, group, fn string, args ...interface{}) { 270 | if _, ok := e.groups[group]; ok { 271 | for _, c := range e.groups[group] { 272 | r := e.getRelayByName(relay.Name, c.ConnectionID) 273 | c.transport.CallClientFunction(r, fn, args...) 274 | } 275 | } 276 | } 277 | 278 | func (e *Exchange) callGroupMethodExcept(relay *Relay, group, fn string, args ...interface{}) { 279 | for _, c := range e.groups[group] { 280 | if c.ConnectionID == relay.ConnectionID { 281 | continue 282 | } 283 | r := e.getRelayByName(relay.Name, c.ConnectionID) 284 | c.transport.CallClientFunction(r, fn, args...) 285 | } 286 | } 287 | 288 | func (e *Exchange) getClientByConnectionID(cID string) *client { 289 | for _, c := range e.groups["Global"] { 290 | if c.ConnectionID == cID { 291 | return c 292 | } 293 | } 294 | return nil 295 | } 296 | 297 | func (e *Exchange) removeFromAllGroups(id string) { 298 | for group := range e.groups { 299 | e.removeFromGroupByID(group, id) 300 | } 301 | } 302 | 303 | func (e *Exchange) removeFromGroupByID(g, id string) { 304 | if i := e.getClientIndexInGroup(g, id); i > -1 { 305 | group := e.groups[g] 306 | group[i] = nil 307 | e.groups[g] = append(group[:i], group[i+1:]...) 308 | 309 | // clean up the group if it is empty 310 | if len(e.groups[g]) == 0 { 311 | delete(e.groups, g) 312 | } 313 | } 314 | } 315 | 316 | func (e *Exchange) getClientIndexInGroup(g, id string) int { 317 | for i, c := range e.groups[g] { 318 | if c.ConnectionID == id { 319 | return i 320 | } 321 | } 322 | 323 | return -1 324 | } 325 | 326 | func (e *Exchange) addToGroup(group, connectionID string) { 327 | // only add them if they aren't currently in the group 328 | if e.getClientIndexInGroup(group, connectionID) == -1 { 329 | e.groups[group] = append(e.groups[group], e.getClientByConnectionID(connectionID)) 330 | } 331 | } 332 | -------------------------------------------------------------------------------- /groupOps.go: -------------------------------------------------------------------------------- 1 | package relayr 2 | 3 | // GroupOperations provides helper methods for communicating 4 | // with clients in groups. Clients must be added to a group 5 | // to be considered a member of a group. 6 | type GroupOperations struct { 7 | relay *Relay 8 | group string 9 | e *Exchange 10 | } 11 | 12 | // Add adds a client to a group via its ConnectionID. It 13 | // is a member of the group for the remainder of its 14 | // connection. At that point, the client must re-negotiate 15 | // its place within the group to be considered a member of it. 16 | func (g *GroupOperations) Add(connectionID string) { 17 | g.e.addToGroup(g.group, connectionID) 18 | } 19 | 20 | // Remove removes a client from a group via its ConnectionID. 21 | func (g *GroupOperations) Remove(connectionID string) { 22 | g.e.removeFromGroupByID(g.group, connectionID) 23 | } 24 | 25 | // Call invokes a client-side method across a Group of clients, 26 | // passing args to them. 27 | func (g *GroupOperations) Call(fn string, args ...interface{}) { 28 | g.e.callGroupMethod(g.relay, g.group, fn, args...) 29 | } 30 | -------------------------------------------------------------------------------- /longpoll-transport.go: -------------------------------------------------------------------------------- 1 | package relayr 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "io" 7 | "net/http" 8 | "sync" 9 | "time" 10 | ) 11 | 12 | type longPollConnection struct { 13 | e *Exchange 14 | result chan []byte 15 | timeoutChan chan struct{} 16 | t *time.Timer 17 | ConnectionID string 18 | } 19 | 20 | type longPollTransport struct { 21 | e *Exchange 22 | connections map[string]longPollConnection 23 | clock *sync.RWMutex 24 | } 25 | 26 | func (t *longPollTransport) clientInConnections(cid string) bool { 27 | _, exists := t.connections[cid] 28 | 29 | return exists 30 | } 31 | 32 | func (t *longPollTransport) addConnection(cid string) longPollConnection { 33 | lp := longPollConnection{ 34 | e: t.e, 35 | result: make(chan []byte, 100), 36 | timeoutChan: make(chan struct{}, 10), 37 | ConnectionID: cid, 38 | } 39 | 40 | t.connections[cid] = lp 41 | 42 | return lp 43 | } 44 | 45 | func (t *longPollTransport) withClient(cid string, fn func(c longPollConnection)) { 46 | if t.clientInConnections(cid) { 47 | fn(t.connections[cid]) 48 | } 49 | } 50 | 51 | func newLongPollTransport(e *Exchange) *longPollTransport { 52 | lp := &longPollTransport{ 53 | e: e, 54 | connections: make(map[string]longPollConnection), 55 | clock: &sync.RWMutex{}, 56 | } 57 | 58 | return lp 59 | } 60 | 61 | func (t *longPollTransport) CallClientFunction(relay *Relay, fn string, args ...interface{}) { 62 | buff := &bytes.Buffer{} 63 | encoder := json.NewEncoder(buff) 64 | 65 | encoder.Encode(struct { 66 | R string 67 | M string 68 | A []interface{} 69 | }{ 70 | relay.Name, 71 | fn, 72 | args, 73 | }) 74 | 75 | go t.withClient(relay.ConnectionID, func(c longPollConnection) { 76 | // force a timeout if we block on sending too long.. 77 | go func() { 78 | <-time.After(time.Second * 30) 79 | c.timeoutChan <- struct{}{} 80 | }() 81 | c.result <- buff.Bytes() 82 | }) 83 | } 84 | 85 | func (t *longPollTransport) removeConnection(cid string) { 86 | delete(t.connections, cid) 87 | } 88 | 89 | func (t *longPollTransport) wait(w http.ResponseWriter, cid string) { 90 | var conn longPollConnection 91 | if !t.clientInConnections(cid) { 92 | conn = t.addConnection(cid) 93 | } else { 94 | conn = t.connections[cid] 95 | } 96 | 97 | select { 98 | case m := <-conn.result: 99 | io.Copy(w, bytes.NewBuffer(m)) 100 | case <-conn.timeoutChan: 101 | buff := &bytes.Buffer{} 102 | encoder := json.NewEncoder(buff) 103 | encoder.Encode(struct { 104 | Z string 105 | }{ 106 | "RECONNECT", 107 | }) 108 | io.WriteString(w, buff.String()) 109 | t.removeConnection(cid) 110 | t.e.removeFromAllGroups(cid) 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /operation.go: -------------------------------------------------------------------------------- 1 | package relayr 2 | 3 | const ( 4 | opNegotiate = "negotiate" 5 | opConnect = "connect" 6 | opWebSocket = "ws" 7 | opLongPoll = "longpoll" 8 | opCallServer = "call" 9 | ) 10 | -------------------------------------------------------------------------------- /relay.go: -------------------------------------------------------------------------------- 1 | package relayr 2 | 3 | import "reflect" 4 | 5 | // Relay encapsulates a connection with a client 6 | // during an interaction with the server. It provides methods 7 | // for interacting with clients and groups. 8 | type Relay struct { 9 | Name string // The name of the relay it is associated with 10 | ConnectionID string // The connectionID of the client that this Relay interacts with 11 | Clients *ClientOperations // An abstraction over clients currently connected to this Relay 12 | 13 | methods []string 14 | t reflect.Type 15 | exchange *Exchange 16 | } 17 | 18 | // Call will execute a function on another server-side Relay, 19 | // passing along the details of the currently connected client. 20 | func (r *Relay) Call(fn string, args ...interface{}) { 21 | r.exchange.callRelayMethod(r, fn, args...) 22 | } 23 | 24 | // Groups returns a GroupOperations object, which offers helper 25 | // methods for communicating with and grouping clients. 26 | func (r *Relay) Groups(group string) *GroupOperations { 27 | return &GroupOperations{ 28 | group: group, 29 | e: r.exchange, 30 | relay: r, 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /transport.go: -------------------------------------------------------------------------------- 1 | package relayr 2 | 3 | // Transport represents a communication mechanism between 4 | // a Relay and a client. 5 | type Transport interface { 6 | CallClientFunction(relay *Relay, fn string, args ...interface{}) 7 | } 8 | -------------------------------------------------------------------------------- /util.go: -------------------------------------------------------------------------------- 1 | package relayr 2 | 3 | import ( 4 | "crypto/rand" 5 | "encoding/base64" 6 | "net/http" 7 | "unicode" 8 | "unicode/utf8" 9 | ) 10 | 11 | func jsonResponse(w http.ResponseWriter) { 12 | w.Header().Set("Content-type", "application/json") 13 | } 14 | 15 | func generateConnectionID() string { 16 | rb := make([]byte, 32) 17 | rand.Read(rb) 18 | rs := base64.URLEncoding.EncodeToString(rb) 19 | return rs 20 | } 21 | 22 | func lowerFirst(s string) string { 23 | if s == "" { 24 | return "" 25 | } 26 | r, n := utf8.DecodeRuneInString(s) 27 | return string(unicode.ToLower(r)) + s[n:] 28 | } 29 | 30 | func upperFirst(s string) string { 31 | if s == "" { 32 | return "" 33 | } 34 | r, n := utf8.DecodeRuneInString(s) 35 | return string(unicode.ToUpper(r)) + s[n:] 36 | } 37 | -------------------------------------------------------------------------------- /websocket-transport.go: -------------------------------------------------------------------------------- 1 | package relayr 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | "fmt" 7 | 8 | "github.com/gorilla/websocket" 9 | ) 10 | 11 | type connection struct { 12 | ws *websocket.Conn 13 | out chan []byte 14 | c *webSocketTransport 15 | id string 16 | e *Exchange 17 | } 18 | 19 | type webSocketTransport struct { 20 | connections map[string]*connection 21 | connected chan *connection 22 | disconnected chan *connection 23 | e *Exchange 24 | } 25 | 26 | type webSocketClientMessage struct { 27 | Server bool `json:"S"` 28 | Relay string `json:"R"` 29 | Method string `json:"M"` 30 | Arguments []interface{} `json:"A"` 31 | ConnectionID string `json:"C"` 32 | } 33 | 34 | func newWebSocketTransport(e *Exchange) *webSocketTransport { 35 | c := &webSocketTransport{ 36 | connected: make(chan *connection), 37 | disconnected: make(chan *connection), 38 | connections: make(map[string]*connection), 39 | e: e, 40 | } 41 | 42 | go c.listen() 43 | 44 | return c 45 | } 46 | 47 | func (c *webSocketTransport) listen() { 48 | for { 49 | select { 50 | case conn := <-c.connected: 51 | c.connections[conn.id] = conn 52 | case conn := <-c.disconnected: 53 | if _, ok := c.connections[conn.id]; ok { 54 | c.e.removeFromAllGroups(conn.id) 55 | delete(c.connections, conn.id) 56 | close(conn.out) 57 | } 58 | } 59 | } 60 | } 61 | 62 | func (c *webSocketTransport) CallClientFunction(relay *Relay, fn string, args ...interface{}) { 63 | buff := &bytes.Buffer{} 64 | encoder := json.NewEncoder(buff) 65 | 66 | encoder.Encode(struct { 67 | R string 68 | M string 69 | A []interface{} 70 | }{ 71 | relay.Name, 72 | fn, 73 | args, 74 | }) 75 | 76 | o := c.connections[relay.ConnectionID] 77 | 78 | if o != nil { 79 | o.out <- buff.Bytes() 80 | } 81 | } 82 | 83 | func (c *connection) read() { 84 | for { 85 | _, message, err := c.ws.ReadMessage() 86 | if err != nil { 87 | break 88 | } 89 | var m webSocketClientMessage 90 | err = json.Unmarshal(message, &m) 91 | if err != nil { 92 | fmt.Println("ERR:", err) 93 | continue 94 | } 95 | 96 | relay := c.e.getRelayByName(m.Relay, m.ConnectionID) 97 | 98 | if m.Server { 99 | err := c.e.callRelayMethod(relay, m.Method, m.Arguments...) 100 | if err != nil { 101 | fmt.Println("ERR:", err) 102 | } 103 | } else { 104 | c.c.CallClientFunction(relay, m.Method, m.Arguments) 105 | } 106 | } 107 | c.ws.Close() 108 | } 109 | 110 | func (c *connection) write() { 111 | for message := range c.out { 112 | err := c.ws.WriteMessage(websocket.TextMessage, message) 113 | if err != nil { 114 | break 115 | } 116 | } 117 | c.ws.Close() 118 | } 119 | --------------------------------------------------------------------------------