├── LICENSE ├── README.md ├── context.go ├── endpoint.go ├── example ├── main.go ├── model.go ├── session.go └── user.go ├── jsondecoder.go ├── jsondecoder_test.go ├── log.go ├── middleware.go ├── renderer.go ├── river.go ├── serviceinjector.go ├── serviceinjector_test.go └── verbose.go /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 2016 Abiola Ibrahim 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 | river 2 | ===== 3 | River is a simple and lightweight REST server. 4 | 5 | ### Getting Started 6 | ```go 7 | rv := river.New() 8 | ``` 9 | 10 | Use middlewares 11 | ```go 12 | rv.Use(river.Logger()) 13 | ``` 14 | 15 | Create endpoints 16 | ```go 17 | e := river.NewEndpoint(). 18 | Get("/:id", func(c *river.Context){ 19 | id := c.Param("id") 20 | ... // fetch data with id 21 | c.Render(200, data) 22 | }). 23 | Post("/", func(c *river.Context){ 24 | ... // process c.Body and store in db 25 | c.Render(201, data) 26 | }) 27 | ... 28 | 29 | e.Use(MyMiddleware) // endpoint specific middleware 30 | ``` 31 | 32 | Handle endpoints 33 | ```go 34 | rv.Handle("/user", e) 35 | ``` 36 | 37 | Run 38 | ```go 39 | rv.Run(":8080") 40 | ``` 41 | 42 | Check [example](https://github.com/abiosoft/river/tree/master/example) code for more. 43 | 44 | ### Approach 45 | * An endpoint is a REST endpoint with handlers for supported methods. 46 | * All endpoints are handled by a River instance. 47 | * Outputs are rendered via a preset or custom Renderer. 48 | * Middlewares and Renderers can be global or specific to an endpoint. 49 | 50 | ### Request Flow 51 | Basic flow 52 | ``` 53 | Request -> Middlewares -> Endpoint -> Renderer 54 | ``` 55 | 56 | Full flow 57 | ``` 58 | Request 59 | | 60 | | 61 | Router 62 | / \ 63 | / \ 64 | / \ 65 | Found Not Found / Method Not Allowed 66 | \ / 67 | \ / 68 | \ / 69 | Global Middlewares 70 | / \ 71 | / \ 72 | Endpoint Middlewares Not Found / Method Not Allowed Handler 73 | | | 74 | | | 75 | Endpoint Renderer 76 | | 77 | | 78 | Renderer 79 | 80 | ``` 81 | 82 | ### Endpoint 83 | Create 84 | ```go 85 | e := river.NewEndpoint() 86 | ``` 87 | 88 | Handle Requests 89 | ```go 90 | e.Get("/", handler).Post(...).Put(...) // method chaining 91 | e.Handle(method, ...) // for custom request methods 92 | ``` 93 | 94 | River supports dependency injection. With that, any function can be an endpoint handler. 95 | ```go 96 | func () {...} // valid 97 | func (c *river.Context) {...} // valid 98 | func (c *river.Context, m MyStruct) {...} // valid 99 | func (w http.ResponseWriter, r *http.Request) {...} // valid 100 | func (w http.ResponseWriter, r *http.Request, m MyStruct) {...} // valid 101 | ``` 102 | 103 | JSON helper 104 | ```go 105 | func (c *river.Context){ 106 | var users []User 107 | c.DecodeJSONBody(&users) 108 | ... // process users 109 | } 110 | ``` 111 | 112 | ### Middleware 113 | Any function that takes in the context can be used as a middleware. 114 | ```go 115 | type Middleware func(c *river.Context) 116 | ``` 117 | 118 | River comes with `river.Recovery()` for panic recovery. 119 | 120 | ```go 121 | rv.Use(Middleware) // global 122 | e.Use(Middleware) // endpoint 123 | ``` 124 | 125 | Middleware can choose to terminate request flow by not calling `c.Next()`. e.g. Authentication middleware. 126 | ```go 127 | func (c *river.Context){ 128 | ... // do something before 129 | c.Next() 130 | ... // do something after 131 | } 132 | ``` 133 | 134 | Any `http.Handler` can also be used as a middleware. 135 | ```go 136 | rv.UseHandler(handler) 137 | ``` 138 | 139 | ### Service Injection 140 | Registering 141 | ```go 142 | var m MyStruct 143 | ... 144 | rv.Register(m) // global 145 | e.Register(m) // endpoint 146 | ``` 147 | 148 | This will be passed as parameter to any endpoint handler that has `MyStruct` 149 | as a function parameter. 150 | ```go 151 | func handle(c *river.Context, m MyStruct) { ... } 152 | ``` 153 | 154 | Middlewares can also register request scoped service. 155 | ```go 156 | func AuthMiddleware(c *river.Context) { 157 | var session *Session 158 | ... // retrieve session 159 | c.Register(session) 160 | } 161 | ``` 162 | 163 | ### Renderer 164 | Renderer takes in data from endpoints and renders the data as response. 165 | 166 | `context.Render(...)` renders using the configured Renderer. `JSONRenderer` is one of the available renderers. 167 | 168 | Example Renderer, transform response to JSend format before sending as JSON. 169 | ```go 170 | func MyRenderer (c *river.Context, data interface{}) error { 171 | resp := river.M{"status" : "success", "data" : data} 172 | if _, ok := data.(error); ok { 173 | resp["status"] = "error" 174 | resp["message"] = data 175 | delete(resp, "data") 176 | } 177 | return JSONRenderer(c, resp) 178 | } 179 | ``` 180 | 181 | Setting a Renderer. When an endpoint Renderer is not set, global Renderer is used. 182 | ```go 183 | rv.Renderer(MyRenderer) // global 184 | e.Renderer(MyRenderer) // endpoint 185 | ``` 186 | 187 | ### Custom server 188 | River is an `http.Handler`. You can do without `Run()`. 189 | ```go 190 | http.ListenAndServe(":8080", rv) 191 | ``` 192 | 193 | ### Router 194 | River uses [httprouter](https://github.com/julienschmidt/httprouter) underneath. 195 | 196 | ### Contributing 197 | * Create an issue to discuss. 198 | * Send in a PR. 199 | 200 | ### Why the name "River", a "REST" server ? Can you REST on a River ? 201 | Well, yes. You only need to know how to swim or wear a life jacket. 202 | 203 | ### License 204 | Apache 2 -------------------------------------------------------------------------------- /context.go: -------------------------------------------------------------------------------- 1 | package river 2 | 3 | import ( 4 | "net/http" 5 | "time" 6 | 7 | "github.com/julienschmidt/httprouter" 8 | ) 9 | 10 | // Context is a request scope context. 11 | // Context implements http.ResponseWriter and embeds *http.Request. 12 | // 13 | // It can be adapted for use in an http.Handler e.g. 14 | // handler.ServeHTTP(c, c.Request) 15 | type Context struct { 16 | *http.Request 17 | rw http.ResponseWriter 18 | params httprouter.Params 19 | values map[string]interface{} 20 | renderer Renderer 21 | errHandler ErrHandler 22 | middlewares []Middleware 23 | jsonDecoder jsonDecoder 24 | headerWritten bool 25 | status int 26 | written int 27 | serviceInjector 28 | } 29 | 30 | // Param returns URL parameters. If key is not found, 31 | // empty string is returned. 32 | // 33 | // Params are set with :key in the handle path. 34 | // e.g. /:category/:id 35 | func (c *Context) Param(key string) string { 36 | return c.params.ByName(key) 37 | } 38 | 39 | // Query returns URL query parameters. If key not found, 40 | // empty string is returned. 41 | func (c *Context) Query(key string) string { 42 | return c.URL.Query().Get(key) 43 | } 44 | 45 | // Redirect performs HTTP redirect to url with code as redirect code. 46 | // code must be 3xx, otherwise http.StatusFound (302) will be used. 47 | func (c *Context) Redirect(url string, code int) { 48 | if code < 300 || code > 399 { 49 | code = http.StatusFound 50 | } 51 | http.Redirect(c, c.Request, url, code) 52 | } 53 | 54 | // Next calls the next handler in the middleware chain. 55 | // A middleware must call Next, otherwise the request stops 56 | // at the middleware. 57 | // 58 | // Next has no effect if called in an endpoint handler. 59 | func (c *Context) Next() { 60 | if len(c.middlewares) < 1 { 61 | return 62 | } 63 | current := c.middlewares[0] 64 | c.middlewares = c.middlewares[1:] 65 | current(c) 66 | } 67 | 68 | // Header returns the header map that will be sent by 69 | // WriteHeader. Changing the header after a call to 70 | // WriteHeader (or Write) has no effect unless the modified 71 | // headers were declared as trailers by setting the 72 | // "Trailer" header before the call to WriteHeader (see example). 73 | // To suppress implicit response headers, set their value to nil. 74 | func (c *Context) Header() http.Header { 75 | return c.rw.Header() 76 | } 77 | 78 | // Write writes the data to the connection as part of an HTTP reply. 79 | // If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) 80 | // before writing the data. If the Header does not contain a 81 | // Content-Type line, Write adds a Content-Type set to the result of passing 82 | // the initial 512 bytes of written data to DetectContentType. 83 | func (c *Context) Write(b []byte) (int, error) { 84 | if !c.headerWritten { 85 | c.WriteHeader(http.StatusOK) 86 | } 87 | n, err := c.rw.Write(b) 88 | c.written += n 89 | return n, err 90 | } 91 | 92 | // WriteHeader sends an HTTP response header with status code. 93 | // If WriteHeader is not called explicitly, the first call to Write 94 | // will trigger an implicit WriteHeader(http.StatusOK). 95 | // Thus explicit calls to WriteHeader are mainly used to 96 | // send error codes. 97 | func (c *Context) WriteHeader(status int) { 98 | c.status = status 99 | c.headerWritten = true 100 | c.rw.WriteHeader(status) 101 | } 102 | 103 | // Get gets the value for key in the context. Key must have been 104 | // previously set using c.Set. 105 | func (c *Context) Get(key string) interface{} { 106 | return c.values[key] 107 | } 108 | 109 | // Set sets key in context to value. 110 | func (c *Context) Set(key string, value interface{}) { 111 | if c.values == nil { 112 | c.values = make(map[string]interface{}) 113 | } 114 | c.values[key] = value 115 | } 116 | 117 | // Render renders data using the current endpoint's renderer (if any) 118 | // or global renderer (if any) or PlainRenderer; in that preference order. 119 | // status is HTTP status code to respond with. 120 | func (c *Context) Render(status int, data interface{}) { 121 | c.WriteHeader(status) 122 | err := c.renderer(c, data) 123 | if err != nil && c.errHandler != nil { 124 | c.errHandler(c, err) 125 | } 126 | } 127 | 128 | // RenderEmpty renders status text for status as body. 129 | // status is HTTP status code to respond with. 130 | func (c *Context) RenderEmpty(status int) { 131 | c.WriteHeader(status) 132 | err := PlainRenderer(c, http.StatusText(status)) 133 | if err != nil && c.errHandler != nil { 134 | c.errHandler(c, err) 135 | } 136 | } 137 | 138 | // Status returns the response status code. This returns 0 unless response 139 | // has been written. 140 | func (c *Context) Status() int { 141 | return c.status 142 | } 143 | 144 | // Written returns the total number of bytes that have been written 145 | // to the ResponseWriter. 146 | func (c *Context) Written() int { 147 | return c.written 148 | } 149 | 150 | // DecodeJSONBody decodes the request body as JSON into v. 151 | // 152 | // The request body must be JSON and v must be a pointer to 153 | // a compatible type for the JSON body. 154 | // 155 | // Type conversion is done if required; based on v's underlying type. 156 | // If v points to a struct and request body is a json array, 157 | // an attempt is made to decode to a slice of the struct and the 158 | // first element of the slice will be stored in v. 159 | // 160 | // Likewise if v points to a slice and request body is a json object, 161 | // an attempt is made to decode to the item type of the slice and a slice 162 | // containing the item will be stored in v. 163 | // 164 | // var v []Type // c.DecodeJSONBody(&v) works even if body is a json object. 165 | // var v Type // c.DecodeJSONBody(&v) works even if body is a json array. 166 | func (c *Context) DecodeJSONBody(v interface{}) error { 167 | if c.jsonDecoder == nil { 168 | if err := c.jsonDecoder.init(c.Request.Body); err != nil { 169 | return err 170 | } 171 | } 172 | return c.jsonDecoder.decode(v) 173 | } 174 | 175 | /* net/context / Go 1.7 Request.Context */ 176 | 177 | // Deadline returns the time when work done on behalf of this context 178 | // should be canceled. Deadline returns ok==false when no deadline is 179 | // set. Successive calls to Deadline return the same results. 180 | func (c *Context) Deadline() (deadline time.Time, ok bool) { 181 | return 182 | } 183 | 184 | // Done returns a channel that's closed when work done on behalf of this 185 | // context should be canceled. Done may return nil if this context can 186 | // never be canceled. Successive calls to Done return the same value. 187 | func (c *Context) Done() <-chan struct{} { 188 | return nil 189 | } 190 | 191 | // Err returns a non-nil error value after Done is closed. Err returns 192 | // Canceled if the context was canceled or DeadlineExceeded if the 193 | // context's deadline passed. No other values for Err are defined. 194 | // After Done is closed, successive calls to Err return the same value. 195 | func (c *Context) Err() error { 196 | return nil 197 | } 198 | 199 | // Value returns the value associated with this context for key, or nil 200 | // if no value is associated with key. Successive calls to Value with 201 | // the same key returns the same result. 202 | func (c *Context) Value(key interface{}) interface{} { 203 | if k, ok := key.(string); ok { 204 | return c.Get(k) 205 | } 206 | return nil 207 | } 208 | -------------------------------------------------------------------------------- /endpoint.go: -------------------------------------------------------------------------------- 1 | package river 2 | 3 | import ( 4 | "net/http" 5 | "reflect" 6 | ) 7 | 8 | // Handler is an endpoint handler with support for dependency injection. 9 | // Any function type (including http.Handler) is a valid Handler. 10 | // Function parameters will be injected accordingly. 11 | // 12 | // If a service is not previously registered and it is not one of 13 | // *river.Context, http.ResponseWriter and *http.Request, zero value of the type 14 | // (or nil if the type is a pointer) will be passed as the parameter. 15 | // 16 | // If there is an attempt to register a non function type as 17 | // a request handler, a panic occurs immediately. This 18 | // prevents possible runtime panic. 19 | // 20 | // The return values of the function (if any) are discarded. 21 | type Handler interface{} 22 | 23 | // Endpoint is a REST endpoint. 24 | type Endpoint struct { 25 | handlers map[string]endpointHandlers 26 | renderer Renderer 27 | middlewareChain 28 | serviceInjector 29 | } 30 | 31 | // NewEndpoint creates a new Endpoint. 32 | func NewEndpoint() *Endpoint { 33 | return &Endpoint{ 34 | handlers: make(map[string]endpointHandlers), 35 | } 36 | } 37 | 38 | // Get sets the function for Get requests. 39 | func (e *Endpoint) Get(p string, h Handler) *Endpoint { 40 | e.set(p, "GET", h) 41 | return e 42 | } 43 | 44 | // Post sets the function for Post requests. 45 | func (e *Endpoint) Post(p string, h Handler) *Endpoint { 46 | e.set(p, "POST", h) 47 | return e 48 | } 49 | 50 | // Put sets the function for Put requests. 51 | func (e *Endpoint) Put(p string, h Handler) *Endpoint { 52 | e.set(p, "PUT", h) 53 | return e 54 | } 55 | 56 | // Patch sets the function for Patch requests. 57 | func (e *Endpoint) Patch(p string, h Handler) *Endpoint { 58 | e.set(p, "PATCH", h) 59 | return e 60 | } 61 | 62 | // Delete sets the function for Delete requests. 63 | func (e *Endpoint) Delete(p string, h Handler) *Endpoint { 64 | e.set(p, "DELETE", h) 65 | return e 66 | } 67 | 68 | // Options sets the function for Options requests. 69 | func (e *Endpoint) Options(p string, h Handler) *Endpoint { 70 | e.set(p, "OPTIONS", h) 71 | return e 72 | } 73 | 74 | // Renderer sets the output renderer for endpoint. 75 | func (e *Endpoint) Renderer(r Renderer) *Endpoint { 76 | e.renderer = r 77 | return e 78 | } 79 | 80 | // Handle sets the function for a custom requests. 81 | func (e *Endpoint) Handle(requestMethod, p string, h Handler) *Endpoint { 82 | e.set(p, requestMethod, h) 83 | return e 84 | } 85 | 86 | func (e *Endpoint) set(subpath string, method string, h Handler) { 87 | if e.handlers[subpath] == nil { 88 | e.handlers[subpath] = make(endpointHandlers) 89 | } 90 | mustBeHandler(h) 91 | e.handlers[subpath][method] = h 92 | } 93 | 94 | // endpointHandlers maps request method to Handler. 95 | type endpointHandlers map[string]Handler 96 | 97 | func handlerToMiddleware(h Handler) Middleware { 98 | if handler, ok := h.(Middleware); ok { 99 | return handler 100 | } 101 | if handler, ok := h.(http.Handler); ok { 102 | return toMiddleware(handler) 103 | } 104 | 105 | mustBeHandler(h) 106 | return func(c *Context) { 107 | /* default injections */ 108 | // context 109 | c.register(c) 110 | 111 | // responseWriter 112 | var rw http.ResponseWriter = c 113 | c.register(rw) 114 | 115 | // request 116 | c.register(c.Request) 117 | 118 | /* handle request */ 119 | c.invoke(h) 120 | } 121 | 122 | } 123 | 124 | func mustBeHandler(h Handler) { 125 | if reflect.TypeOf(h).Kind() != reflect.Func { 126 | // this is called in the beginning of the app, safer to panic here 127 | // and prevent possible request time panic. 128 | panic("Cannot use non function type as Handler") 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /example/main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "github.com/abiosoft/river" 4 | 5 | func main() { 6 | rv := river.New() 7 | 8 | userEndpoint := river.NewEndpoint(). 9 | Post("/", addUser). 10 | Get("/", getAllUser). 11 | Get("/:id", getUser). 12 | Put("/:id", updateUser). 13 | Delete("/:id", deleteUser) 14 | userEndpoint.Use(authMid) 15 | userEndpoint.Register(basicModel()) 16 | rv.Handle("/user", userEndpoint) 17 | 18 | infoEndpoint := river.NewEndpoint(). 19 | Get("/", sessionInfo) 20 | infoEndpoint.Use(authMid) 21 | rv.Handle("/session", infoEndpoint) 22 | 23 | authEndpoint := river.NewEndpoint(). 24 | Get("/", newAuthToken) 25 | rv.Handle("/auth", authEndpoint) 26 | 27 | panicEndpoint := river.NewEndpoint(). 28 | Get("/", func() { panic("Recovery middleware has handled this") }) 29 | rv.Handle("/panic", panicEndpoint) 30 | 31 | rv.Use(river.Recovery()) 32 | rv.Run(":8080") 33 | } 34 | -------------------------------------------------------------------------------- /example/model.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import "math/rand" 4 | 5 | // Model is a sample basic data model. 6 | type Model struct { 7 | get func(id string) interface{} 8 | getAll func() interface{} 9 | add func(items ...interface{}) 10 | put func(id string, item interface{}) 11 | delete func(id string) 12 | } 13 | 14 | func basicModel() Model { 15 | var model Model 16 | var users = []User{} 17 | search := func(id string) int { 18 | for i := range users { 19 | if users[i].ID == id { 20 | return i 21 | } 22 | } 23 | return -1 24 | } 25 | model.get = func(id string) interface{} { 26 | if i := search(id); i > -1 { 27 | return users[i] 28 | } 29 | return nil 30 | } 31 | model.getAll = func() interface{} { 32 | return users 33 | } 34 | model.add = func(items ...interface{}) { 35 | for i := range items { 36 | users = append(users, items[i].(User)) 37 | } 38 | } 39 | model.put = func(id string, item interface{}) { 40 | if i := search(id); i > -1 { 41 | users[i] = item.(User) 42 | } 43 | } 44 | model.delete = func(id string) { 45 | if i := search(id); i > -1 { 46 | part := append(users[:i]) 47 | if i < len(users)-1 { 48 | part = append(part, users[i+1:]...) 49 | } 50 | users = part 51 | } 52 | } 53 | return model 54 | } 55 | 56 | func randString(l int) (str string) { 57 | const alphaNum = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_1234567890" 58 | for i := 0; i < l; i++ { 59 | n := rand.Intn(len(alphaNum)) 60 | str += alphaNum[n : n+1] 61 | } 62 | return 63 | } 64 | -------------------------------------------------------------------------------- /example/session.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "net/http" 5 | "time" 6 | 7 | "github.com/abiosoft/river" 8 | ) 9 | 10 | // Session is basic token based session. 11 | type Session struct { 12 | Token string 13 | Created time.Time 14 | Expires time.Time 15 | } 16 | 17 | // authMid is sample authentication middleware. 18 | func authMid(c *river.Context) { 19 | token := c.Query("token") 20 | session := getSession(token) 21 | if !session.Valid() { 22 | c.Render(http.StatusUnauthorized, river.M{"error": "Unauthorized"}) 23 | return 24 | } 25 | c.Register(session) 26 | c.Next() 27 | } 28 | 29 | // newAuthToken handles GET /auth. 30 | func newAuthToken(c *river.Context) { 31 | session := newSession() 32 | c.Render(200, river.M{"token": session.Token, "expires": session.Expires}) 33 | } 34 | 35 | // sessionInfo handles GET /session. 36 | func sessionInfo(c *river.Context, session Session) { 37 | c.Render(http.StatusOK, session) 38 | } 39 | 40 | var sessions = map[string]Session{} 41 | 42 | func getSession(token string) (session Session) { 43 | if s, ok := sessions[token]; ok { 44 | session = s 45 | } 46 | return 47 | } 48 | 49 | // Valid checks if the current session is valid. 50 | func (s Session) Valid() bool { 51 | return time.Now().Before(s.Expires) 52 | } 53 | 54 | func newSession() Session { 55 | session := Session{ 56 | Token: randString(10), 57 | Created: time.Now(), 58 | Expires: time.Now().Add(time.Minute * 5), 59 | } 60 | sessions[session.Token] = session 61 | return session 62 | } 63 | -------------------------------------------------------------------------------- /example/user.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "net/http" 5 | 6 | "github.com/abiosoft/river" 7 | ) 8 | 9 | // User is user data. 10 | type User struct { 11 | ID string `json:"id"` 12 | Name string `json:"name"` 13 | } 14 | 15 | // getUser handles GET /user/:id. 16 | func getUser(c *river.Context, model Model) { 17 | user := model.get(c.Param("id")) 18 | if user == nil { 19 | c.RenderEmpty(http.StatusNotFound) 20 | return 21 | } 22 | c.Render(http.StatusOK, user) 23 | } 24 | 25 | // getAllUser handles GET /user. 26 | func getAllUser(c *river.Context, model Model) { 27 | c.Render(http.StatusOK, model.getAll()) 28 | } 29 | 30 | // addUser handles POST /user. 31 | func addUser(c *river.Context, model Model) { 32 | var users []User 33 | if err := c.DecodeJSONBody(&users); err != nil { 34 | c.Render(http.StatusBadRequest, err) 35 | return 36 | } 37 | for i := range users { 38 | model.add(users[i]) 39 | } 40 | c.Render(http.StatusCreated, users) 41 | } 42 | 43 | // updateUser handles PUT /user/:id. 44 | func updateUser(c *river.Context, model Model) { 45 | id := c.Param("id") 46 | var user User 47 | if err := c.DecodeJSONBody(&user); err != nil { 48 | c.Render(http.StatusBadRequest, err) 49 | return 50 | } 51 | model.put(id, user) 52 | c.Render(http.StatusOK, user) 53 | } 54 | 55 | // deleteUser handles DELETE /user/:id. 56 | func deleteUser(c *river.Context, model Model) { 57 | model.delete(c.Param("id")) 58 | c.RenderEmpty(http.StatusNoContent) 59 | } 60 | -------------------------------------------------------------------------------- /jsondecoder.go: -------------------------------------------------------------------------------- 1 | package river 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "io" 7 | "io/ioutil" 8 | "reflect" 9 | ) 10 | 11 | type jsonDecoder []byte 12 | 13 | func (j *jsonDecoder) init(src io.Reader) error { 14 | b, err := ioutil.ReadAll(src) 15 | *j = b 16 | return err 17 | } 18 | 19 | func (j *jsonDecoder) copy() []byte { 20 | buf := make([]byte, len(*j)) 21 | copy(buf, *j) 22 | return buf 23 | } 24 | 25 | func (j *jsonDecoder) decode(v interface{}) (err error) { 26 | defer func() { 27 | if err1 := recover(); err1 != nil { 28 | if _, ok := err1.(error); ok { 29 | err = err1.(error) 30 | } else { 31 | err = fmt.Errorf("Unidenfied error: %v", err1) 32 | } 33 | } 34 | }() 35 | 36 | if !reflect.ValueOf(v).IsValid() || reflect.TypeOf(v).Kind() != reflect.Ptr || reflect.ValueOf(v).IsNil() { 37 | return fmt.Errorf("cannot marshal to %v, must be pointer and not nil", reflect.TypeOf(v).String()) 38 | } 39 | 40 | if err := json.Unmarshal(j.copy(), &v); err == nil { 41 | return nil 42 | } else if _, ok := err.(*json.UnmarshalTypeError); !ok { 43 | // not type related error 44 | return err 45 | } 46 | 47 | var elem reflect.Value 48 | 49 | if reflect.ValueOf(v).Elem().Kind() == reflect.Slice { 50 | // if type is slice, attempt an element of the slice 51 | // and return a slice containing the element. 52 | item := reflect.New(reflect.ValueOf(v).Elem().Type().Elem()) 53 | if err := json.Unmarshal(j.copy(), item.Interface()); err != nil { 54 | return err 55 | } 56 | elem = reflect.Append(reflect.ValueOf(v).Elem(), item.Elem()) 57 | } else if reflect.ValueOf(v).Elem().Kind() == reflect.Struct { 58 | // if type is a struct, attempt a slice of the struct 59 | // and return first element of the slice. 60 | slice := reflect.New(reflect.SliceOf(reflect.TypeOf(v).Elem())) 61 | if err := json.Unmarshal(j.copy(), slice.Interface()); err != nil { 62 | return err 63 | } 64 | elem = slice.Elem().Index(0) 65 | } else { 66 | return fmt.Errorf("Cannot unmarshal to type %v", reflect.ValueOf(v).Elem().Type()) 67 | } 68 | 69 | reflect.ValueOf(v).Elem().Set(elem) 70 | return nil 71 | } 72 | -------------------------------------------------------------------------------- /jsondecoder_test.go: -------------------------------------------------------------------------------- 1 | package river 2 | 3 | import ( 4 | "fmt" 5 | "testing" 6 | ) 7 | 8 | func TestJsonDecoder(t *testing.T) { 9 | type A struct{ Name string } 10 | itemTests := []struct { 11 | body string 12 | obj A 13 | expected interface{} 14 | }{ 15 | { 16 | `{"name": "Some Name"}`, 17 | A{}, 18 | A{Name: "Some Name"}, 19 | }, 20 | { 21 | `[{"name": "Some Name"}]`, 22 | A{}, 23 | A{Name: "Some Name"}, 24 | }, 25 | } 26 | 27 | for i, test := range itemTests { 28 | decoder := jsonDecoder([]byte(test.body)) 29 | err := decoder.decode(&test.obj) 30 | if err != nil { 31 | t.Errorf("Struct Test %d: %v", i, err) 32 | } 33 | val, exp := fmt.Sprint(test.obj), fmt.Sprint(test.expected) 34 | if val != exp { 35 | t.Errorf("Test %d: expected %s, found %s", i, exp, val) 36 | } 37 | } 38 | 39 | sliceTests := []struct { 40 | body string 41 | obj []A 42 | expected interface{} 43 | }{ 44 | { 45 | `{"name": "Some Name"}`, 46 | nil, 47 | []A{{Name: "Some Name"}}, 48 | }, 49 | { 50 | `[{"name": "Some Name"}]`, 51 | nil, 52 | []A{{Name: "Some Name"}}, 53 | }, 54 | } 55 | 56 | for i, test := range sliceTests { 57 | decoder := jsonDecoder([]byte(test.body)) 58 | err := decoder.decode(&test.obj) 59 | if err != nil { 60 | t.Errorf("Struct Test %d: %v", i, err) 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /log.go: -------------------------------------------------------------------------------- 1 | package river 2 | 3 | import ( 4 | "fmt" 5 | oslog "log" 6 | "os" 7 | "time" 8 | 9 | humanize "github.com/dustin/go-humanize" 10 | "github.com/fatih/color" 11 | ) 12 | 13 | var ( 14 | // Log is the logger. This can be replaced or set to nil. 15 | Log = oslog.New(os.Stdout, "[River] ", 0) 16 | 17 | // LogRequests enables request log. Useful for development. 18 | LogRequests = true 19 | 20 | log riverLog 21 | ) 22 | 23 | type riverLog struct{} 24 | 25 | func (r riverLog) println(v ...interface{}) { 26 | if Log != nil { 27 | Log.Println(v...) 28 | } 29 | } 30 | 31 | func (r riverLog) printf(format string, v ...interface{}) { 32 | if Log != nil { 33 | Log.Printf(format, v...) 34 | } 35 | } 36 | 37 | func (r riverLog) prefix() string { 38 | if Log != nil { 39 | return Log.Prefix() 40 | } 41 | return "" 42 | } 43 | 44 | // requestLogger is a middleware that logs requests in a colourful way. 45 | func requestLogger() Middleware { 46 | return func(c *Context) { 47 | start := time.Now() 48 | 49 | c.Next() 50 | 51 | duration := time.Since(start) 52 | 53 | bg := color.BgBlack 54 | switch { 55 | case c.Status() >= 200 && c.Status() < 300: 56 | bg = color.BgGreen 57 | case c.Status() >= 300 && c.Status() < 400: 58 | bg = color.BgBlue 59 | case c.Status() >= 400 && c.Status() < 500: 60 | bg = color.BgYellow 61 | case c.Status() >= 500 && c.Status() < 600: 62 | bg = color.BgRed 63 | } 64 | 65 | paint := color.New(bg, color.FgWhite, color.Bold).SprintFunc() 66 | status := paint(fmt.Sprintf(" %d ", c.Status())) 67 | size := humanize.Bytes(uint64(c.Written())) 68 | 69 | fmt.Printf("%s%v|%s|%15v|%6s|%-4s %s\n", 70 | log.prefix(), 71 | time.Now().Format("2006-01-02 15:04:05"), 72 | status, duration, size, c.Method, c.URL.Path, 73 | ) 74 | 75 | } 76 | } 77 | -------------------------------------------------------------------------------- /middleware.go: -------------------------------------------------------------------------------- 1 | package river 2 | 3 | import "net/http" 4 | 5 | // Middleware is River middleware. 6 | // A middleware needs to call c.Next() 7 | // for request to continue to other middlewares. 8 | // func (c *river.Context){ 9 | // // do something before 10 | // c.Next() 11 | // // do something after 12 | // } 13 | type Middleware func(*Context) 14 | 15 | // middlewareChain is chain of middlewares. 16 | type middlewareChain []Middleware 17 | 18 | // Use adds middlewares to the middleware chain. 19 | func (c *middlewareChain) Use(middlewares ...Middleware) { 20 | *c = append(*c, middlewares...) 21 | } 22 | 23 | // UseHandler adds any http.Handler as middleware to the middleware chain. 24 | func (c *middlewareChain) UseHandler(middlewares ...http.Handler) { 25 | for i := range middlewares { 26 | c.Use(toMiddleware(middlewares[i])) 27 | } 28 | } 29 | 30 | func toMiddleware(h http.Handler) Middleware { 31 | return func(c *Context) { 32 | h.ServeHTTP(c, c.Request) 33 | c.Next() 34 | } 35 | } 36 | 37 | // Recovery creates a panic recovery middleware. 38 | // handlers are called after recovery. 39 | func Recovery(handlers ...func(c *Context, err interface{})) Middleware { 40 | return func(c *Context) { 41 | defer func() { 42 | if err := recover(); err != nil { 43 | if handlers != nil { 44 | for i := range handlers { 45 | handlers[i](c, err) 46 | } 47 | } else { 48 | c.Render(http.StatusInternalServerError, err) 49 | } 50 | } 51 | }() 52 | c.Next() 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /renderer.go: -------------------------------------------------------------------------------- 1 | package river 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | ) 7 | 8 | // M is a convenience wrapper for map[string]interface{}. 9 | // M{"status": "success, "data": M{"id": 1, "type": "complex"}} 10 | type M map[string]interface{} 11 | 12 | // Renderer renders data in a specified format. 13 | // Renderer should set Content-Type accordingly. 14 | type Renderer func(c *Context, data interface{}) error 15 | 16 | // JSONRenderer is json renderer. 17 | func JSONRenderer(c *Context, data interface{}) error { 18 | c.Header().Set("Content-Type", "application/json") 19 | return json.NewEncoder(c).Encode(data) 20 | } 21 | 22 | // PlainRenderer is plain text renderer. 23 | func PlainRenderer(c *Context, data interface{}) error { 24 | c.Header().Set("Content-Type", "text/plain") 25 | _, err := fmt.Fprint(c, data) 26 | return err 27 | } 28 | 29 | // ErrHandler handles error returned by Renderer. 30 | type ErrHandler func(c *Context, err error) 31 | -------------------------------------------------------------------------------- /river.go: -------------------------------------------------------------------------------- 1 | package river 2 | 3 | import ( 4 | "net/http" 5 | "path" 6 | 7 | "github.com/julienschmidt/httprouter" 8 | ) 9 | 10 | // River is a REST server handler and toolkit. 11 | type River struct { 12 | r *httprouter.Router 13 | middlewareChain 14 | renderer Renderer 15 | serviceInjector 16 | errHandler ErrHandler 17 | verbose 18 | } 19 | 20 | // New creates a new River and initiates with middlewares. 21 | // Middlewares can also be added with river.Use* methods. 22 | // 23 | // Renderer defaults to JSONRenderer. 24 | func New(middlewares ...Middleware) *River { 25 | r := httprouter.New() 26 | r.HandleMethodNotAllowed = true 27 | r.HandleOPTIONS = true 28 | r.RedirectTrailingSlash = true 29 | 30 | return (&River{r: r, middlewareChain: middlewares}). 31 | NotFound(notFound). 32 | NotAllowed(notAllowed). 33 | Renderer(JSONRenderer) 34 | } 35 | 36 | func (rv *River) ServeHTTP(w http.ResponseWriter, r *http.Request) { 37 | rv.r.ServeHTTP(w, r) 38 | } 39 | 40 | // Handle handles endpoint at path p. 41 | // This should only be called after Endpoint requests have been handled. 42 | func (rv *River) Handle(p string, e *Endpoint) *River { 43 | rv.handle(p, e) 44 | return rv 45 | } 46 | 47 | func (rv *River) routerHandle(h Handler, e *Endpoint) httprouter.Handle { 48 | return func(w http.ResponseWriter, r *http.Request, p httprouter.Params) { 49 | c := &Context{ 50 | rw: w, 51 | Request: r, 52 | params: p, 53 | renderer: notNilRenderer(e.renderer, rv.renderer), 54 | middlewares: composeMiddlewares(rv, handlerToMiddleware(h), e), 55 | serviceInjector: copyInjectors(rv.serviceInjector, e.serviceInjector), 56 | } 57 | c.Next() 58 | } 59 | } 60 | 61 | func (rv *River) routerHandleNoEndpoint(handler Middleware) http.HandlerFunc { 62 | return func(w http.ResponseWriter, r *http.Request) { 63 | c := &Context{ 64 | rw: w, 65 | Request: r, 66 | renderer: notNilRenderer(rv.renderer), 67 | middlewares: composeMiddlewares(rv, handler, nil), 68 | serviceInjector: copyInjectors(rv.serviceInjector), 69 | } 70 | c.Next() 71 | } 72 | } 73 | 74 | func (rv *River) handle(p string, e *Endpoint) { 75 | for subPath := range e.handlers { 76 | fullPath := path.Join(p, subPath) 77 | for method, handler := range e.handlers[subPath] { 78 | rv.r.Handle(method, fullPath, rv.routerHandle(handler, e)) 79 | rv.handledPaths.add(method, fullPath, nameOf(handler)) 80 | } 81 | } 82 | } 83 | 84 | // Run starts River as an http server. 85 | func (rv *River) Run(addr string) error { 86 | log.printf("Server started on %s", addr) 87 | rv.Dump() 88 | return http.ListenAndServe(addr, rv) 89 | } 90 | 91 | // Renderer sets output renderer. 92 | // An endpoint renderer overrules this. 93 | func (rv *River) Renderer(r Renderer) *River { 94 | rv.renderer = r 95 | return rv 96 | } 97 | 98 | // NotAllowed replaces the default handler for methods not handled by 99 | // any endpoint with h. 100 | func (rv *River) NotAllowed(h Handler) *River { 101 | if handler, ok := h.(Middleware); ok { 102 | rv.r.MethodNotAllowed = rv.routerHandleNoEndpoint(handler) 103 | } else { 104 | rv.r.MethodNotAllowed = rv.routerHandleNoEndpoint(handlerToMiddleware(h)) 105 | } 106 | return rv 107 | } 108 | 109 | // NotFound replaces the default handler for request paths without 110 | // any endpoint. 111 | func (rv *River) NotFound(h Handler) *River { 112 | if handler, ok := h.(Middleware); ok { 113 | rv.r.NotFound = rv.routerHandleNoEndpoint(handler) 114 | } else { 115 | rv.r.NotFound = rv.routerHandleNoEndpoint(handlerToMiddleware(h)) 116 | } 117 | return rv 118 | } 119 | 120 | // RenderError sets the handler that handles error 121 | // returned by a Renderer. 122 | func (rv *River) RenderError(h ErrHandler) *River { 123 | rv.errHandler = h 124 | return rv 125 | } 126 | 127 | func composeMiddlewares(rv *River, h Middleware, e *Endpoint) []Middleware { 128 | var middlewares []Middleware 129 | if e != nil { 130 | middlewares = append(rv.middlewareChain, append(e.middlewareChain, h)...) 131 | } else { 132 | middlewares = append(rv.middlewareChain, h) 133 | } 134 | if LogRequests { 135 | middlewares = append([]Middleware{requestLogger()}, middlewares...) 136 | } 137 | return middlewares 138 | } 139 | 140 | func notFound(c *Context) { 141 | c.Render(http.StatusNotFound, http.StatusText(http.StatusNotFound)) 142 | } 143 | 144 | func notAllowed(c *Context) { 145 | c.Render(http.StatusMethodNotAllowed, http.StatusText(http.StatusNotFound)) 146 | } 147 | 148 | func notNilRenderer(r ...Renderer) Renderer { 149 | for i := range r { 150 | if r[i] != nil { 151 | return r[i] 152 | } 153 | } 154 | return PlainRenderer 155 | } 156 | -------------------------------------------------------------------------------- /serviceinjector.go: -------------------------------------------------------------------------------- 1 | package river 2 | 3 | import "reflect" 4 | 5 | type serviceInjector map[reflect.Type]interface{} 6 | 7 | // Register registers a new service. Services are identifiable by their types. 8 | // Multiple services of same type should be grouped into a struct, 9 | // and the struct should be registered instead. 10 | func (s *serviceInjector) Register(service interface{}) { 11 | // don't allow context override 12 | if reflect.TypeOf(service) == reflect.TypeOf(&Context{}) { 13 | return 14 | } 15 | s.register(service) 16 | } 17 | 18 | func (s *serviceInjector) register(service interface{}) { 19 | if *s == nil { 20 | *s = make(serviceInjector) 21 | } 22 | (*s)[reflect.TypeOf(service)] = service 23 | } 24 | 25 | // invoke invokes function f. f must be Func type. 26 | func (s serviceInjector) invoke(f interface{}) { 27 | if reflect.TypeOf(f).Kind() != reflect.Func { 28 | // log and return to prevent panic. 29 | log.println("Cannot invoke non function type") 30 | return 31 | } 32 | 33 | args := make([]reflect.Value, reflect.TypeOf(f).NumIn()) 34 | for i := range args { 35 | argType := reflect.TypeOf(f).In(i) 36 | if service, ok := s[argType]; ok { 37 | args[i] = reflect.ValueOf(service) 38 | } else { 39 | // set zero value 40 | args[i] = reflect.Zero(argType) 41 | } 42 | } 43 | reflect.ValueOf(f).Call(args) 44 | } 45 | 46 | func copyInjectors(injectors ...serviceInjector) serviceInjector { 47 | var s = serviceInjector{} 48 | for i := range injectors { 49 | for j := range injectors[i] { 50 | s[j] = injectors[i][j] 51 | } 52 | } 53 | return s 54 | } 55 | -------------------------------------------------------------------------------- /serviceinjector_test.go: -------------------------------------------------------------------------------- 1 | package river 2 | 3 | import ( 4 | "reflect" 5 | "testing" 6 | ) 7 | 8 | type A struct{ a string } 9 | 10 | func newInjector() serviceInjector { 11 | var injector serviceInjector 12 | var a = A{"a"} 13 | injector.Register(a) 14 | return injector 15 | } 16 | 17 | func TestServiceInjector_Register(t *testing.T) { 18 | injector := newInjector() 19 | var a A 20 | if _, ok := injector[reflect.TypeOf(a)]; !ok { 21 | t.Error("a is not registered") 22 | } 23 | } 24 | 25 | func TestServiceInjector_invoke(t *testing.T) { 26 | injector := newInjector() 27 | injector.invoke(func(a A) { 28 | if a.a != "a" { 29 | t.Error("invoke failed") 30 | } 31 | }) 32 | } 33 | 34 | func TestServiceInjector_merge(t *testing.T) { 35 | stringType := reflect.TypeOf("") 36 | injector := newInjector() 37 | injector = copyInjectors(serviceInjector{ 38 | stringType: "some string", 39 | }) 40 | if _, ok := injector[stringType]; !ok { 41 | t.Error("injector should include string") 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /verbose.go: -------------------------------------------------------------------------------- 1 | package river 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "reflect" 7 | "runtime" 8 | ) 9 | 10 | type verbose struct { 11 | handledPaths handledPaths 12 | } 13 | 14 | // Dump dumps all endpoints that are being handled to the log. 15 | func (v verbose) Dump() { 16 | var b bytes.Buffer 17 | fmt.Fprintln(&b) 18 | fmt.Fprintln(&b, "Endpoints") 19 | fmt.Fprintln(&b, "---------") 20 | for _, hp := range v.handledPaths { 21 | fmt.Fprintf(&b, "%-8s %-25s %s\n", hp.method, hp.path, hp.handler) 22 | } 23 | log.println(b.String()) 24 | } 25 | 26 | type handledPath struct { 27 | path, method, handler string 28 | } 29 | 30 | type handledPaths []handledPath 31 | 32 | func (h *handledPaths) add(method, path string, handler string) { 33 | *h = append(*h, handledPath{path: path, method: method, handler: handler}) 34 | } 35 | 36 | func nameOf(f interface{}) string { 37 | return runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name() 38 | } 39 | --------------------------------------------------------------------------------