├── .gitignore ├── LICENSE ├── README.md ├── adatper.go ├── error.go ├── error_test.go ├── form_helper.go ├── go.mod ├── go.sum ├── go113.go ├── group.go ├── interface.go ├── plugin.go ├── pre_go113.go ├── types.go ├── types_test.go ├── wrapper.go └── wrapper_test.go /.gitignore: -------------------------------------------------------------------------------- 1 | /.idea 2 | .DS_Store 3 | -------------------------------------------------------------------------------- /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 | # fn 2 | 3 | This library aims to simplify the construction of JSON API service, 4 | `fn.Wrap` is able to wrap any function to adapt the interface of 5 | `http.Handler`, which unmarshals POST data to a struct automatically. 6 | 7 | ## Benchmark 8 | 9 | ``` 10 | BenchmarkIsBuiltinType-8 50000000 33.5 ns/op 0 B/op 0 allocs/op 11 | BenchmarkSimplePlainAdapter_Invoke-8 2000000 757 ns/op 195 B/op 3 allocs/op 12 | BenchmarkSimpleUnaryAdapter_Invoke-8 2000000 681 ns/op 946 B/op 5 allocs/op 13 | BenchmarkGenericAdapter_Invoke-8 2000000 708 ns/op 946 B/op 5 allocs/op 14 | ``` 15 | 16 | ## Support types 17 | 18 | ``` 19 | io.ReadCloser // request.Body 20 | http.Header // request.Header 21 | fn.Form // request.Form 22 | fn.PostForm // request.PostForm 23 | *fn.Form // request.Form 24 | *fn.PostForm // request.PostForm 25 | *url.URL // request.URL 26 | *multipart.Form // request.MultipartForm 27 | *http.Request // raw request 28 | ``` 29 | 30 | ## Usage 31 | 32 | ```go 33 | http.Handle("/test", fn.Wrap(test)) 34 | 35 | func test(io.ReadCloser, http.Header, fn.Form, fn.PostForm, *CustomizedRequestType, *url.URL, *multipart.Form) (*CustomizedResponseType, error) 36 | ``` 37 | 38 | ## Examples 39 | 40 | ### Basic 41 | 42 | ```go 43 | package examples 44 | 45 | import ( 46 | "io" 47 | "mime/multipart" 48 | "net/http" 49 | "net/url" 50 | 51 | "github.com/pingcap/fn" 52 | ) 53 | 54 | type Request struct { 55 | Username string `json:"username"` 56 | Password string `json:"password"` 57 | } 58 | 59 | type Response struct { 60 | Token string `json:"token"` 61 | } 62 | 63 | func api1() (*Response, error) { 64 | return &Response{Token: "token"}, nil 65 | } 66 | 67 | func api2(request *Request) (*Response, error) { 68 | token := request.Username + request.Password 69 | return &Response{Token: token}, nil 70 | } 71 | 72 | func api3(rawreq *http.Request, request *Request) (*Response, error) { 73 | token := request.Username + request.Password 74 | return &Response{Token: token}, nil 75 | } 76 | 77 | func api4(rawreq http.Header, request *Request) (*Response, error) { 78 | token := request.Username + request.Password 79 | return &Response{Token: token}, nil 80 | } 81 | 82 | func api5(form *fn.Form, request *Request) (*Response, error) { 83 | token := request.Username + request.Password + form.Get("type") 84 | return &Response{Token: token}, nil 85 | } 86 | 87 | func api6(body io.ReadCloser, request *Request) (*Response, error) { 88 | token := request.Username + request.Password 89 | return &Response{Token: token}, nil 90 | } 91 | 92 | func api7(form *multipart.Form, request *Request) (*Response, error) { 93 | token := request.Username + request.Password 94 | return &Response{Token: token}, nil 95 | } 96 | 97 | func api7(urls *url.URL, request *Request) (*Response, error) { 98 | token := request.Username + request.Password 99 | return &Response{Token: token}, nil 100 | } 101 | 102 | func api8(urls *url.URL, form *multipart.Form, body io.ReadCloser, rawreq http.Header, request *Request) (*Response, error) { 103 | token := request.Username + request.Password 104 | return &Response{Token: token}, nil 105 | } 106 | ``` 107 | 108 | ### Plugins 109 | 110 | ```go 111 | package examples 112 | 113 | import ( 114 | "context" 115 | "errors" 116 | "io" 117 | "log" 118 | "mime/multipart" 119 | "net/http" 120 | "net/url" 121 | "strings" 122 | 123 | "github.com/pingcap/fn" 124 | ) 125 | 126 | var PermissionDenied = errors.New("permission denied") 127 | 128 | func logger(ctx context.Context, req *http.Request) (context.Context, error) { 129 | log.Println("Request", req.RemoteAddr, req.URL.String()) 130 | return ctx, nil 131 | } 132 | 133 | func ipWhitelist(ctx context.Context, req *http.Request) (context.Context, error) { 134 | if strings.HasPrefix(req.RemoteAddr, "172.168") { 135 | return ctx, PermissionDenied 136 | } 137 | return ctx, nil 138 | } 139 | 140 | func auth(ctx context.Context, req *http.Request) (context.Context, error) { 141 | token := req.Header.Get("X-Auth-token") 142 | _ = token // Validate token (e.g: query db) 143 | if token != "valid" { 144 | return ctx, fn.ErrorWithStatusCode(PermissionDenied, http.StatusForbidden) 145 | } 146 | return ctx, nil 147 | } 148 | 149 | type Request struct { 150 | Username string `json:"username"` 151 | Password string `json:"password"` 152 | } 153 | 154 | type Response struct { 155 | Token string `json:"token"` 156 | } 157 | 158 | func example() { 159 | fn.Plugin(logger, ipWhitelist, auth) 160 | http.Handle("/api1", fn.Wrap(api1)) 161 | http.Handle("/api2", fn.Wrap(api2)) 162 | } 163 | 164 | // api1 and api2 request have be validated by `ipWhitelist` and `auth` 165 | 166 | func api1() (*Response, error) { 167 | return &Response{Token: "token"}, nil 168 | } 169 | 170 | func api2(request *Request) (*Response, error) { 171 | token := request.Username + request.Password 172 | return &Response{Token: token}, nil 173 | } 174 | ``` 175 | 176 | ### `fn.Group` 177 | 178 | ```go 179 | package examples 180 | 181 | import ( 182 | "context" 183 | "errors" 184 | "io" 185 | "log" 186 | "mime/multipart" 187 | "net/http" 188 | "net/url" 189 | "strings" 190 | 191 | "github.com/pingcap/fn" 192 | ) 193 | 194 | var PermissionDenied = errors.New("permission denied") 195 | 196 | func logger(ctx context.Context, req *http.Request) (context.Context, error) { 197 | log.Println("Request", req.RemoteAddr, req.URL.String()) 198 | return ctx, nil 199 | } 200 | 201 | func ipWhitelist(ctx context.Context, req *http.Request) (context.Context, error) { 202 | if strings.HasPrefix(req.RemoteAddr, "172.168") { 203 | return ctx, PermissionDenied 204 | } 205 | return ctx, nil 206 | } 207 | 208 | func auth(ctx context.Context, req *http.Request) (context.Context, error) { 209 | token := req.Header.Get("X-Auth-token") 210 | _ = token // Validate token (e.g: query db) 211 | if token != "valid" { 212 | return ctx, fn.ErrorWithStatusCode(PermissionDenied, http.StatusForbidden) 213 | } 214 | return ctx, nil 215 | } 216 | 217 | type User struct { 218 | Balance int64 219 | } 220 | 221 | func queryUserFromRedis(ctx context.Context, req *http.Request) (context.Context, error) { 222 | token := req.Header.Get("X-Auth-token") 223 | _ = token // Validate token (e.g: query db) 224 | if token != "valid" { 225 | return ctx, fn.ErrorWithStatusCode(PermissionDenied, http.StatusForbidden) 226 | } 227 | user := &User{ 228 | Balance: 10000, // balance from redis 229 | } 230 | return context.WithValue(ctx, "user", user), nil 231 | } 232 | 233 | type Response struct { 234 | Balance int64 `json:"balance"` 235 | } 236 | 237 | func example() { 238 | // Global plugins 239 | fn.Plugin(logger, ipWhitelist, auth) 240 | 241 | group := fn.NewGroup() 242 | 243 | // Group plugins 244 | group.Plugin(queryUserFromRedis) 245 | http.Handle("/user/balance", group.Wrap(fetchBalance)) 246 | http.Handle("/user/buy", group.Wrap(buy)) 247 | } 248 | 249 | func fetchBalance(ctx context.Context) (*Response, error) { 250 | user := ctx.Value("user").(*User) 251 | return &Response{Balance: user.Balance}, nil 252 | } 253 | 254 | func buy(ctx context.Context) (*Response, error) { 255 | user := ctx.Value("user").(*User) 256 | if user.Balance < 100 { 257 | return nil, errors.New("please check balance") 258 | } 259 | user.Balance -= 100 260 | return &Response{Balance: user.Balance}, nil 261 | } 262 | ``` 263 | 264 | ### ResponseEncoder 265 | 266 | ```go 267 | package examples 268 | 269 | import ( 270 | "context" 271 | "errors" 272 | "io" 273 | "log" 274 | "mime/multipart" 275 | "net/http" 276 | "net/url" 277 | "strings" 278 | 279 | "github.com/pingcap/fn" 280 | ) 281 | 282 | var PermissionDenied = errors.New("permission denied") 283 | 284 | func logger(ctx context.Context, req *http.Request) (context.Context, error) { 285 | log.Println("Request", req.RemoteAddr, req.URL.String()) 286 | return ctx, nil 287 | } 288 | 289 | func ipWhitelist(ctx context.Context, req *http.Request) (context.Context, error) { 290 | if strings.HasPrefix(req.RemoteAddr, "172.168") { 291 | return ctx, PermissionDenied 292 | } 293 | return ctx, nil 294 | } 295 | 296 | func auth(ctx context.Context, req *http.Request) (context.Context, error) { 297 | token := req.Header.Get("X-Auth-token") 298 | _ = token // Validate token (e.g: query db) 299 | if token != "valid" { 300 | return ctx, fn.ErrorWithStatusCode(PermissionDenied, http.StatusForbidden) 301 | } 302 | return ctx, nil 303 | } 304 | 305 | func injectRequest(ctx context.Context, req *http.Request) (context.Context, error) { 306 | return context.WithValue(ctx, "_rawreq", req), nil 307 | } 308 | 309 | type User struct { 310 | Balance int64 311 | } 312 | 313 | func queryUserFromRedis(ctx context.Context, req *http.Request) (context.Context, error) { 314 | token := req.Header.Get("X-Auth-token") 315 | _ = token // Validate token (e.g: query db) 316 | if token != "valid" { 317 | return ctx, fn.ErrorWithStatusCode(PermissionDenied, http.StatusForbidden) 318 | } 319 | user := &User{ 320 | Balance: 10000, // balance from redis 321 | } 322 | return context.WithValue(ctx, "user", user), nil 323 | } 324 | 325 | type Response struct { 326 | Balance int64 `json:"balance"` 327 | } 328 | 329 | type ResponseMessage struct { 330 | Code int `json:"code"` 331 | Data interface{} `json:"data"` 332 | } 333 | 334 | type ErrorMessage struct { 335 | Code int `json:"code"` 336 | Error string `json:"error"` 337 | } 338 | 339 | func example() { 340 | // Global plugins 341 | fn.Plugin(logger, ipWhitelist, auth, injectRequest) 342 | // Uniform all responses 343 | fn.SetErrorEncoder(func(ctx context.Context, err error) interface{} { 344 | req := ctx.Value("_rawreq").(*http.Request) 345 | log.Println("Error occurred: ", req.URL, err) 346 | return &ErrorMessage{ 347 | Code: -1, 348 | Error: err.Error(), 349 | } 350 | }) 351 | 352 | fn.SetResponseEncoder(func(ctx context.Context, payload interface{}) interface{} { 353 | return &ResponseMessage{ 354 | Code: 1, 355 | Data: payload, 356 | } 357 | }) 358 | 359 | group := fn.NewGroup() 360 | 361 | // Group plugins 362 | group.Plugin(queryUserFromRedis) 363 | http.Handle("/user/balance", group.Wrap(fetchBalance)) 364 | http.Handle("/user/buy", group.Wrap(buy)) 365 | } 366 | 367 | func fetchBalance(ctx context.Context) (*Response, error) { 368 | user := ctx.Value("user").(*User) 369 | return &Response{Balance: user.Balance}, nil 370 | } 371 | 372 | func buy(ctx context.Context) (*Response, error) { 373 | user := ctx.Value("user").(*User) 374 | if user.Balance < 100 { 375 | return nil, errors.New("please check balance") 376 | } 377 | user.Balance -= 100 378 | return &Response{Balance: user.Balance}, nil 379 | } 380 | ``` -------------------------------------------------------------------------------- /adatper.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 PingCAP, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package fn 16 | 17 | import ( 18 | "context" 19 | "encoding/json" 20 | "net/http" 21 | "reflect" 22 | ) 23 | 24 | // adapter represents a container that contain a handler function 25 | // and convert a it to a http.Handler 26 | type adapter interface { 27 | invoke(context.Context, http.ResponseWriter, *http.Request) (interface{}, error) 28 | } 29 | 30 | // genericAdapter represents a common adapter 31 | type genericAdapter struct { 32 | inContext bool 33 | method reflect.Value 34 | numIn int 35 | types []reflect.Type 36 | cacheArgs []reflect.Value // cache args 37 | } 38 | 39 | // Accept zero parameter adapter 40 | type simplePlainAdapter struct { 41 | inContext bool 42 | method reflect.Value 43 | cacheArgs []reflect.Value 44 | } 45 | 46 | // Accept only one parameter adapter 47 | type simpleUnaryAdapter struct { 48 | outContext bool 49 | argType reflect.Type 50 | method reflect.Value 51 | cacheArgs []reflect.Value // cache args 52 | } 53 | 54 | func makeGenericAdapter(method reflect.Value, inContext bool) *genericAdapter { 55 | var noSupportExists = false 56 | t := method.Type() 57 | numIn := t.NumIn() 58 | 59 | a := &genericAdapter{ 60 | inContext: inContext, 61 | method: method, 62 | numIn: numIn, 63 | types: make([]reflect.Type, numIn), 64 | cacheArgs: make([]reflect.Value, numIn), 65 | } 66 | 67 | for i := 0; i < numIn; i++ { 68 | in := t.In(i) 69 | if in != contextType && !isBuiltinType(in) { 70 | if noSupportExists { 71 | panic("function should accept only one customize type") 72 | } 73 | 74 | if in.Kind() != reflect.Ptr { 75 | panic("customize type should be a pointer(" + in.PkgPath() + "." + in.Name() + ")") 76 | } 77 | noSupportExists = true 78 | } 79 | a.types[i] = in 80 | } 81 | 82 | return a 83 | } 84 | 85 | func (a *genericAdapter) invoke(ctx context.Context, w http.ResponseWriter, r *http.Request) (interface{}, error) { 86 | values := a.cacheArgs 87 | for i := 0; i < a.numIn; i++ { 88 | typ := a.types[i] 89 | v, ok := supportTypes[typ] 90 | if ok { 91 | value, err := v(r) 92 | if err != nil { 93 | return nil, err 94 | } 95 | values[i] = value 96 | } else if typ == contextType { 97 | values[i] = reflect.ValueOf(ctx) 98 | } else { 99 | d := reflect.New(a.types[i].Elem()).Interface() 100 | err := json.NewDecoder(r.Body).Decode(d) 101 | if err != nil { 102 | return nil, err 103 | } 104 | values[i] = reflect.ValueOf(d) 105 | } 106 | } 107 | 108 | var err error 109 | results := a.method.Call(values) 110 | payload := results[0].Interface() 111 | if e := results[1].Interface(); e != nil { 112 | err = e.(error) 113 | } 114 | return payload, err 115 | } 116 | 117 | func (a *simplePlainAdapter) invoke(ctx context.Context, w http.ResponseWriter, r *http.Request) (interface{}, error) { 118 | if a.inContext { 119 | a.cacheArgs[0] = reflect.ValueOf(ctx) 120 | } 121 | 122 | var err error 123 | results := a.method.Call(a.cacheArgs) 124 | payload := results[0].Interface() 125 | if e := results[1].Interface(); e != nil { 126 | err = e.(error) 127 | } 128 | return payload, err 129 | } 130 | 131 | func (a *simpleUnaryAdapter) invoke(ctx context.Context, w http.ResponseWriter, r *http.Request) (interface{}, error) { 132 | data := reflect.New(a.argType.Elem()).Interface() 133 | err := json.NewDecoder(r.Body).Decode(data) 134 | if err != nil { 135 | return nil, err 136 | } 137 | 138 | a.cacheArgs[0] = reflect.ValueOf(data) 139 | results := a.method.Call(a.cacheArgs) 140 | payload := results[0].Interface() 141 | if e := results[1].Interface(); e != nil { 142 | err = e.(error) 143 | } 144 | return payload, err 145 | } 146 | -------------------------------------------------------------------------------- /error.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 PingCAP, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package fn 16 | 17 | type statusCodeError struct { 18 | err error 19 | statusCode int 20 | } 21 | 22 | type StatusCodeError interface { 23 | StatusCode() int 24 | } 25 | 26 | func (s *statusCodeError) StatusCode() int { 27 | return s.statusCode 28 | } 29 | 30 | func (s *statusCodeError) Unwrap() error { 31 | return s.err 32 | } 33 | 34 | func (s *statusCodeError) Error() string { 35 | return s.err.Error() 36 | } 37 | 38 | func UnwrapErrorStatusCode(err error) (int, bool) { 39 | for err != nil { 40 | if v, ok := err.(StatusCodeError); ok { 41 | return v.StatusCode(), true 42 | } 43 | err = Unwrap(err) 44 | } 45 | return 0, false 46 | } 47 | 48 | func ErrorWithStatusCode(err error, statusCode int) error { 49 | return &statusCodeError{err, statusCode} 50 | } 51 | -------------------------------------------------------------------------------- /error_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2020 PingCAP, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package fn 16 | 17 | import ( 18 | "errors" 19 | "net/http" 20 | "testing" 21 | 22 | "github.com/stretchr/testify/require" 23 | ) 24 | 25 | var errTest = errors.New("test") 26 | 27 | type withError struct { 28 | err error 29 | } 30 | 31 | func (w *withError) Error() string { 32 | return w.err.Error() 33 | } 34 | 35 | func (w *withError) Unwrap() error { 36 | return w.err 37 | } 38 | 39 | // TestWithError test UnwrapErrorStatusCode method 40 | func TestWithError(t *testing.T) { 41 | var err error = &withError{ 42 | err: ErrorWithStatusCode(errTest, http.StatusInternalServerError), 43 | } 44 | code, ok := UnwrapErrorStatusCode(err) 45 | require.True(t, ok) 46 | require.Equal(t, http.StatusInternalServerError, code) 47 | } 48 | 49 | // TestOriginError test ErrorWithStatusCode Unwrap 50 | func TestOriginError(t *testing.T) { 51 | err := ErrorWithStatusCode(errTest, http.StatusInternalServerError) 52 | require.Equal(t, errTest, Unwrap(err)) 53 | } 54 | -------------------------------------------------------------------------------- /form_helper.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 PingCAP, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package fn 16 | 17 | import ( 18 | "strconv" 19 | ) 20 | 21 | func (f *uniform) Int(key string) int { 22 | value := f.Get(key) 23 | if value == "" { 24 | return 0 25 | } 26 | v, err := strconv.Atoi(value) 27 | if err != nil { 28 | return 0 29 | } 30 | return v 31 | } 32 | 33 | func (f *uniform) IntOrDefault(key string, def int) int { 34 | value := f.Get(key) 35 | if value == "" { 36 | return def 37 | } 38 | v, err := strconv.Atoi(value) 39 | if err != nil { 40 | return def 41 | } 42 | return v 43 | } 44 | 45 | func (f *uniform) Int64(key string) int64 { 46 | value := f.Get(key) 47 | if value == "" { 48 | return 0 49 | } 50 | v, err := strconv.ParseInt(value, 10, 64) 51 | if err != nil { 52 | return 0 53 | } 54 | return v 55 | } 56 | 57 | func (f *uniform) Int64OrDefault(key string, def int64) int64 { 58 | value := f.Get(key) 59 | if value == "" { 60 | return def 61 | } 62 | v, err := strconv.ParseInt(value, 10, 64) 63 | if err != nil { 64 | return def 65 | } 66 | return v 67 | } 68 | 69 | func (f *uniform) Uint64(key string) uint64 { 70 | value := f.Get(key) 71 | if value == "" { 72 | return 0 73 | } 74 | v, err := strconv.ParseUint(value, 10, 64) 75 | if err != nil { 76 | return 0 77 | } 78 | return v 79 | } 80 | 81 | func (f *uniform) Uint64OrDefault(key string, def uint64) uint64 { 82 | value := f.Get(key) 83 | if value == "" { 84 | return def 85 | } 86 | v, err := strconv.ParseUint(value, 10, 64) 87 | if err != nil { 88 | return def 89 | } 90 | return v 91 | } 92 | 93 | // Get gets the first value associated with the given key. 94 | // If there are no values associated with the key, Get returns 95 | // the empty string. To access multiple values, use the map 96 | // directly. 97 | func (f *uniform) Get(key string) string { 98 | return f.Values.Get(key) 99 | } 100 | 101 | // Set sets the key to value. It replaces any existing 102 | // values. 103 | func (f *uniform) Set(key, value string) { 104 | f.Values.Set(key, value) 105 | } 106 | 107 | // Add adds the value to key. It appends to any existing 108 | // values associated with key. 109 | func (f *uniform) Add(key, value string) { 110 | f.Values.Add(key, value) 111 | } 112 | 113 | // Del deletes the values associated with key. 114 | func (f *uniform) Del(key string) { 115 | f.Values.Del(key) 116 | } 117 | 118 | // Encode encodes the values into ``URL encoded'' form 119 | // ("bar=baz&foo=quux") sorted by key. 120 | func (f *uniform) Encode() string { 121 | return f.Values.Encode() 122 | } 123 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/pingcap/fn 2 | 3 | go 1.11 4 | 5 | require ( 6 | github.com/davecgh/go-spew v1.1.1 // indirect 7 | github.com/stretchr/testify v1.7.1 8 | gopkg.in/yaml.v3 v3.0.0-20220512140231-539c8e751b99 // indirect 9 | ) 10 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 2 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 3 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 4 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= 5 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 6 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= 7 | github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= 8 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= 9 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 10 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 11 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 12 | gopkg.in/yaml.v3 v3.0.0-20220512140231-539c8e751b99 h1:dbuHpmKjkDzSOMKAWl10QNlgaZUd3V1q99xc81tt2Kc= 13 | gopkg.in/yaml.v3 v3.0.0-20220512140231-539c8e751b99/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= 14 | -------------------------------------------------------------------------------- /go113.go: -------------------------------------------------------------------------------- 1 | //go:build go1.13 2 | // +build go1.13 3 | 4 | // Copyright 2020 PingCAP, Inc. 5 | // 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | package fn 19 | 20 | import "errors" 21 | 22 | func Unwrap(err error) error { 23 | return errors.Unwrap(err) 24 | } 25 | -------------------------------------------------------------------------------- /group.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 PingCAP, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package fn 16 | 17 | // Group represents a handler group that contains same hooks 18 | type Group struct { 19 | plugins []PluginFunc 20 | } 21 | 22 | func NewGroup() *Group { 23 | return &Group{} 24 | } 25 | 26 | func (g *Group) Plugin(plugins ...PluginFunc) *Group { 27 | for _, b := range plugins { 28 | if b != nil { 29 | g.plugins = append(g.plugins, b) 30 | } 31 | } 32 | return g 33 | } 34 | 35 | func (g *Group) Wrap(f interface{}) *fn { 36 | n := Wrap(f) 37 | if length := len(g.plugins); length > 0 { 38 | n.plugins = make([]PluginFunc, length) 39 | copy(n.plugins, g.plugins) 40 | } 41 | return n 42 | } 43 | -------------------------------------------------------------------------------- /interface.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 PingCAP, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package fn 16 | 17 | import ( 18 | "reflect" 19 | ) 20 | 21 | func Wrap(f interface{}) *fn { 22 | t := reflect.TypeOf(f) 23 | if t.Kind() != reflect.Func { 24 | panic("fn only support wrap a function to http.Handler") 25 | } 26 | 27 | numOut := t.NumOut() 28 | 29 | // Supported signatures 30 | // func(...) (Response, error) 31 | if numOut != 2 { 32 | panic("unsupported function type, function return values should contain response data & error") 33 | } 34 | 35 | var ( 36 | adapter adapter 37 | numIn = t.NumIn() 38 | inContext = false 39 | ) 40 | 41 | if numIn > 0 { 42 | for i := 0; i < numIn; i++ { 43 | // Legal: func(ctx context.Context, ...) ... 44 | if t.In(i) == contextType { 45 | // Illegal: func(..., ctx context.Context, ...) ... 46 | if i != 0 { 47 | panic("the `context.Context` must be the first parameter if the signature contains `context.Context`") 48 | } 49 | // Illegal: func(..., ctx context.Context, ..., ctx2 context.Context) ... 50 | if inContext { 51 | panic("the function can receive two `context.Context`") 52 | } 53 | inContext = true 54 | } 55 | } 56 | } 57 | 58 | if numIn == 0 { 59 | // func() (Response, error) 60 | adapter = &simplePlainAdapter{ 61 | inContext: false, 62 | method: reflect.ValueOf(f), 63 | cacheArgs: []reflect.Value{}, 64 | } 65 | } else if numIn == 1 && inContext { 66 | // func(ctx context.Context) (Response, error) 67 | adapter = &simplePlainAdapter{ 68 | inContext: true, 69 | method: reflect.ValueOf(f), 70 | cacheArgs: make([]reflect.Value, 1), 71 | } 72 | } else if numIn == 1 && !isBuiltinType(t.In(0)) && t.In(0).Kind() == reflect.Ptr { 73 | // func(request *Customized) (Response, error) 74 | adapter = &simpleUnaryAdapter{ 75 | argType: t.In(0), 76 | method: reflect.ValueOf(f), 77 | cacheArgs: make([]reflect.Value, 1), 78 | } 79 | } else { 80 | // Complicated signatures 81 | // 82 | // e.g: 83 | // type LoginResponse {...} 84 | // type LoginRequest {...} 85 | // 86 | // func (header http.Header) (*LoginResponse, error) {} 87 | // func (form fn.Form) (*LoginResponse, error) {} 88 | // func (header http.Header, form fn.Form, body io.ReadCloser) (*LoginResponse, error) {} 89 | // func (header http.Header, r *LoginRequest, url *url.URL) (*LoginResponse, error) { } 90 | adapter = makeGenericAdapter(reflect.ValueOf(f), inContext) 91 | } 92 | 93 | return &fn{adapter: adapter} 94 | } 95 | 96 | func SetErrorEncoder(c ErrorEncoder) { 97 | if c == nil { 98 | panic("nil pointer to error encoder") 99 | } 100 | errorEncoder = c 101 | } 102 | 103 | func SetResponseEncoder(c ResponseEncoder) { 104 | if c == nil { 105 | panic("nil pointer to error encoder") 106 | } 107 | responseEncoder = c 108 | } 109 | 110 | func SetMultipartFormMaxMemory(m int64) { 111 | maxMemory = m 112 | } 113 | -------------------------------------------------------------------------------- /plugin.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 PingCAP, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package fn 16 | 17 | import ( 18 | "context" 19 | "net/http" 20 | ) 21 | 22 | // Global plugins, such as IP filter, logs 23 | var globalPlugins []PluginFunc 24 | 25 | type PluginFunc func(context.Context, *http.Request) (context.Context, error) 26 | 27 | func Plugin(plugins ...PluginFunc) { 28 | for _, a := range plugins { 29 | if a != nil { 30 | globalPlugins = append(globalPlugins, a) 31 | } 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /pre_go113.go: -------------------------------------------------------------------------------- 1 | //go:build !go1.13 2 | // +build !go1.13 3 | 4 | // Copyright 2020 PingCAP, Inc. 5 | // 6 | // Licensed under the Apache License, Version 2.0 (the "License"); 7 | // you may not use this file except in compliance with the License. 8 | // You may obtain a copy of the License at 9 | // 10 | // http://www.apache.org/licenses/LICENSE-2.0 11 | // 12 | // Unless required by applicable law or agreed to in writing, software 13 | // distributed under the License is distributed on an "AS IS" BASIS, 14 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | // See the License for the specific language governing permissions and 16 | // limitations under the License. 17 | 18 | package fn 19 | 20 | type wrapError interface { 21 | Unwrap() error 22 | } 23 | 24 | func Unwrap(err error) error { 25 | u, ok := err.(wrapError) 26 | if !ok { 27 | return nil 28 | } 29 | return u.Unwrap() 30 | } 31 | -------------------------------------------------------------------------------- /types.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 PingCAP, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package fn 16 | 17 | import ( 18 | "context" 19 | "io" 20 | "mime/multipart" 21 | "net/http" 22 | "net/url" 23 | "reflect" 24 | ) 25 | 26 | type valuer func(r *http.Request) (reflect.Value, error) 27 | 28 | var contextType = reflect.TypeOf((*context.Context)(nil)).Elem() 29 | 30 | // BenchmarkIsBuiltinType-8 100000000 23.1 ns/op 0 B/op 0 allocs/op 31 | var supportTypes = map[reflect.Type]valuer{ 32 | reflect.TypeOf((*io.ReadCloser)(nil)).Elem(): bodyValuer, // request.Body 33 | reflect.TypeOf((http.Header)(nil)): headerValuer, // request.Header 34 | reflect.TypeOf(Form{}): formValuer, // request.Form 35 | reflect.TypeOf(PostForm{}): postFromValuer, // request.PostFrom 36 | reflect.TypeOf((*Form)(nil)): formPtrValuer, // request.Form 37 | reflect.TypeOf((*PostForm)(nil)): postFromPtrValuer, // request.PostFrom 38 | reflect.TypeOf((*url.URL)(nil)): urlValuer, // request.URL 39 | reflect.TypeOf((*multipart.Form)(nil)): multipartValuer, // request.MultipartForm 40 | reflect.TypeOf((*http.Request)(nil)): requestValuer, // raw request 41 | } 42 | 43 | var maxMemory = int64(2 * 1024 * 1024) 44 | 45 | type uniform struct { 46 | url.Values 47 | } 48 | 49 | type Form struct { 50 | uniform 51 | } 52 | 53 | type PostForm struct { 54 | uniform 55 | } 56 | 57 | func bodyValuer(r *http.Request) (reflect.Value, error) { 58 | return reflect.ValueOf(r.Body), nil 59 | } 60 | 61 | func urlValuer(r *http.Request) (reflect.Value, error) { 62 | return reflect.ValueOf(r.URL), nil 63 | } 64 | 65 | func headerValuer(r *http.Request) (reflect.Value, error) { 66 | return reflect.ValueOf(r.Header), nil 67 | } 68 | 69 | func multipartValuer(r *http.Request) (reflect.Value, error) { 70 | err := r.ParseMultipartForm(maxMemory) 71 | if err != nil { 72 | return reflect.Value{}, err 73 | } 74 | return reflect.ValueOf(r.MultipartForm), nil 75 | } 76 | 77 | func formValuer(r *http.Request) (reflect.Value, error) { 78 | err := r.ParseForm() 79 | if err != nil { 80 | return reflect.Value{}, nil 81 | } 82 | return reflect.ValueOf(Form{uniform{r.Form}}), nil 83 | } 84 | 85 | func postFromValuer(r *http.Request) (reflect.Value, error) { 86 | err := r.ParseForm() 87 | if err != nil { 88 | return reflect.Value{}, nil 89 | } 90 | return reflect.ValueOf(PostForm{uniform{r.PostForm}}), nil 91 | } 92 | 93 | func formPtrValuer(r *http.Request) (reflect.Value, error) { 94 | err := r.ParseForm() 95 | if err != nil { 96 | return reflect.Value{}, nil 97 | } 98 | return reflect.ValueOf(&Form{uniform{r.Form}}), nil 99 | } 100 | 101 | func postFromPtrValuer(r *http.Request) (reflect.Value, error) { 102 | err := r.ParseForm() 103 | if err != nil { 104 | return reflect.Value{}, nil 105 | } 106 | return reflect.ValueOf(&PostForm{uniform{r.PostForm}}), nil 107 | } 108 | 109 | func requestValuer(r *http.Request) (reflect.Value, error) { 110 | return reflect.ValueOf(r), nil 111 | } 112 | 113 | func isBuiltinType(t reflect.Type) bool { 114 | _, ok := supportTypes[t] 115 | return ok 116 | } 117 | -------------------------------------------------------------------------------- /types_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 PingCAP, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package fn 16 | 17 | import ( 18 | "reflect" 19 | "testing" 20 | ) 21 | 22 | func BenchmarkIsBuiltinType(b *testing.B) { 23 | b.ReportAllocs() 24 | b.ResetTimer() 25 | typ := reflect.TypeOf((*Form)(nil)) 26 | for i := 0; i < b.N; i++ { 27 | isBuiltinType(typ) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /wrapper.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 PingCAP, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package fn 16 | 17 | import ( 18 | "context" 19 | "encoding/json" 20 | "net/http" 21 | "reflect" 22 | ) 23 | 24 | type ( 25 | // ErrorEncoder encode error to response body 26 | ErrorEncoder func(ctx context.Context, err error) interface{} 27 | 28 | // ResponseEncoder encode payload to response body 29 | ResponseEncoder func(ctx context.Context, payload interface{}) interface{} 30 | 31 | // fn represents a handler that contains a bundle of hooks 32 | fn struct { 33 | plugins []PluginFunc 34 | adapter adapter 35 | } 36 | ) 37 | 38 | var ( 39 | errorEncoder ErrorEncoder 40 | responseEncoder ResponseEncoder 41 | ) 42 | 43 | func failure(ctx context.Context, w http.ResponseWriter, err error) { 44 | statusCode := http.StatusBadRequest 45 | if v, ok := UnwrapErrorStatusCode(err); ok { 46 | statusCode = v 47 | } 48 | w.WriteHeader(statusCode) 49 | _ = json.NewEncoder(w).Encode(errorEncoder(ctx, err)) 50 | } 51 | 52 | func success(ctx context.Context, w http.ResponseWriter, data interface{}) { 53 | if data == nil || (reflect.ValueOf(data).Kind() == reflect.Ptr && reflect.ValueOf(data).IsNil()) { 54 | w.WriteHeader(http.StatusNoContent) 55 | } else { 56 | _ = json.NewEncoder(w).Encode(responseEncoder(ctx, data)) 57 | } 58 | } 59 | 60 | func (fn *fn) ServeHTTP(w http.ResponseWriter, r *http.Request) { 61 | w.Header().Set("Content-Type", "application/json; charset=utf-8") 62 | var ( 63 | ctx = r.Context() 64 | err error 65 | resp interface{} 66 | ) 67 | 68 | for _, b := range globalPlugins { 69 | ctx, err = b(ctx, r) 70 | if err != nil { 71 | failure(ctx, w, err) 72 | return 73 | } 74 | } 75 | 76 | for _, b := range fn.plugins { 77 | ctx, err = b(ctx, r) 78 | if err != nil { 79 | failure(ctx, w, err) 80 | return 81 | } 82 | } 83 | 84 | resp, err = fn.adapter.invoke(ctx, w, r) 85 | if err != nil { 86 | failure(ctx, w, err) 87 | return 88 | } 89 | success(ctx, w, resp) 90 | } 91 | 92 | func (fn *fn) Plugin(before ...PluginFunc) *fn { 93 | for _, b := range before { 94 | if b != nil { 95 | fn.plugins = append(fn.plugins, b) 96 | } 97 | } 98 | return fn 99 | } 100 | 101 | func init() { 102 | errorEncoder = func(ctx context.Context, err error) interface{} { 103 | return err.Error() 104 | } 105 | 106 | responseEncoder = func(ctx context.Context, payload interface{}) interface{} { 107 | return payload 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /wrapper_test.go: -------------------------------------------------------------------------------- 1 | // Copyright 2017 PingCAP, Inc. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | package fn 16 | 17 | import ( 18 | "bytes" 19 | "context" 20 | "encoding/json" 21 | "errors" 22 | "io" 23 | "io/ioutil" 24 | "mime/multipart" 25 | "net/http" 26 | "net/http/httptest" 27 | "net/url" 28 | "testing" 29 | 30 | "github.com/stretchr/testify/require" 31 | ) 32 | 33 | type testRequest struct { 34 | Foo string `json:"foo"` 35 | Bar int `json:"bar"` 36 | } 37 | type testResponse struct { 38 | Code int `json:"code"` 39 | Message string `json:"message"` 40 | } 41 | type testErrorResponse struct { 42 | Code int `json:"code"` 43 | Error string `json:"message"` 44 | } 45 | 46 | var successResponse = &testResponse{Message: "success"} 47 | 48 | func init() { 49 | Plugin( 50 | func(ctx context.Context, request *http.Request) (context.Context, error) { 51 | return context.WithValue(ctx, "global1", "globalvalue1"), nil 52 | }, 53 | nil, 54 | func(ctx context.Context, request *http.Request) (context.Context, error) { 55 | return context.WithValue(ctx, "global2", "globalvalue2"), nil 56 | }) 57 | } 58 | 59 | // acceptable function signature 60 | func withNone() (*testResponse, error) { return successResponse, nil } 61 | func withBody(io.ReadCloser) (*testResponse, error) { return successResponse, nil } 62 | func withReq(*testRequest) (*testResponse, error) { return successResponse, nil } 63 | func withHeader(http.Header) (*testResponse, error) { return successResponse, nil } 64 | func withForm(Form) (*testResponse, error) { return successResponse, nil } 65 | func withPostForm(PostForm) (*testResponse, error) { return successResponse, nil } 66 | func withFormPtr(*Form) (*testResponse, error) { return successResponse, nil } 67 | func withPostFormPtr(*PostForm) (*testResponse, error) { return successResponse, nil } 68 | func withMultipartForm(*multipart.Form) (*testResponse, error) { return successResponse, nil } 69 | func withUrl(*url.URL) (*testResponse, error) { return successResponse, nil } 70 | func withRawRequest(*http.Request) (*testResponse, error) { return successResponse, nil } 71 | 72 | func withInContext(context.Context) (*testResponse, error) { return successResponse, nil } 73 | 74 | func withInContextAndPayload(context.Context, *testRequest) (*testResponse, error) { 75 | return successResponse, nil 76 | } 77 | 78 | func withMulti(*testRequest, Form, PostForm, http.Header, *url.URL) (*testResponse, error) { 79 | return nil, nil 80 | } 81 | func withAll(io.ReadCloser, *testRequest, Form, PostForm, http.Header, *multipart.Form, *url.URL) (*testResponse, error) { 82 | return nil, nil 83 | } 84 | 85 | func TestHandler(t *testing.T) { 86 | Wrap(withNone) 87 | Wrap(withBody) 88 | Wrap(withReq) 89 | Wrap(withHeader) 90 | Wrap(withForm) 91 | Wrap(withPostForm) 92 | Wrap(withFormPtr) 93 | Wrap(withPostFormPtr) 94 | Wrap(withMultipartForm) 95 | Wrap(withUrl) 96 | Wrap(withRawRequest) 97 | Wrap(withMulti) 98 | Wrap(withAll) 99 | Wrap(withInContext) 100 | Wrap(withInContextAndPayload) 101 | } 102 | 103 | func TestPlugin(t *testing.T) { 104 | logic := func(ctx context.Context) (*testResponse, error) { 105 | require.Equal(t, "value", ctx.Value("key").(string)) 106 | require.Equal(t, "value2", ctx.Value("key2").(string)) 107 | return &testResponse{}, nil 108 | } 109 | 110 | plugin1 := func(ctx context.Context, request *http.Request) (context.Context, error) { 111 | require.Equal(t, "globalvalue1", ctx.Value("global1").(string)) 112 | require.Equal(t, "globalvalue2", ctx.Value("global2").(string)) 113 | return context.WithValue(ctx, "key", "value"), nil 114 | } 115 | 116 | plugin2 := func(ctx context.Context, request *http.Request) (context.Context, error) { 117 | require.Equal(t, "globalvalue1", ctx.Value("global1").(string)) 118 | require.Equal(t, "globalvalue2", ctx.Value("global2").(string)) 119 | require.Equal(t, "value", ctx.Value("key").(string)) 120 | return context.WithValue(ctx, "key2", "value2"), nil 121 | } 122 | 123 | handler := Wrap(logic).Plugin(plugin1, plugin2) 124 | 125 | recorder := httptest.NewRecorder() 126 | request, err := http.NewRequest(http.MethodGet, "", nil) 127 | require.NoError(t, err) 128 | handler.ServeHTTP(recorder, request) 129 | } 130 | 131 | func TestGroupPlugin(t *testing.T) { 132 | group := NewGroup() 133 | group.Plugin(func(ctx context.Context, request *http.Request) (context.Context, error) { 134 | return context.WithValue(ctx, "key", "value"), nil 135 | }) 136 | 137 | logic := func(ctx context.Context) (*testResponse, error) { 138 | require.Equal(t, "value", ctx.Value("key").(string)) 139 | return &testResponse{}, nil 140 | } 141 | handler := group.Wrap(logic) 142 | 143 | recorder := httptest.NewRecorder() 144 | request, err := http.NewRequest(http.MethodGet, "", nil) 145 | require.NoError(t, err) 146 | handler.ServeHTTP(recorder, request) 147 | } 148 | 149 | func TestSetResponseEncoder(t *testing.T) { 150 | handler := Wrap(func(ctx context.Context, request *http.Request) (context.Context, error) { 151 | return context.TODO(), nil 152 | }) 153 | 154 | testResp := &testResponse{ 155 | Code: 1, 156 | Message: "msg", 157 | } 158 | SetResponseEncoder(func(ctx context.Context, payload interface{}) interface{} { 159 | return testResp 160 | }) 161 | 162 | recorder := httptest.NewRecorder() 163 | request, err := http.NewRequest(http.MethodGet, "", nil) 164 | require.NoError(t, err) 165 | handler.ServeHTTP(recorder, request) 166 | respMsg := &testResponse{} 167 | _ = json.Unmarshal(recorder.Body.Bytes(), &respMsg) 168 | require.Equal(t, testResp, respMsg) 169 | } 170 | 171 | func TestSetErrorEncoder(t *testing.T) { 172 | handler := Wrap(func(ctx context.Context, request *http.Request) (context.Context, error) { 173 | return nil, errors.New("") 174 | }) 175 | 176 | testErrorResp := &testErrorResponse{ 177 | Code: -1, 178 | Error: "something went wrong", 179 | } 180 | SetErrorEncoder(func(ctx context.Context, err error) interface{} { 181 | return testErrorResp 182 | }) 183 | 184 | recorder := httptest.NewRecorder() 185 | request, err := http.NewRequest(http.MethodGet, "", nil) 186 | require.NoError(t, err) 187 | handler.ServeHTTP(recorder, request) 188 | 189 | respMsg := &testErrorResponse{} 190 | _ = json.Unmarshal(recorder.Body.Bytes(), &respMsg) 191 | require.Equal(t, testErrorResp, respMsg) 192 | } 193 | 194 | func TestGenericAdapter_Invoke(t *testing.T) { 195 | type CustomForm testRequest 196 | handler := Wrap(func(ctx context.Context, form *CustomForm) (context.Context, error) { 197 | return nil, nil 198 | }) 199 | recorder := httptest.NewRecorder() 200 | request, err := http.NewRequest(http.MethodGet, "", nil) 201 | require.NoError(t, err) 202 | payload := []byte(`{"for":"hello", "bar":10000}`) 203 | request.Body = ioutil.NopCloser(bytes.NewBuffer(payload)) 204 | require.NoError(t, err) 205 | handler.ServeHTTP(recorder, request) 206 | } 207 | 208 | func TestSimpleUnaryAdapter_Invoke(t *testing.T) { 209 | handler := Wrap(withReq) 210 | 211 | recorder := httptest.NewRecorder() 212 | request, err := http.NewRequest(http.MethodGet, "", nil) 213 | require.NoError(t, err) 214 | payload := []byte(`{"for":"hello", "bar":10000}`) 215 | request.Body = ioutil.NopCloser(bytes.NewBuffer(payload)) 216 | require.NoError(t, err) 217 | handler.ServeHTTP(recorder, request) 218 | } 219 | 220 | func TestErrorWithStatusCode(t *testing.T) { 221 | handler := Wrap(func(ctx context.Context, request *http.Request) (context.Context, error) { 222 | return nil, ErrorWithStatusCode(errors.New("not found"), http.StatusNotFound) 223 | }) 224 | 225 | recorder := httptest.NewRecorder() 226 | request, err := http.NewRequest(http.MethodGet, "", nil) 227 | require.NoError(t, err) 228 | handler.ServeHTTP(recorder, request) 229 | require.Equal(t, http.StatusNotFound, recorder.Code) 230 | } 231 | 232 | func BenchmarkSimplePlainAdapter_Invoke(b *testing.B) { 233 | handler := Wrap(withNone) 234 | request, err := http.NewRequest(http.MethodGet, "", nil) 235 | if err != nil { 236 | b.Fatal(err) 237 | } 238 | recorder := httptest.NewRecorder() 239 | b.ReportAllocs() 240 | b.ResetTimer() 241 | for i := 0; i < b.N; i++ { 242 | handler.ServeHTTP(recorder, request) 243 | } 244 | } 245 | 246 | func BenchmarkSimpleUnaryAdapter_Invoke(b *testing.B) { 247 | handler := Wrap(withReq) 248 | request, err := http.NewRequest(http.MethodGet, "", nil) 249 | if err != nil { 250 | b.Fatal(err) 251 | } 252 | payload := []byte(`{"for":"hello", "bar":10000}`) 253 | request.Body = ioutil.NopCloser(bytes.NewBuffer(payload)) 254 | recorder := httptest.NewRecorder() 255 | b.ReportAllocs() 256 | b.ResetTimer() 257 | for i := 0; i < b.N; i++ { 258 | handler.ServeHTTP(recorder, request) 259 | } 260 | } 261 | 262 | func BenchmarkGenericAdapter_Invoke(b *testing.B) { 263 | handler := Wrap(withMulti) 264 | request, err := http.NewRequest(http.MethodGet, "", nil) 265 | if err != nil { 266 | b.Fatal(err) 267 | } 268 | payload := []byte(`{"for":"hello", "bar":10000}`) 269 | request.Body = ioutil.NopCloser(bytes.NewBuffer(payload)) 270 | recorder := httptest.NewRecorder() 271 | b.ReportAllocs() 272 | b.ResetTimer() 273 | for i := 0; i < b.N; i++ { 274 | handler.ServeHTTP(recorder, request) 275 | } 276 | } 277 | --------------------------------------------------------------------------------