pax_global_header00006660000000000000000000000064142413602070014511gustar00rootroot0000000000000052 comment=c28df42d4275dca6dac5de4d82aad059397f4098 fn-1.0.0/000077500000000000000000000000001424136020700121125ustar00rootroot00000000000000fn-1.0.0/.gitignore000066400000000000000000000000211424136020700140730ustar00rootroot00000000000000/.idea .DS_Store fn-1.0.0/LICENSE000066400000000000000000000261351424136020700131260ustar00rootroot00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. fn-1.0.0/README.md000066400000000000000000000214601424136020700133740ustar00rootroot00000000000000# fn This library aims to simplify the construction of JSON API service, `fn.Wrap` is able to wrap any function to adapt the interface of `http.Handler`, which unmarshals POST data to a struct automatically. ## Benchmark ``` BenchmarkIsBuiltinType-8 50000000 33.5 ns/op 0 B/op 0 allocs/op BenchmarkSimplePlainAdapter_Invoke-8 2000000 757 ns/op 195 B/op 3 allocs/op BenchmarkSimpleUnaryAdapter_Invoke-8 2000000 681 ns/op 946 B/op 5 allocs/op BenchmarkGenericAdapter_Invoke-8 2000000 708 ns/op 946 B/op 5 allocs/op ``` ## Support types ``` io.ReadCloser // request.Body http.Header // request.Header fn.Form // request.Form fn.PostForm // request.PostForm *fn.Form // request.Form *fn.PostForm // request.PostForm *url.URL // request.URL *multipart.Form // request.MultipartForm *http.Request // raw request ``` ## Usage ```go http.Handle("/test", fn.Wrap(test)) func test(io.ReadCloser, http.Header, fn.Form, fn.PostForm, *CustomizedRequestType, *url.URL, *multipart.Form) (*CustomizedResponseType, error) ``` ## Examples ### Basic ```go package examples import ( "io" "mime/multipart" "net/http" "net/url" "github.com/pingcap/fn" ) type Request struct { Username string `json:"username"` Password string `json:"password"` } type Response struct { Token string `json:"token"` } func api1() (*Response, error) { return &Response{Token: "token"}, nil } func api2(request *Request) (*Response, error) { token := request.Username + request.Password return &Response{Token: token}, nil } func api3(rawreq *http.Request, request *Request) (*Response, error) { token := request.Username + request.Password return &Response{Token: token}, nil } func api4(rawreq http.Header, request *Request) (*Response, error) { token := request.Username + request.Password return &Response{Token: token}, nil } func api5(form *fn.Form, request *Request) (*Response, error) { token := request.Username + request.Password + form.Get("type") return &Response{Token: token}, nil } func api6(body io.ReadCloser, request *Request) (*Response, error) { token := request.Username + request.Password return &Response{Token: token}, nil } func api7(form *multipart.Form, request *Request) (*Response, error) { token := request.Username + request.Password return &Response{Token: token}, nil } func api7(urls *url.URL, request *Request) (*Response, error) { token := request.Username + request.Password return &Response{Token: token}, nil } func api8(urls *url.URL, form *multipart.Form, body io.ReadCloser, rawreq http.Header, request *Request) (*Response, error) { token := request.Username + request.Password return &Response{Token: token}, nil } ``` ### Plugins ```go package examples import ( "context" "errors" "io" "log" "mime/multipart" "net/http" "net/url" "strings" "github.com/pingcap/fn" ) var PermissionDenied = errors.New("permission denied") func logger(ctx context.Context, req *http.Request) (context.Context, error) { log.Println("Request", req.RemoteAddr, req.URL.String()) return ctx, nil } func ipWhitelist(ctx context.Context, req *http.Request) (context.Context, error) { if strings.HasPrefix(req.RemoteAddr, "172.168") { return ctx, PermissionDenied } return ctx, nil } func auth(ctx context.Context, req *http.Request) (context.Context, error) { token := req.Header.Get("X-Auth-token") _ = token // Validate token (e.g: query db) if token != "valid" { return ctx, fn.ErrorWithStatusCode(PermissionDenied, http.StatusForbidden) } return ctx, nil } type Request struct { Username string `json:"username"` Password string `json:"password"` } type Response struct { Token string `json:"token"` } func example() { fn.Plugin(logger, ipWhitelist, auth) http.Handle("/api1", fn.Wrap(api1)) http.Handle("/api2", fn.Wrap(api2)) } // api1 and api2 request have be validated by `ipWhitelist` and `auth` func api1() (*Response, error) { return &Response{Token: "token"}, nil } func api2(request *Request) (*Response, error) { token := request.Username + request.Password return &Response{Token: token}, nil } ``` ### `fn.Group` ```go package examples import ( "context" "errors" "io" "log" "mime/multipart" "net/http" "net/url" "strings" "github.com/pingcap/fn" ) var PermissionDenied = errors.New("permission denied") func logger(ctx context.Context, req *http.Request) (context.Context, error) { log.Println("Request", req.RemoteAddr, req.URL.String()) return ctx, nil } func ipWhitelist(ctx context.Context, req *http.Request) (context.Context, error) { if strings.HasPrefix(req.RemoteAddr, "172.168") { return ctx, PermissionDenied } return ctx, nil } func auth(ctx context.Context, req *http.Request) (context.Context, error) { token := req.Header.Get("X-Auth-token") _ = token // Validate token (e.g: query db) if token != "valid" { return ctx, fn.ErrorWithStatusCode(PermissionDenied, http.StatusForbidden) } return ctx, nil } type User struct { Balance int64 } func queryUserFromRedis(ctx context.Context, req *http.Request) (context.Context, error) { token := req.Header.Get("X-Auth-token") _ = token // Validate token (e.g: query db) if token != "valid" { return ctx, fn.ErrorWithStatusCode(PermissionDenied, http.StatusForbidden) } user := &User{ Balance: 10000, // balance from redis } return context.WithValue(ctx, "user", user), nil } type Response struct { Balance int64 `json:"balance"` } func example() { // Global plugins fn.Plugin(logger, ipWhitelist, auth) group := fn.NewGroup() // Group plugins group.Plugin(queryUserFromRedis) http.Handle("/user/balance", group.Wrap(fetchBalance)) http.Handle("/user/buy", group.Wrap(buy)) } func fetchBalance(ctx context.Context) (*Response, error) { user := ctx.Value("user").(*User) return &Response{Balance: user.Balance}, nil } func buy(ctx context.Context) (*Response, error) { user := ctx.Value("user").(*User) if user.Balance < 100 { return nil, errors.New("please check balance") } user.Balance -= 100 return &Response{Balance: user.Balance}, nil } ``` ### ResponseEncoder ```go package examples import ( "context" "errors" "io" "log" "mime/multipart" "net/http" "net/url" "strings" "github.com/pingcap/fn" ) var PermissionDenied = errors.New("permission denied") func logger(ctx context.Context, req *http.Request) (context.Context, error) { log.Println("Request", req.RemoteAddr, req.URL.String()) return ctx, nil } func ipWhitelist(ctx context.Context, req *http.Request) (context.Context, error) { if strings.HasPrefix(req.RemoteAddr, "172.168") { return ctx, PermissionDenied } return ctx, nil } func auth(ctx context.Context, req *http.Request) (context.Context, error) { token := req.Header.Get("X-Auth-token") _ = token // Validate token (e.g: query db) if token != "valid" { return ctx, fn.ErrorWithStatusCode(PermissionDenied, http.StatusForbidden) } return ctx, nil } func injectRequest(ctx context.Context, req *http.Request) (context.Context, error) { return context.WithValue(ctx, "_rawreq", req), nil } type User struct { Balance int64 } func queryUserFromRedis(ctx context.Context, req *http.Request) (context.Context, error) { token := req.Header.Get("X-Auth-token") _ = token // Validate token (e.g: query db) if token != "valid" { return ctx, fn.ErrorWithStatusCode(PermissionDenied, http.StatusForbidden) } user := &User{ Balance: 10000, // balance from redis } return context.WithValue(ctx, "user", user), nil } type Response struct { Balance int64 `json:"balance"` } type ResponseMessage struct { Code int `json:"code"` Data interface{} `json:"data"` } type ErrorMessage struct { Code int `json:"code"` Error string `json:"error"` } func example() { // Global plugins fn.Plugin(logger, ipWhitelist, auth, injectRequest) // Uniform all responses fn.SetErrorEncoder(func(ctx context.Context, err error) interface{} { req := ctx.Value("_rawreq").(*http.Request) log.Println("Error occurred: ", req.URL, err) return &ErrorMessage{ Code: -1, Error: err.Error(), } }) fn.SetResponseEncoder(func(ctx context.Context, payload interface{}) interface{} { return &ResponseMessage{ Code: 1, Data: payload, } }) group := fn.NewGroup() // Group plugins group.Plugin(queryUserFromRedis) http.Handle("/user/balance", group.Wrap(fetchBalance)) http.Handle("/user/buy", group.Wrap(buy)) } func fetchBalance(ctx context.Context) (*Response, error) { user := ctx.Value("user").(*User) return &Response{Balance: user.Balance}, nil } func buy(ctx context.Context) (*Response, error) { user := ctx.Value("user").(*User) if user.Balance < 100 { return nil, errors.New("please check balance") } user.Balance -= 100 return &Response{Balance: user.Balance}, nil } ```fn-1.0.0/adatper.go000066400000000000000000000071261424136020700140670ustar00rootroot00000000000000// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fn import ( "context" "encoding/json" "net/http" "reflect" ) // adapter represents a container that contain a handler function // and convert a it to a http.Handler type adapter interface { invoke(context.Context, http.ResponseWriter, *http.Request) (interface{}, error) } // genericAdapter represents a common adapter type genericAdapter struct { inContext bool method reflect.Value numIn int types []reflect.Type cacheArgs []reflect.Value // cache args } // Accept zero parameter adapter type simplePlainAdapter struct { inContext bool method reflect.Value cacheArgs []reflect.Value } // Accept only one parameter adapter type simpleUnaryAdapter struct { outContext bool argType reflect.Type method reflect.Value cacheArgs []reflect.Value // cache args } func makeGenericAdapter(method reflect.Value, inContext bool) *genericAdapter { var noSupportExists = false t := method.Type() numIn := t.NumIn() a := &genericAdapter{ inContext: inContext, method: method, numIn: numIn, types: make([]reflect.Type, numIn), cacheArgs: make([]reflect.Value, numIn), } for i := 0; i < numIn; i++ { in := t.In(i) if in != contextType && !isBuiltinType(in) { if noSupportExists { panic("function should accept only one customize type") } if in.Kind() != reflect.Ptr { panic("customize type should be a pointer(" + in.PkgPath() + "." + in.Name() + ")") } noSupportExists = true } a.types[i] = in } return a } func (a *genericAdapter) invoke(ctx context.Context, w http.ResponseWriter, r *http.Request) (interface{}, error) { values := a.cacheArgs for i := 0; i < a.numIn; i++ { typ := a.types[i] v, ok := supportTypes[typ] if ok { value, err := v(r) if err != nil { return nil, err } values[i] = value } else if typ == contextType { values[i] = reflect.ValueOf(ctx) } else { d := reflect.New(a.types[i].Elem()).Interface() err := json.NewDecoder(r.Body).Decode(d) if err != nil { return nil, err } values[i] = reflect.ValueOf(d) } } var err error results := a.method.Call(values) payload := results[0].Interface() if e := results[1].Interface(); e != nil { err = e.(error) } return payload, err } func (a *simplePlainAdapter) invoke(ctx context.Context, w http.ResponseWriter, r *http.Request) (interface{}, error) { if a.inContext { a.cacheArgs[0] = reflect.ValueOf(ctx) } var err error results := a.method.Call(a.cacheArgs) payload := results[0].Interface() if e := results[1].Interface(); e != nil { err = e.(error) } return payload, err } func (a *simpleUnaryAdapter) invoke(ctx context.Context, w http.ResponseWriter, r *http.Request) (interface{}, error) { data := reflect.New(a.argType.Elem()).Interface() err := json.NewDecoder(r.Body).Decode(data) if err != nil { return nil, err } a.cacheArgs[0] = reflect.ValueOf(data) results := a.method.Call(a.cacheArgs) payload := results[0].Interface() if e := results[1].Interface(); e != nil { err = e.(error) } return payload, err } fn-1.0.0/error.go000066400000000000000000000022771424136020700136020ustar00rootroot00000000000000// Copyright 2020 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fn type statusCodeError struct { err error statusCode int } type StatusCodeError interface { StatusCode() int } func (s *statusCodeError) StatusCode() int { return s.statusCode } func (s *statusCodeError) Unwrap() error { return s.err } func (s *statusCodeError) Error() string { return s.err.Error() } func UnwrapErrorStatusCode(err error) (int, bool) { for err != nil { if v, ok := err.(StatusCodeError); ok { return v.StatusCode(), true } err = Unwrap(err) } return 0, false } func ErrorWithStatusCode(err error, statusCode int) error { return &statusCodeError{err, statusCode} } fn-1.0.0/error_test.go000066400000000000000000000025461424136020700146400ustar00rootroot00000000000000// Copyright 2020 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fn import ( "errors" "net/http" "testing" "github.com/stretchr/testify/require" ) var errTest = errors.New("test") type withError struct { err error } func (w *withError) Error() string { return w.err.Error() } func (w *withError) Unwrap() error { return w.err } // TestWithError test UnwrapErrorStatusCode method func TestWithError(t *testing.T) { var err error = &withError{ err: ErrorWithStatusCode(errTest, http.StatusInternalServerError), } code, ok := UnwrapErrorStatusCode(err) require.True(t, ok) require.Equal(t, http.StatusInternalServerError, code) } // TestOriginError test ErrorWithStatusCode Unwrap func TestOriginError(t *testing.T) { err := ErrorWithStatusCode(errTest, http.StatusInternalServerError) require.Equal(t, errTest, Unwrap(err)) } fn-1.0.0/form_helper.go000066400000000000000000000050531424136020700147460ustar00rootroot00000000000000// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fn import ( "strconv" ) func (f *uniform) Int(key string) int { value := f.Get(key) if value == "" { return 0 } v, err := strconv.Atoi(value) if err != nil { return 0 } return v } func (f *uniform) IntOrDefault(key string, def int) int { value := f.Get(key) if value == "" { return def } v, err := strconv.Atoi(value) if err != nil { return def } return v } func (f *uniform) Int64(key string) int64 { value := f.Get(key) if value == "" { return 0 } v, err := strconv.ParseInt(value, 10, 64) if err != nil { return 0 } return v } func (f *uniform) Int64OrDefault(key string, def int64) int64 { value := f.Get(key) if value == "" { return def } v, err := strconv.ParseInt(value, 10, 64) if err != nil { return def } return v } func (f *uniform) Uint64(key string) uint64 { value := f.Get(key) if value == "" { return 0 } v, err := strconv.ParseUint(value, 10, 64) if err != nil { return 0 } return v } func (f *uniform) Uint64OrDefault(key string, def uint64) uint64 { value := f.Get(key) if value == "" { return def } v, err := strconv.ParseUint(value, 10, 64) if err != nil { return def } return v } // Get gets the first value associated with the given key. // If there are no values associated with the key, Get returns // the empty string. To access multiple values, use the map // directly. func (f *uniform) Get(key string) string { return f.Values.Get(key) } // Set sets the key to value. It replaces any existing // values. func (f *uniform) Set(key, value string) { f.Values.Set(key, value) } // Add adds the value to key. It appends to any existing // values associated with key. func (f *uniform) Add(key, value string) { f.Values.Add(key, value) } // Del deletes the values associated with key. func (f *uniform) Del(key string) { f.Values.Del(key) } // Encode encodes the values into ``URL encoded'' form // ("bar=baz&foo=quux") sorted by key. func (f *uniform) Encode() string { return f.Values.Encode() } fn-1.0.0/go.mod000066400000000000000000000003071424136020700132200ustar00rootroot00000000000000module github.com/pingcap/fn go 1.11 require ( github.com/davecgh/go-spew v1.1.1 // indirect github.com/stretchr/testify v1.7.1 gopkg.in/yaml.v3 v3.0.0-20220512140231-539c8e751b99 // indirect ) fn-1.0.0/go.sum000066400000000000000000000023041424136020700132440ustar00rootroot00000000000000github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.1 h1:5TQK59W5E3v0r2duFAb7P95B6hEeOyEnHRa8MjYSMTY= github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= gopkg.in/yaml.v3 v3.0.0-20220512140231-539c8e751b99 h1:dbuHpmKjkDzSOMKAWl10QNlgaZUd3V1q99xc81tt2Kc= gopkg.in/yaml.v3 v3.0.0-20220512140231-539c8e751b99/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= fn-1.0.0/go113.go000066400000000000000000000013141424136020700132720ustar00rootroot00000000000000//go:build go1.13 // +build go1.13 // Copyright 2020 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fn import "errors" func Unwrap(err error) error { return errors.Unwrap(err) } fn-1.0.0/group.go000066400000000000000000000021061424136020700135740ustar00rootroot00000000000000// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fn // Group represents a handler group that contains same hooks type Group struct { plugins []PluginFunc } func NewGroup() *Group { return &Group{} } func (g *Group) Plugin(plugins ...PluginFunc) *Group { for _, b := range plugins { if b != nil { g.plugins = append(g.plugins, b) } } return g } func (g *Group) Wrap(f interface{}) *fn { n := Wrap(f) if length := len(g.plugins); length > 0 { n.plugins = make([]PluginFunc, length) copy(n.plugins, g.plugins) } return n } fn-1.0.0/interface.go000066400000000000000000000057241424136020700144110ustar00rootroot00000000000000// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fn import ( "reflect" ) func Wrap(f interface{}) *fn { t := reflect.TypeOf(f) if t.Kind() != reflect.Func { panic("fn only support wrap a function to http.Handler") } numOut := t.NumOut() // Supported signatures // func(...) (Response, error) if numOut != 2 { panic("unsupported function type, function return values should contain response data & error") } var ( adapter adapter numIn = t.NumIn() inContext = false ) if numIn > 0 { for i := 0; i < numIn; i++ { // Legal: func(ctx context.Context, ...) ... if t.In(i) == contextType { // Illegal: func(..., ctx context.Context, ...) ... if i != 0 { panic("the `context.Context` must be the first parameter if the signature contains `context.Context`") } // Illegal: func(..., ctx context.Context, ..., ctx2 context.Context) ... if inContext { panic("the function can receive two `context.Context`") } inContext = true } } } if numIn == 0 { // func() (Response, error) adapter = &simplePlainAdapter{ inContext: false, method: reflect.ValueOf(f), cacheArgs: []reflect.Value{}, } } else if numIn == 1 && inContext { // func(ctx context.Context) (Response, error) adapter = &simplePlainAdapter{ inContext: true, method: reflect.ValueOf(f), cacheArgs: make([]reflect.Value, 1), } } else if numIn == 1 && !isBuiltinType(t.In(0)) && t.In(0).Kind() == reflect.Ptr { // func(request *Customized) (Response, error) adapter = &simpleUnaryAdapter{ argType: t.In(0), method: reflect.ValueOf(f), cacheArgs: make([]reflect.Value, 1), } } else { // Complicated signatures // // e.g: // type LoginResponse {...} // type LoginRequest {...} // // func (header http.Header) (*LoginResponse, error) {} // func (form fn.Form) (*LoginResponse, error) {} // func (header http.Header, form fn.Form, body io.ReadCloser) (*LoginResponse, error) {} // func (header http.Header, r *LoginRequest, url *url.URL) (*LoginResponse, error) { } adapter = makeGenericAdapter(reflect.ValueOf(f), inContext) } return &fn{adapter: adapter} } func SetErrorEncoder(c ErrorEncoder) { if c == nil { panic("nil pointer to error encoder") } errorEncoder = c } func SetResponseEncoder(c ResponseEncoder) { if c == nil { panic("nil pointer to error encoder") } responseEncoder = c } func SetMultipartFormMaxMemory(m int64) { maxMemory = m } fn-1.0.0/plugin.go000066400000000000000000000016371424136020700137460ustar00rootroot00000000000000// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fn import ( "context" "net/http" ) // Global plugins, such as IP filter, logs var globalPlugins []PluginFunc type PluginFunc func(context.Context, *http.Request) (context.Context, error) func Plugin(plugins ...PluginFunc) { for _, a := range plugins { if a != nil { globalPlugins = append(globalPlugins, a) } } } fn-1.0.0/pre_go113.go000066400000000000000000000014271424136020700141450ustar00rootroot00000000000000//go:build !go1.13 // +build !go1.13 // Copyright 2020 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fn type wrapError interface { Unwrap() error } func Unwrap(err error) error { u, ok := err.(wrapError) if !ok { return nil } return u.Unwrap() } fn-1.0.0/types.go000066400000000000000000000063351424136020700136140ustar00rootroot00000000000000// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fn import ( "context" "io" "mime/multipart" "net/http" "net/url" "reflect" ) type valuer func(r *http.Request) (reflect.Value, error) var contextType = reflect.TypeOf((*context.Context)(nil)).Elem() // BenchmarkIsBuiltinType-8 100000000 23.1 ns/op 0 B/op 0 allocs/op var supportTypes = map[reflect.Type]valuer{ reflect.TypeOf((*io.ReadCloser)(nil)).Elem(): bodyValuer, // request.Body reflect.TypeOf((http.Header)(nil)): headerValuer, // request.Header reflect.TypeOf(Form{}): formValuer, // request.Form reflect.TypeOf(PostForm{}): postFromValuer, // request.PostFrom reflect.TypeOf((*Form)(nil)): formPtrValuer, // request.Form reflect.TypeOf((*PostForm)(nil)): postFromPtrValuer, // request.PostFrom reflect.TypeOf((*url.URL)(nil)): urlValuer, // request.URL reflect.TypeOf((*multipart.Form)(nil)): multipartValuer, // request.MultipartForm reflect.TypeOf((*http.Request)(nil)): requestValuer, // raw request } var maxMemory = int64(2 * 1024 * 1024) type uniform struct { url.Values } type Form struct { uniform } type PostForm struct { uniform } func bodyValuer(r *http.Request) (reflect.Value, error) { return reflect.ValueOf(r.Body), nil } func urlValuer(r *http.Request) (reflect.Value, error) { return reflect.ValueOf(r.URL), nil } func headerValuer(r *http.Request) (reflect.Value, error) { return reflect.ValueOf(r.Header), nil } func multipartValuer(r *http.Request) (reflect.Value, error) { err := r.ParseMultipartForm(maxMemory) if err != nil { return reflect.Value{}, err } return reflect.ValueOf(r.MultipartForm), nil } func formValuer(r *http.Request) (reflect.Value, error) { err := r.ParseForm() if err != nil { return reflect.Value{}, nil } return reflect.ValueOf(Form{uniform{r.Form}}), nil } func postFromValuer(r *http.Request) (reflect.Value, error) { err := r.ParseForm() if err != nil { return reflect.Value{}, nil } return reflect.ValueOf(PostForm{uniform{r.PostForm}}), nil } func formPtrValuer(r *http.Request) (reflect.Value, error) { err := r.ParseForm() if err != nil { return reflect.Value{}, nil } return reflect.ValueOf(&Form{uniform{r.Form}}), nil } func postFromPtrValuer(r *http.Request) (reflect.Value, error) { err := r.ParseForm() if err != nil { return reflect.Value{}, nil } return reflect.ValueOf(&PostForm{uniform{r.PostForm}}), nil } func requestValuer(r *http.Request) (reflect.Value, error) { return reflect.ValueOf(r), nil } func isBuiltinType(t reflect.Type) bool { _, ok := supportTypes[t] return ok } fn-1.0.0/types_test.go000066400000000000000000000014461424136020700146510ustar00rootroot00000000000000// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fn import ( "reflect" "testing" ) func BenchmarkIsBuiltinType(b *testing.B) { b.ReportAllocs() b.ResetTimer() typ := reflect.TypeOf((*Form)(nil)) for i := 0; i < b.N; i++ { isBuiltinType(typ) } } fn-1.0.0/wrapper.go000066400000000000000000000050041424136020700141200ustar00rootroot00000000000000// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fn import ( "context" "encoding/json" "net/http" "reflect" ) type ( // ErrorEncoder encode error to response body ErrorEncoder func(ctx context.Context, err error) interface{} // ResponseEncoder encode payload to response body ResponseEncoder func(ctx context.Context, payload interface{}) interface{} // fn represents a handler that contains a bundle of hooks fn struct { plugins []PluginFunc adapter adapter } ) var ( errorEncoder ErrorEncoder responseEncoder ResponseEncoder ) func failure(ctx context.Context, w http.ResponseWriter, err error) { statusCode := http.StatusBadRequest if v, ok := UnwrapErrorStatusCode(err); ok { statusCode = v } w.WriteHeader(statusCode) _ = json.NewEncoder(w).Encode(errorEncoder(ctx, err)) } func success(ctx context.Context, w http.ResponseWriter, data interface{}) { if data == nil || (reflect.ValueOf(data).Kind() == reflect.Ptr && reflect.ValueOf(data).IsNil()) { w.WriteHeader(http.StatusNoContent) } else { _ = json.NewEncoder(w).Encode(responseEncoder(ctx, data)) } } func (fn *fn) ServeHTTP(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json; charset=utf-8") var ( ctx = r.Context() err error resp interface{} ) for _, b := range globalPlugins { ctx, err = b(ctx, r) if err != nil { failure(ctx, w, err) return } } for _, b := range fn.plugins { ctx, err = b(ctx, r) if err != nil { failure(ctx, w, err) return } } resp, err = fn.adapter.invoke(ctx, w, r) if err != nil { failure(ctx, w, err) return } success(ctx, w, resp) } func (fn *fn) Plugin(before ...PluginFunc) *fn { for _, b := range before { if b != nil { fn.plugins = append(fn.plugins, b) } } return fn } func init() { errorEncoder = func(ctx context.Context, err error) interface{} { return err.Error() } responseEncoder = func(ctx context.Context, payload interface{}) interface{} { return payload } } fn-1.0.0/wrapper_test.go000066400000000000000000000206751424136020700151720ustar00rootroot00000000000000// Copyright 2017 PingCAP, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package fn import ( "bytes" "context" "encoding/json" "errors" "io" "io/ioutil" "mime/multipart" "net/http" "net/http/httptest" "net/url" "testing" "github.com/stretchr/testify/require" ) type testRequest struct { Foo string `json:"foo"` Bar int `json:"bar"` } type testResponse struct { Code int `json:"code"` Message string `json:"message"` } type testErrorResponse struct { Code int `json:"code"` Error string `json:"message"` } var successResponse = &testResponse{Message: "success"} func init() { Plugin( func(ctx context.Context, request *http.Request) (context.Context, error) { return context.WithValue(ctx, "global1", "globalvalue1"), nil }, nil, func(ctx context.Context, request *http.Request) (context.Context, error) { return context.WithValue(ctx, "global2", "globalvalue2"), nil }) } // acceptable function signature func withNone() (*testResponse, error) { return successResponse, nil } func withBody(io.ReadCloser) (*testResponse, error) { return successResponse, nil } func withReq(*testRequest) (*testResponse, error) { return successResponse, nil } func withHeader(http.Header) (*testResponse, error) { return successResponse, nil } func withForm(Form) (*testResponse, error) { return successResponse, nil } func withPostForm(PostForm) (*testResponse, error) { return successResponse, nil } func withFormPtr(*Form) (*testResponse, error) { return successResponse, nil } func withPostFormPtr(*PostForm) (*testResponse, error) { return successResponse, nil } func withMultipartForm(*multipart.Form) (*testResponse, error) { return successResponse, nil } func withUrl(*url.URL) (*testResponse, error) { return successResponse, nil } func withRawRequest(*http.Request) (*testResponse, error) { return successResponse, nil } func withInContext(context.Context) (*testResponse, error) { return successResponse, nil } func withInContextAndPayload(context.Context, *testRequest) (*testResponse, error) { return successResponse, nil } func withMulti(*testRequest, Form, PostForm, http.Header, *url.URL) (*testResponse, error) { return nil, nil } func withAll(io.ReadCloser, *testRequest, Form, PostForm, http.Header, *multipart.Form, *url.URL) (*testResponse, error) { return nil, nil } func TestHandler(t *testing.T) { Wrap(withNone) Wrap(withBody) Wrap(withReq) Wrap(withHeader) Wrap(withForm) Wrap(withPostForm) Wrap(withFormPtr) Wrap(withPostFormPtr) Wrap(withMultipartForm) Wrap(withUrl) Wrap(withRawRequest) Wrap(withMulti) Wrap(withAll) Wrap(withInContext) Wrap(withInContextAndPayload) } func TestPlugin(t *testing.T) { logic := func(ctx context.Context) (*testResponse, error) { require.Equal(t, "value", ctx.Value("key").(string)) require.Equal(t, "value2", ctx.Value("key2").(string)) return &testResponse{}, nil } plugin1 := func(ctx context.Context, request *http.Request) (context.Context, error) { require.Equal(t, "globalvalue1", ctx.Value("global1").(string)) require.Equal(t, "globalvalue2", ctx.Value("global2").(string)) return context.WithValue(ctx, "key", "value"), nil } plugin2 := func(ctx context.Context, request *http.Request) (context.Context, error) { require.Equal(t, "globalvalue1", ctx.Value("global1").(string)) require.Equal(t, "globalvalue2", ctx.Value("global2").(string)) require.Equal(t, "value", ctx.Value("key").(string)) return context.WithValue(ctx, "key2", "value2"), nil } handler := Wrap(logic).Plugin(plugin1, plugin2) recorder := httptest.NewRecorder() request, err := http.NewRequest(http.MethodGet, "", nil) require.NoError(t, err) handler.ServeHTTP(recorder, request) } func TestGroupPlugin(t *testing.T) { group := NewGroup() group.Plugin(func(ctx context.Context, request *http.Request) (context.Context, error) { return context.WithValue(ctx, "key", "value"), nil }) logic := func(ctx context.Context) (*testResponse, error) { require.Equal(t, "value", ctx.Value("key").(string)) return &testResponse{}, nil } handler := group.Wrap(logic) recorder := httptest.NewRecorder() request, err := http.NewRequest(http.MethodGet, "", nil) require.NoError(t, err) handler.ServeHTTP(recorder, request) } func TestSetResponseEncoder(t *testing.T) { handler := Wrap(func(ctx context.Context, request *http.Request) (context.Context, error) { return context.TODO(), nil }) testResp := &testResponse{ Code: 1, Message: "msg", } SetResponseEncoder(func(ctx context.Context, payload interface{}) interface{} { return testResp }) recorder := httptest.NewRecorder() request, err := http.NewRequest(http.MethodGet, "", nil) require.NoError(t, err) handler.ServeHTTP(recorder, request) respMsg := &testResponse{} _ = json.Unmarshal(recorder.Body.Bytes(), &respMsg) require.Equal(t, testResp, respMsg) } func TestSetErrorEncoder(t *testing.T) { handler := Wrap(func(ctx context.Context, request *http.Request) (context.Context, error) { return nil, errors.New("") }) testErrorResp := &testErrorResponse{ Code: -1, Error: "something went wrong", } SetErrorEncoder(func(ctx context.Context, err error) interface{} { return testErrorResp }) recorder := httptest.NewRecorder() request, err := http.NewRequest(http.MethodGet, "", nil) require.NoError(t, err) handler.ServeHTTP(recorder, request) respMsg := &testErrorResponse{} _ = json.Unmarshal(recorder.Body.Bytes(), &respMsg) require.Equal(t, testErrorResp, respMsg) } func TestGenericAdapter_Invoke(t *testing.T) { type CustomForm testRequest handler := Wrap(func(ctx context.Context, form *CustomForm) (context.Context, error) { return nil, nil }) recorder := httptest.NewRecorder() request, err := http.NewRequest(http.MethodGet, "", nil) require.NoError(t, err) payload := []byte(`{"for":"hello", "bar":10000}`) request.Body = ioutil.NopCloser(bytes.NewBuffer(payload)) require.NoError(t, err) handler.ServeHTTP(recorder, request) } func TestSimpleUnaryAdapter_Invoke(t *testing.T) { handler := Wrap(withReq) recorder := httptest.NewRecorder() request, err := http.NewRequest(http.MethodGet, "", nil) require.NoError(t, err) payload := []byte(`{"for":"hello", "bar":10000}`) request.Body = ioutil.NopCloser(bytes.NewBuffer(payload)) require.NoError(t, err) handler.ServeHTTP(recorder, request) } func TestErrorWithStatusCode(t *testing.T) { handler := Wrap(func(ctx context.Context, request *http.Request) (context.Context, error) { return nil, ErrorWithStatusCode(errors.New("not found"), http.StatusNotFound) }) recorder := httptest.NewRecorder() request, err := http.NewRequest(http.MethodGet, "", nil) require.NoError(t, err) handler.ServeHTTP(recorder, request) require.Equal(t, http.StatusNotFound, recorder.Code) } func BenchmarkSimplePlainAdapter_Invoke(b *testing.B) { handler := Wrap(withNone) request, err := http.NewRequest(http.MethodGet, "", nil) if err != nil { b.Fatal(err) } recorder := httptest.NewRecorder() b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { handler.ServeHTTP(recorder, request) } } func BenchmarkSimpleUnaryAdapter_Invoke(b *testing.B) { handler := Wrap(withReq) request, err := http.NewRequest(http.MethodGet, "", nil) if err != nil { b.Fatal(err) } payload := []byte(`{"for":"hello", "bar":10000}`) request.Body = ioutil.NopCloser(bytes.NewBuffer(payload)) recorder := httptest.NewRecorder() b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { handler.ServeHTTP(recorder, request) } } func BenchmarkGenericAdapter_Invoke(b *testing.B) { handler := Wrap(withMulti) request, err := http.NewRequest(http.MethodGet, "", nil) if err != nil { b.Fatal(err) } payload := []byte(`{"for":"hello", "bar":10000}`) request.Body = ioutil.NopCloser(bytes.NewBuffer(payload)) recorder := httptest.NewRecorder() b.ReportAllocs() b.ResetTimer() for i := 0; i < b.N; i++ { handler.ServeHTTP(recorder, request) } }