├── CONTRIBUTORS ├── LICENSE ├── README.md ├── doc.go ├── handlers.go ├── udp.go ├── udp_config.go ├── udp_handlers_test.go └── udp_test.go /CONTRIBUTORS: -------------------------------------------------------------------------------- 1 | # This is the official list of people who can contribute 2 | # (and typically have contributed) code to the gotraining repository. 3 | # 4 | # Names should be added to this file only after verifying that 5 | # the individual or the individual's organization has agreed to 6 | # the appropriate Contributor License Agreement, found here: 7 | # 8 | # http://code.google.com/legal/individual-cla-v1.0.html 9 | # http://code.google.com/legal/corporate-cla-v1.0.html 10 | # 11 | # The agreement for individuals can be filled out on the web. 12 | 13 | # Names should be added to this file like so: 14 | # Name 15 | # 16 | # An entry with two email addresses specifies that the 17 | # first address should be used in the submit logs and 18 | # that the second address should be recognized as the 19 | # same person when interacting with Rietveld. 20 | 21 | # Please keep the list sorted. 22 | 23 | William Kennedy -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # udp 4 | `import "github.com/ardanlabs/udp"` 5 | 6 | * [Overview](#pkg-overview) 7 | * [Index](#pkg-index) 8 | 9 | ## Overview 10 | Package udp provides the boilerplate code for working with UDP based data. The package 11 | allows you to establish a UDP listener that can accept data on a specified IP address 12 | and port. It also provides a function to send data back to the client. 13 | 14 | There are three interfaces that need to be implemented to use the package. These 15 | interfaces provide the API for processing data. 16 | 17 | ConnHandler 18 | 19 | 20 | type ConnHandler interface { 21 | Bind(logCtx string, listener *net.UDPConn) (io.Reader, io.Writer) 22 | } 23 | 24 | The ConnHandler interface is implemented by the user to bind the listener 25 | to a reader and writer for processing. 26 | 27 | ReqHandler 28 | 29 | 30 | type ReqHandler interface { 31 | Read(logCtx string, reader io.Reader) (*net.UDPAddr, []byte, int, error) 32 | Process(logCtx string, r *Request) 33 | } 34 | 35 | type Request struct { 36 | UDP *UDP 37 | UDPAddr *net.UDPAddr 38 | Data []byte 39 | Length int 40 | } 41 | 42 | The ReqHandler interface is implemented by the user to implement the processing 43 | of request messages from the client. Read is provided the user-defined reader 44 | and must return the data read off the wire and the length. Returning io.EOF or 45 | a non temporary error will show down the listener. 46 | 47 | RespHandler 48 | 49 | 50 | type RespHandler interface { 51 | Write(logCtx string, r *Response, writer io.Writer) 52 | } 53 | 54 | type Response struct { 55 | UDPAddr *net.UDPAddr 56 | Data []byte 57 | Length int 58 | } 59 | 60 | The RespHandler interface is implemented by the user to implement the processing 61 | of the response messages to the client. Write is provided the user-defined 62 | writer and the data to write. 63 | 64 | ### Sample Application 65 | After implementing the interfaces, the following code is all that is needed to 66 | start processing messages. 67 | 68 | 69 | func main() { 70 | log.Startf("TEST", "main", "Starting Test App") 71 | 72 | cfg := udp.Config{ 73 | NetType: "udp4", 74 | Addr: ":9000", 75 | WorkRoutines: 2, 76 | WorkStats: time.Minute, 77 | ConnHandler: udpConnHandler{}, 78 | ReqHandler: udpReqHandler{}, 79 | RespHandler: udpRespHandler{}, 80 | } 81 | 82 | u, err := udp.New("TEST", &cfg) 83 | if err != nil { 84 | log.ErrFatal(err, "TEST", "main") 85 | } 86 | 87 | if err := u.Start("TEST"); err != nil { 88 | log.ErrFatal(err, "TEST", "main") 89 | } 90 | 91 | // Wait for a signal to shutdown. 92 | sigChan := make(chan os.Signal, 1) 93 | signal.Notify(sigChan, os.Interrupt) 94 | <-sigChan 95 | 96 | u.Stop("TEST") 97 | 98 | log.Complete("TEST", "main") 99 | } 100 | 101 | 102 | 103 | 104 | ## Index 105 | * [Variables](#pkg-variables) 106 | * [type Config](#Config) 107 | * [func (cfg *Config) Event(event string, format string, a ...interface{})](#Config.Event) 108 | * [func (cfg *Config) Validate() error](#Config.Validate) 109 | * [type ConnHandler](#ConnHandler) 110 | * [type OptEvent](#OptEvent) 111 | * [type ReqHandler](#ReqHandler) 112 | * [type Request](#Request) 113 | * [type RespHandler](#RespHandler) 114 | * [type Response](#Response) 115 | * [type UDP](#UDP) 116 | * [func New(name string, cfg Config) (*UDP, error)](#New) 117 | * [func (d *UDP) Addr() net.Addr](#UDP.Addr) 118 | * [func (d *UDP) Send(r *Response) error](#UDP.Send) 119 | * [func (d *UDP) Start() error](#UDP.Start) 120 | * [func (d *UDP) Stop() error](#UDP.Stop) 121 | 122 | 123 | #### Package files 124 | [doc.go](/src/github.com/ardanlabs/udp/doc.go) [handlers.go](/src/github.com/ardanlabs/udp/handlers.go) [udp.go](/src/github.com/ardanlabs/udp/udp.go) [udp_config.go](/src/github.com/ardanlabs/udp/udp_config.go) 125 | 126 | 127 | 128 | ## Variables 129 | ``` go 130 | var ( 131 | ErrInvalidConfiguration = errors.New("Invalid Configuration") 132 | ErrInvalidNetType = errors.New("Invalid NetType Configuration") 133 | ErrInvalidConnHandler = errors.New("Invalid Connection Handler Configuration") 134 | ErrInvalidReqHandler = errors.New("Invalid Request Handler Configuration") 135 | ErrInvalidRespHandler = errors.New("Invalid Response Handler Configuration") 136 | ) 137 | ``` 138 | Set of error variables for start up. 139 | 140 | 141 | 142 | 143 | ## type [Config](/src/target/udp_config.go?s=227:845#L1) 144 | ``` go 145 | type Config struct { 146 | NetType string // "udp", udp4" or "udp6" 147 | Addr string // "host:port" or "[ipv6-host%zone]:port" 148 | 149 | ConnHandler ConnHandler // Support for binding new connections to a reader and writer. 150 | ReqHandler ReqHandler // Support for handling the specific request workflow. 151 | RespHandler RespHandler // Support for handling the specific response workflow. 152 | 153 | OptEvent 154 | } 155 | ``` 156 | Config provides a data structure of required configuration parameters. 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | ### func (\*Config) [Event](/src/target/udp_config.go?s=1369:1440#L40) 168 | ``` go 169 | func (cfg *Config) Event(event string, format string, a ...interface{}) 170 | ``` 171 | Event fires events back to the user for important events. 172 | 173 | 174 | 175 | 176 | ### func (\*Config) [Validate](/src/target/udp_config.go?s=903:938#L15) 177 | ``` go 178 | func (cfg *Config) Validate() error 179 | ``` 180 | Validate checks the configuration to required items. 181 | 182 | 183 | 184 | 185 | ## type [ConnHandler](/src/target/handlers.go?s=447:579#L18) 186 | ``` go 187 | type ConnHandler interface { 188 | 189 | // Bind is called to set the reader and writer. 190 | Bind(listener *net.UDPConn) (io.Reader, io.Writer) 191 | } 192 | ``` 193 | ConnHandler is implemented by the user to bind the listener 194 | to a reader and writer for processing. 195 | 196 | 197 | 198 | 199 | 200 | 201 | 202 | 203 | 204 | 205 | ## type [OptEvent](/src/target/udp_config.go?s=68:151#L1) 206 | ``` go 207 | type OptEvent struct { 208 | Event func(event string, format string, a ...interface{}) 209 | } 210 | ``` 211 | OptEvent defines an handler used to provide events. 212 | 213 | 214 | 215 | 216 | 217 | 218 | 219 | 220 | 221 | 222 | ## type [ReqHandler](/src/target/handlers.go?s=690:1109#L26) 223 | ``` go 224 | type ReqHandler interface { 225 | 226 | // Read is provided the user-defined reader and must return the data read 227 | // off the wire and the length. Returning io.EOF or a non temporary error 228 | // will show down the listener. 229 | Read(reader io.Reader) (*net.UDPAddr, []byte, int, error) 230 | 231 | // Process is used to handle the processing of the request. This method 232 | // is called on a routine from a pool of routines. 233 | Process(r *Request) 234 | } 235 | ``` 236 | ReqHandler is implemented by the user to implement the processing 237 | of request messages from the client. 238 | 239 | 240 | 241 | 242 | 243 | 244 | 245 | 246 | 247 | 248 | ## type [Request](/src/target/handlers.go?s=96:217#L1) 249 | ``` go 250 | type Request struct { 251 | UDP *UDP 252 | UDPAddr *net.UDPAddr 253 | IsIPv6 bool 254 | ReadAt time.Time 255 | Data []byte 256 | Length int 257 | } 258 | ``` 259 | Request is the message received by the client. 260 | 261 | 262 | 263 | 264 | 265 | 266 | 267 | 268 | 269 | 270 | ## type [RespHandler](/src/target/handlers.go?s=1224:1368#L40) 271 | ``` go 272 | type RespHandler interface { 273 | 274 | // Write is provided the user-defined writer and the data to write. 275 | Write(r *Response, writer io.Writer) error 276 | } 277 | ``` 278 | RespHandler is implemented by the user to implement the processing 279 | of the response messages to the client. 280 | 281 | 282 | 283 | 284 | 285 | 286 | 287 | 288 | 289 | 290 | ## type [Response](/src/target/handlers.go?s=265:340#L10) 291 | ``` go 292 | type Response struct { 293 | UDPAddr *net.UDPAddr 294 | Data []byte 295 | Length int 296 | } 297 | ``` 298 | Response is message to send to the client. 299 | 300 | 301 | 302 | 303 | 304 | 305 | 306 | 307 | 308 | 309 | ## type [UDP](/src/target/udp.go?s=717:953#L19) 310 | ``` go 311 | type UDP struct { 312 | Config 313 | Name string 314 | // contains filtered or unexported fields 315 | } 316 | ``` 317 | UDP manages message to a specific ip address and port. 318 | 319 | 320 | 321 | 322 | 323 | 324 | 325 | ### func [New](/src/target/udp.go?s=1004:1051#L38) 326 | ``` go 327 | func New(name string, cfg Config) (*UDP, error) 328 | ``` 329 | New creates a new manager to service clients. 330 | 331 | 332 | 333 | 334 | 335 | ### func (\*UDP) [Addr](/src/target/udp.go?s=4944:4973#L216) 336 | ``` go 337 | func (d *UDP) Addr() net.Addr 338 | ``` 339 | Addr returns the local listening network address. 340 | 341 | 342 | 343 | 344 | ### func (\*UDP) [Send](/src/target/udp.go?s=4807:4844#L211) 345 | ``` go 346 | func (d *UDP) Send(r *Response) error 347 | ``` 348 | Send will deliver the response back to the client. 349 | 350 | 351 | 352 | 353 | ### func (\*UDP) [Start](/src/target/udp.go?s=1675:1702#L70) 354 | ``` go 355 | func (d *UDP) Start() error 356 | ``` 357 | Start begins to accept data. 358 | 359 | 360 | 361 | 362 | ### func (\*UDP) [Stop](/src/target/udp.go?s=4236:4262#L183) 363 | ``` go 364 | func (d *UDP) Stop() error 365 | ``` 366 | Stop shuts down the manager and closes all connections. 367 | 368 | 369 | 370 | 371 | 372 | 373 | 374 | 375 | - - - 376 | Generated by [godoc2md](http://godoc.org/github.com/davecheney/godoc2md) 377 | -------------------------------------------------------------------------------- /doc.go: -------------------------------------------------------------------------------- 1 | // Package udp provides the boilerplate code for working with UDP based data. The package 2 | // allows you to establish a UDP listener that can accept data on a specified IP address 3 | // and port. It also provides a function to send data back to the client. 4 | // 5 | // There are three interfaces that need to be implemented to use the package. These 6 | // interfaces provide the API for processing data. 7 | // 8 | // ConnHandler 9 | // 10 | // type ConnHandler interface { 11 | // Bind(logCtx string, listener *net.UDPConn) (io.Reader, io.Writer) 12 | // } 13 | // 14 | // The ConnHandler interface is implemented by the user to bind the listener 15 | // to a reader and writer for processing. 16 | // 17 | // ReqHandler 18 | // 19 | // type ReqHandler interface { 20 | // Read(logCtx string, reader io.Reader) (*net.UDPAddr, []byte, int, error) 21 | // Process(logCtx string, r *Request) 22 | // } 23 | // 24 | // type Request struct { 25 | // UDP *UDP 26 | // UDPAddr *net.UDPAddr 27 | // Data []byte 28 | // Length int 29 | // } 30 | // 31 | // The ReqHandler interface is implemented by the user to implement the processing 32 | // of request messages from the client. Read is provided the user-defined reader 33 | // and must return the data read off the wire and the length. Returning io.EOF or 34 | // a non temporary error will show down the listener. 35 | // 36 | // RespHandler 37 | // 38 | // type RespHandler interface { 39 | // Write(logCtx string, r *Response, writer io.Writer) 40 | // } 41 | // 42 | // type Response struct { 43 | // UDPAddr *net.UDPAddr 44 | // Data []byte 45 | // Length int 46 | // } 47 | // 48 | // The RespHandler interface is implemented by the user to implement the processing 49 | // of the response messages to the client. Write is provided the user-defined 50 | // writer and the data to write. 51 | // 52 | // Sample Application 53 | // 54 | // After implementing the interfaces, the following code is all that is needed to 55 | // start processing messages. 56 | // 57 | // func main() { 58 | // log.Startf("TEST", "main", "Starting Test App") 59 | // 60 | // cfg := udp.Config{ 61 | // NetType: "udp4", 62 | // Addr: ":9000", 63 | // WorkRoutines: 2, 64 | // WorkStats: time.Minute, 65 | // ConnHandler: udpConnHandler{}, 66 | // ReqHandler: udpReqHandler{}, 67 | // RespHandler: udpRespHandler{}, 68 | // } 69 | // 70 | // u, err := udp.New("TEST", &cfg) 71 | // if err != nil { 72 | // log.ErrFatal(err, "TEST", "main") 73 | // } 74 | // 75 | // if err := u.Start("TEST"); err != nil { 76 | // log.ErrFatal(err, "TEST", "main") 77 | // } 78 | // 79 | // // Wait for a signal to shutdown. 80 | // sigChan := make(chan os.Signal, 1) 81 | // signal.Notify(sigChan, os.Interrupt) 82 | // <-sigChan 83 | // 84 | // u.Stop("TEST") 85 | // 86 | // log.Complete("TEST", "main") 87 | // } 88 | package udp 89 | -------------------------------------------------------------------------------- /handlers.go: -------------------------------------------------------------------------------- 1 | package udp 2 | 3 | import ( 4 | "io" 5 | "net" 6 | "time" 7 | ) 8 | 9 | // Request is the message received by the client. 10 | type Request struct { 11 | UDP *UDP 12 | UDPAddr *net.UDPAddr 13 | IsIPv6 bool 14 | ReadAt time.Time 15 | Data []byte 16 | Length int 17 | } 18 | 19 | // Response is message to send to the client. 20 | type Response struct { 21 | UDPAddr *net.UDPAddr 22 | Data []byte 23 | Length int 24 | } 25 | 26 | // ConnHandler is implemented by the user to bind the listener 27 | // to a reader and writer for processing. 28 | type ConnHandler interface { 29 | 30 | // Bind is called to set the reader and writer. 31 | Bind(listener *net.UDPConn) (io.Reader, io.Writer) 32 | } 33 | 34 | // ReqHandler is implemented by the user to implement the processing 35 | // of request messages from the client. 36 | type ReqHandler interface { 37 | 38 | // Read is provided the user-defined reader and must return the data read 39 | // off the wire and the length. Returning io.EOF or a non temporary error 40 | // will show down the listener. 41 | Read(reader io.Reader) (*net.UDPAddr, []byte, int, error) 42 | 43 | // Process is used to handle the processing of the request. This method 44 | // is called on a routine from a pool of routines. 45 | Process(r *Request) 46 | } 47 | 48 | // RespHandler is implemented by the user to implement the processing 49 | // of the response messages to the client. 50 | type RespHandler interface { 51 | 52 | // Write is provided the user-defined writer and the data to write. 53 | Write(r *Response, writer io.Writer) error 54 | } 55 | -------------------------------------------------------------------------------- /udp.go: -------------------------------------------------------------------------------- 1 | package udp 2 | 3 | import ( 4 | "errors" 5 | "io" 6 | "net" 7 | "strconv" 8 | "sync" 9 | "sync/atomic" 10 | "time" 11 | ) 12 | 13 | // Set of error variables for start up. 14 | var ( 15 | ErrInvalidConfiguration = errors.New("Invalid Configuration") 16 | ErrInvalidNetType = errors.New("Invalid NetType Configuration") 17 | ErrInvalidConnHandler = errors.New("Invalid Connection Handler Configuration") 18 | ErrInvalidReqHandler = errors.New("Invalid Request Handler Configuration") 19 | ErrInvalidRespHandler = errors.New("Invalid Response Handler Configuration") 20 | ) 21 | 22 | // temporary is declared to test for the existence of the method coming 23 | // from the net package. 24 | type temporary interface { 25 | Temporary() bool 26 | } 27 | 28 | // UDP manages message to a specific ip address and port. 29 | type UDP struct { 30 | Config 31 | Name string 32 | 33 | ipAddress string 34 | port int 35 | udpAddr *net.UDPAddr 36 | 37 | listener *net.UDPConn 38 | listenerMu sync.RWMutex 39 | 40 | reader io.Reader 41 | writer io.Writer 42 | 43 | wg sync.WaitGroup 44 | shuttingDown int32 45 | } 46 | 47 | // New creates a new manager to service clients. 48 | func New(name string, cfg Config) (*UDP, error) { 49 | 50 | // Validate the configuration. 51 | if err := cfg.Validate(); err != nil { 52 | return nil, err 53 | } 54 | 55 | // Resolve the addr that is provided. 56 | udpAddr, err := net.ResolveUDPAddr(cfg.NetType, cfg.Addr) 57 | if err != nil { 58 | return nil, err 59 | } 60 | 61 | // Create a UDP for this ipaddress and port. 62 | udp := UDP{ 63 | Config: cfg, 64 | Name: name, 65 | 66 | ipAddress: udpAddr.IP.String(), 67 | port: udpAddr.Port, 68 | udpAddr: udpAddr, 69 | } 70 | 71 | return &udp, nil 72 | } 73 | 74 | // join takes an IP and port values and creates a cleaner string. 75 | func join(ip string, port int) string { 76 | return net.JoinHostPort(ip, strconv.Itoa(port)) 77 | } 78 | 79 | // Start begins to accept data. 80 | func (d *UDP) Start() error { 81 | d.listenerMu.Lock() 82 | { 83 | // If the listener has been started already, return an error. 84 | if d.listener != nil { 85 | d.listenerMu.Unlock() 86 | return errors.New("this UDP has already been started") 87 | } 88 | } 89 | d.listenerMu.Unlock() 90 | 91 | // We need to wait for the goroutine to initialize itself. 92 | var waitStart sync.WaitGroup 93 | waitStart.Add(1) 94 | 95 | // Start the data accept routine. 96 | d.wg.Add(1) 97 | go func() { 98 | for { 99 | d.listenerMu.Lock() 100 | { 101 | // Start a listener for the specified addr and port is one 102 | // does not exist. 103 | if d.listener == nil { 104 | var err error 105 | d.listener, err = net.ListenUDP(d.NetType, d.udpAddr) 106 | if err != nil { 107 | panic(err) 108 | } 109 | 110 | // Ask the user to bind the reader and writer they want to 111 | // use for this listener. 112 | d.reader, d.writer = d.ConnHandler.Bind(d.listener) 113 | 114 | waitStart.Done() 115 | 116 | d.Event("accept", "Waiting For Data : IPAddress[ %s ]", join(d.ipAddress, d.port)) 117 | } 118 | } 119 | d.listenerMu.Unlock() 120 | 121 | // Wait for a message to arrive. 122 | udpAddr, data, length, err := d.ReqHandler.Read(d.reader) 123 | timeRead := time.Now() 124 | 125 | if err != nil { 126 | if atomic.LoadInt32(&d.shuttingDown) == 1 { 127 | d.listenerMu.Lock() 128 | { 129 | d.listener = nil 130 | } 131 | d.listenerMu.Unlock() 132 | break 133 | } 134 | 135 | d.Event("accept", "ERROR : %v", err) 136 | 137 | if e, ok := err.(temporary); ok && !e.Temporary() { 138 | d.listenerMu.Lock() 139 | { 140 | d.listener.Close() 141 | d.listener = nil 142 | } 143 | d.listenerMu.Unlock() 144 | 145 | // Don't want to add a flag. So setting this back to 146 | // 1 so when the listener is re-established, the call 147 | // to Done does not fail. 148 | waitStart.Add(1) 149 | } 150 | 151 | continue 152 | } 153 | 154 | // Check to see if this message is ipv6. 155 | isIPv6 := true 156 | if ip4 := udpAddr.IP.To4(); ip4 != nil { 157 | 158 | // Make sure we return an IPv4 address if udpAddr 159 | // is an IPv4-mapped IPv6 address. Otherwise we 160 | // could end up sending an IPv6 response. 161 | udpAddr.IP = ip4 162 | isIPv6 = false 163 | } 164 | 165 | // Create the request. 166 | req := Request{ 167 | UDP: d, 168 | UDPAddr: udpAddr, 169 | IsIPv6: isIPv6, 170 | ReadAt: timeRead, 171 | Data: data, 172 | Length: length, 173 | } 174 | 175 | // Process the request on this goroutine that is 176 | // handling the socket connection. 177 | d.ReqHandler.Process(&req) 178 | } 179 | 180 | d.wg.Done() 181 | d.Event("accept", "Shutdown : IPAddress[ %s ]", join(d.ipAddress, d.port)) 182 | 183 | return 184 | }() 185 | 186 | // Wait for the goroutine to initialize itself. 187 | waitStart.Wait() 188 | 189 | return nil 190 | } 191 | 192 | // Stop shuts down the manager and closes all connections. 193 | func (d *UDP) Stop() error { 194 | d.listenerMu.Lock() 195 | { 196 | // If the listener has been stopped already, return an error. 197 | if d.listener == nil { 198 | d.listenerMu.Unlock() 199 | return errors.New("this UDP has already been stopped") 200 | } 201 | } 202 | d.listenerMu.Unlock() 203 | 204 | // Mark that we are shutting down. 205 | atomic.StoreInt32(&d.shuttingDown, 1) 206 | 207 | // Don't accept anymore client data. 208 | d.listenerMu.Lock() 209 | { 210 | d.listener.Close() 211 | } 212 | d.listenerMu.Unlock() 213 | 214 | // Wait for the accept routine to terminate. 215 | d.wg.Wait() 216 | 217 | return nil 218 | } 219 | 220 | // Send will deliver the response back to the client. 221 | func (d *UDP) Send(r *Response) error { 222 | return d.RespHandler.Write(r, d.writer) 223 | } 224 | 225 | // Addr returns the local listening network address. 226 | func (d *UDP) Addr() net.Addr { 227 | 228 | // We are aware this read is not safe with the 229 | // goroutine accepting connections. 230 | if d.listener == nil { 231 | return nil 232 | } 233 | return d.listener.LocalAddr() 234 | } 235 | -------------------------------------------------------------------------------- /udp_config.go: -------------------------------------------------------------------------------- 1 | package udp 2 | 3 | // OptEvent defines an handler used to provide events. 4 | type OptEvent struct { 5 | Event func(event string, format string, a ...interface{}) 6 | } 7 | 8 | // Config provides a data structure of required configuration parameters. 9 | type Config struct { 10 | NetType string // "udp", udp4" or "udp6" 11 | Addr string // "host:port" or "[ipv6-host%zone]:port" 12 | 13 | ConnHandler ConnHandler // Support for binding new connections to a reader and writer. 14 | ReqHandler ReqHandler // Support for handling the specific request workflow. 15 | RespHandler RespHandler // Support for handling the specific response workflow. 16 | 17 | // ************************************************************************* 18 | // ** Not Required, optional ** 19 | // ************************************************************************* 20 | 21 | OptEvent 22 | } 23 | 24 | // Validate checks the configuration to required items. 25 | func (cfg *Config) Validate() error { 26 | if cfg == nil { 27 | return ErrInvalidConfiguration 28 | } 29 | 30 | if cfg.NetType != "udp" && cfg.NetType != "udp4" && cfg.NetType != "udp6" { 31 | return ErrInvalidNetType 32 | } 33 | 34 | if cfg.ConnHandler == nil { 35 | return ErrInvalidConnHandler 36 | } 37 | 38 | if cfg.ReqHandler == nil { 39 | return ErrInvalidReqHandler 40 | } 41 | 42 | if cfg.RespHandler == nil { 43 | return ErrInvalidRespHandler 44 | } 45 | 46 | return nil 47 | } 48 | 49 | // Event fires events back to the user for important events. 50 | func (cfg *Config) Event(event string, format string, a ...interface{}) { 51 | if cfg.OptEvent.Event != nil { 52 | cfg.OptEvent.Event(event, format, a...) 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /udp_handlers_test.go: -------------------------------------------------------------------------------- 1 | package udp_test 2 | 3 | import ( 4 | "io" 5 | "net" 6 | "sync/atomic" 7 | "time" 8 | 9 | "github.com/ardanlabs/udp" 10 | ) 11 | 12 | // udpConnHandler is required to process data. 13 | type udpConnHandler struct{} 14 | 15 | // Bind is called to init to reader and writer. 16 | func (udpConnHandler) Bind(listener *net.UDPConn) (io.Reader, io.Writer) { 17 | return listener, listener 18 | } 19 | 20 | // udpReqHandler is required to process client messages. 21 | type udpReqHandler struct{} 22 | 23 | // Read implements the udp.ReqHandler interface. It is provided a request 24 | // value to popular and a io.Reader that was created in the Bind above. 25 | func (udpReqHandler) Read(reader io.Reader) (*net.UDPAddr, []byte, int, error) { 26 | listener := reader.(*net.UDPConn) 27 | 28 | // Each package is 20 bytes in lengrh. 29 | data := make([]byte, 20) 30 | length, udpAddr, err := listener.ReadFromUDP(data) 31 | if err != nil { 32 | return nil, nil, 0, err 33 | } 34 | 35 | return udpAddr, data, length, nil 36 | } 37 | 38 | var dur int64 39 | 40 | // Process is used to handle the processing of the message. This method 41 | // is called on a routine from a pool of routines. 42 | func (udpReqHandler) Process(r *udp.Request) { 43 | if r.Length != 20 { 44 | return 45 | } 46 | 47 | // Extract the header from the first 8 bytes. 48 | // h := struct { 49 | // Raw []byte 50 | // Length int 51 | // Version uint8 52 | // TransactionID uint8 53 | // OpCode uint8 54 | // StatusCode uint8 55 | // StreamHandle uint32 56 | // }{ 57 | // Raw: r.Data, 58 | // Length: r.Length, 59 | // Version: uint8(r.Data[0]), 60 | // TransactionID: uint8(r.Data[1]), 61 | // OpCode: uint8(r.Data[2]), 62 | // StatusCode: uint8(r.Data[3]), 63 | // StreamHandle: uint32(binary.BigEndian.Uint32(r.Data[4:8])), 64 | // } 65 | 66 | resp := udp.Response{ 67 | UDPAddr: r.UDPAddr, 68 | Data: []byte("GOT IT"), 69 | Length: 6, 70 | } 71 | 72 | r.UDP.Send(&resp) 73 | 74 | d := int64(time.Now().Sub(r.ReadAt)) 75 | atomic.StoreInt64(&dur, d) 76 | } 77 | 78 | type udpRespHandler struct{} 79 | 80 | // Write is provided the user-defined writer and the data to write. 81 | func (udpRespHandler) Write(r *udp.Response, writer io.Writer) error { 82 | listener := writer.(*net.UDPConn) 83 | if _, err := listener.WriteToUDP(r.Data, r.UDPAddr); err != nil { 84 | return err 85 | } 86 | 87 | return nil 88 | } 89 | -------------------------------------------------------------------------------- /udp_test.go: -------------------------------------------------------------------------------- 1 | package udp_test 2 | 3 | import ( 4 | "bytes" 5 | "io" 6 | "net" 7 | "os" 8 | "sync/atomic" 9 | "testing" 10 | "time" 11 | 12 | "github.com/ardanlabs/udp" 13 | ) 14 | 15 | // TestUDP provide a test of listening for a connection and 16 | // echoing the data back. 17 | func TestUDP(t *testing.T) { 18 | resetLog() 19 | defer displayLog() 20 | 21 | t.Log("Given the need to listen and process UDP data.") 22 | { 23 | // Create a configuration. 24 | cfg := udp.Config{ 25 | NetType: "udp4", 26 | Addr: ":0", 27 | 28 | ConnHandler: udpConnHandler{}, 29 | ReqHandler: udpReqHandler{}, 30 | RespHandler: udpRespHandler{}, 31 | } 32 | 33 | // Create a new UDP value. 34 | u, err := udp.New("TEST", cfg) 35 | if err != nil { 36 | t.Fatal("\tShould be able to create a new UDP listener.", failed, err) 37 | } 38 | t.Log("\tShould be able to create a new UDP listener.", success) 39 | 40 | // Start accepting client data. 41 | if err := u.Start(); err != nil { 42 | t.Fatal("\tShould be able to start the UDP listener.", failed, err) 43 | } 44 | t.Log("\tShould be able to start the UDP listener.", success) 45 | 46 | defer u.Stop() 47 | 48 | // Let's connect back and send a UDP package 49 | conn, err := net.Dial("udp4", u.Addr().String()) 50 | if err != nil { 51 | t.Fatal("\tShould be able to dial a new UDP connection.", failed, err) 52 | } 53 | t.Log("\tShould be able to dial a new UDP connection.", success) 54 | 55 | // Send some know data to the udp listener. 56 | b := bytes.NewBuffer([]byte{0x01, 0x3D, 0x06, 0x00, 0x58, 0x68, 0x9b, 0x9d, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFC, 0x00, 0x01}) 57 | b.WriteTo(conn) 58 | 59 | // Setup a limit reader to extract the response. 60 | lr := io.LimitReader(conn, 6) 61 | 62 | // Let's read the response. 63 | data := make([]byte, 6) 64 | if _, err := lr.Read(data); err != nil { 65 | t.Fatal("\tShould be able to read the response from the connection.", failed, err) 66 | } 67 | t.Log("\tShould be able to read the response from the connection.", success) 68 | 69 | response := string(data) 70 | 71 | if response == "GOT IT" { 72 | t.Log("\tShould receive the string \"GOT IT\".", success) 73 | } else { 74 | t.Error("\tShould receive the string \"GOT IT\".", failed, response) 75 | } 76 | 77 | d := atomic.LoadInt64(&dur) 78 | duration := time.Duration(d) 79 | 80 | if duration <= 2*time.Second { 81 | t.Log("\tShould be less that 2 seconds.", success) 82 | } else { 83 | t.Error("\tShould be less that 2 seconds.", failed, duration) 84 | } 85 | } 86 | } 87 | 88 | // Test udp.Addr works correctly. 89 | func TestUDPAddr(t *testing.T) { 90 | resetLog() 91 | defer displayLog() 92 | 93 | t.Log("Given the need to listen on any port and know that bound UDP address.") 94 | { 95 | // Create a configuration. 96 | cfg := udp.Config{ 97 | NetType: "udp4", 98 | Addr: ":0", // Defer port assignment to OS. 99 | 100 | ConnHandler: udpConnHandler{}, 101 | ReqHandler: udpReqHandler{}, 102 | RespHandler: udpRespHandler{}, 103 | } 104 | 105 | // Create a new UDP value. 106 | u, err := udp.New("TEST", cfg) 107 | if err != nil { 108 | t.Fatal("\tShould be able to create a new UDP listener.", failed, err) 109 | } 110 | t.Log("\tShould be able to create a new UDP listener.", success) 111 | 112 | // Addr should be nil before start. 113 | if addr := u.Addr(); addr != nil { 114 | t.Fatalf("\tAddr() should be nil before Start; Addr() = %q. %s", addr, failed) 115 | } 116 | t.Log("\tAddr() should be nil before Start.", success) 117 | 118 | // Start accepting client data. 119 | if err := u.Start(); err != nil { 120 | t.Fatal("\tShould be able to start the UDP listener.", failed, err) 121 | } 122 | defer u.Stop() 123 | 124 | // Addr should be non-nil after Start. 125 | addr := u.Addr() 126 | if addr == nil { 127 | t.Fatal("\tAddr() should be not be nil after Start.", failed) 128 | } 129 | t.Log("\tAddr() should be not be nil after Start.", success) 130 | 131 | // The OS should assign a random open port, which shouldn't be 0. 132 | _, port, err := net.SplitHostPort(addr.String()) 133 | if err != nil { 134 | t.Fatalf("\tSplitHostPort should not fail. failed %v. %s", err, failed) 135 | } 136 | if port == "0" { 137 | t.Fatalf("\tAddr port should not be %q. %s", port, failed) 138 | } 139 | t.Logf("\tAddr() should be not be 0 after Start (port = %q). %s", port, success) 140 | } 141 | } 142 | 143 | // Test generic UDP write timeout. 144 | func TestUDPWriteTimeout(t *testing.T) { 145 | t.Log("Given the need to get a timeout error on UDP write.") 146 | { 147 | localAddr, err := net.ResolveUDPAddr("udp4", "127.0.0.1:0") 148 | if err != nil { 149 | t.Fatalf("Should not have failed to resolve UDP address. Err[%v] %s", err, failed) 150 | } 151 | remoteAddr, err := net.ResolveUDPAddr("udp4", "127.0.0.1:1234") 152 | if err != nil { 153 | t.Fatalf("Should not have failed to resolve UDP address. Err[%v] %s", err, failed) 154 | } 155 | 156 | conn, err := net.ListenUDP("udp4", localAddr) 157 | if err != nil { 158 | t.Fatalf("Should not have failed to create UDP connection. Err[%v] %s", err, failed) 159 | } 160 | 161 | if err := conn.SetWriteDeadline(time.Now().Add(1)); err != nil { 162 | t.Fatalf("Should not have failed to set write deadline. Err[%v] %s", err, failed) 163 | } 164 | 165 | const str = "String to send via UDP socket for testing purposes." 166 | 167 | _, err = conn.WriteToUDP([]byte(str), remoteAddr) 168 | if err == nil { 169 | t.Fatalf("Should not gotten an error %s", failed) 170 | } 171 | 172 | t.Logf("Got error [%T: %v] %s", err, err, success) 173 | 174 | opError, ok := err.(*net.OpError) 175 | if !ok { 176 | t.Fatalf("Should have gotten *net.OpError, got [%T: %v] %s", err, err, failed) 177 | } 178 | 179 | if !opError.Timeout() { 180 | t.Fatalf("Should have gotten a timeout error %s", failed) 181 | } 182 | 183 | t.Logf("Got timeout error %s", success) 184 | } 185 | } 186 | 187 | // ============================================================================= 188 | 189 | // Success and failure markers. 190 | var ( 191 | success = "\u2713" 192 | failed = "\u2717" 193 | ) 194 | 195 | // logdash is the central buffer where all logs are stored. 196 | var logdash bytes.Buffer 197 | 198 | // resetLog resets the contents of Logdash. 199 | func resetLog() { 200 | logdash.Reset() 201 | } 202 | 203 | // displayLog writes the Logdash data to standand out, if testing in verbose mode 204 | // was turned on. 205 | func displayLog() { 206 | if !testing.Verbose() { 207 | return 208 | } 209 | 210 | logdash.WriteTo(os.Stdout) 211 | } 212 | --------------------------------------------------------------------------------