diff --git a/Makefile b/Makefile index 783110c..e113d63 100644 --- a/Makefile +++ b/Makefile @@ -3,6 +3,10 @@ VERSION = v$(shell cat .version) COMMIT_SHA ?= $(shell git describe --always)-devel GOTEST = go test -v -race +fmt: + goimports -l -w . + gofmt -l -w . + test: GODEBUG=x509ignoreCN=0 $(GOTEST) ./... diff --git a/__examples__/downstream/client_demo/client.go b/__examples__/downstream/client_demo/client.go index a3988e0..f89f4ac 100644 --- a/__examples__/downstream/client_demo/client.go +++ b/__examples__/downstream/client_demo/client.go @@ -16,7 +16,7 @@ type ClientDemo interface { FormMultipartWithFiles(req *FormMultipartWithFiles, metas ...github_com_go_courier_courier.Metadata) (github_com_go_courier_courier.Metadata, error) FormURLEncoded(req *FormURLEncoded, metas ...github_com_go_courier_courier.Metadata) (github_com_go_courier_courier.Metadata, error) GetByID(req *GetByID, metas ...github_com_go_courier_courier.Metadata) (*Data, github_com_go_courier_courier.Metadata, error) - HealthCheck(metas ...github_com_go_courier_courier.Metadata) (github_com_go_courier_courier.Metadata, error) + HealthCheck(req *HealthCheck, metas ...github_com_go_courier_courier.Metadata) (github_com_go_courier_courier.Metadata, error) Proxy(metas ...github_com_go_courier_courier.Metadata) (*IpInfo, github_com_go_courier_courier.Metadata, error) ProxyV2(metas ...github_com_go_courier_courier.Metadata) (*IpInfo, github_com_go_courier_courier.Metadata, error) Redirect(metas ...github_com_go_courier_courier.Metadata) (github_com_go_courier_courier.Metadata, error) @@ -79,8 +79,8 @@ func (c *ClientDemoStruct) GetByID(req *GetByID, metas ...github_com_go_courier_ return req.InvokeContext(c.Context(), c.Client, metas...) } -func (c *ClientDemoStruct) HealthCheck(metas ...github_com_go_courier_courier.Metadata) (github_com_go_courier_courier.Metadata, error) { - return (&HealthCheck{}).InvokeContext(c.Context(), c.Client, metas...) +func (c *ClientDemoStruct) HealthCheck(req *HealthCheck, metas ...github_com_go_courier_courier.Metadata) (github_com_go_courier_courier.Metadata, error) { + return req.InvokeContext(c.Context(), c.Client, metas...) } func (c *ClientDemoStruct) Proxy(metas ...github_com_go_courier_courier.Metadata) (*IpInfo, github_com_go_courier_courier.Metadata, error) { diff --git a/__examples__/downstream/client_demo/operations.go b/__examples__/downstream/client_demo/operations.go index 869e08f..96db78e 100644 --- a/__examples__/downstream/client_demo/operations.go +++ b/__examples__/downstream/client_demo/operations.go @@ -225,6 +225,7 @@ func (req *GetByID) Invoke(c github_com_go_courier_courier.Client, metas ...gith } type HealthCheck struct { + PullPolicy GithubComGoCourierHttptransportExamplesServerPkgTypesPullPolicy `in:"query" name:"pullPolicy,omitempty"` } func (HealthCheck) Path() string { diff --git a/__examples__/downstream/client_demo/types.go b/__examples__/downstream/client_demo/types.go index c20341d..c067e48 100644 --- a/__examples__/downstream/client_demo/types.go +++ b/__examples__/downstream/client_demo/types.go @@ -20,6 +20,8 @@ type Data struct { type GithubComGoCourierHttptransportExamplesServerPkgTypesProtocol = github_com_go_courier_httptransport_examples_server_pkg_types.Protocol +type GithubComGoCourierHttptransportExamplesServerPkgTypesPullPolicy = github_com_go_courier_httptransport_examples_server_pkg_types.PullPolicy + type GithubComGoCourierHttptransportHttpxAttachment = github_com_go_courier_httptransport_httpx.Attachment type GithubComGoCourierHttptransportHttpxImagePNG = github_com_go_courier_httptransport_httpx.ImagePNG diff --git a/__examples__/server/cmd/app/routes/restful.go b/__examples__/server/cmd/app/routes/restful.go index 181916d..68f2f0d 100644 --- a/__examples__/server/cmd/app/routes/restful.go +++ b/__examples__/server/cmd/app/routes/restful.go @@ -2,12 +2,12 @@ package routes import ( "context" - "fmt" "github.com/go-courier/courier" "github.com/go-courier/httptransport/__examples__/server/pkg/errors" "github.com/go-courier/httptransport/__examples__/server/pkg/types" "github.com/go-courier/httptransport/httpx" + perrors "github.com/pkg/errors" "github.com/go-courier/httptransport" ) @@ -95,7 +95,7 @@ type UpdateByID struct { } func (req UpdateByID) Output(ctx context.Context) (interface{}, error) { - return nil, fmt.Errorf("something wrong") + return nil, perrors.Errorf("something wrong") } type DataProvider struct { diff --git a/__examples__/server/pkg/types/protocol__generated.go b/__examples__/server/pkg/types/protocol__generated.go index aa2c4e6..1fc070a 100644 --- a/__examples__/server/pkg/types/protocol__generated.go +++ b/__examples__/server/pkg/types/protocol__generated.go @@ -3,7 +3,8 @@ package types import ( "bytes" database_sql_driver "database/sql/driver" - "errors" + + "github.com/pkg/errors" github_com_go_courier_enumeration "github.com/go-courier/enumeration" ) diff --git a/client/client.go b/client/client.go index df6db12..c88a4d2 100644 --- a/client/client.go +++ b/client/client.go @@ -2,7 +2,6 @@ package client import ( "context" - "errors" "fmt" "io" "mime" @@ -12,16 +11,16 @@ import ( "reflect" "time" + "github.com/pkg/errors" + "github.com/go-courier/courier" + "github.com/go-courier/httptransport" "github.com/go-courier/httptransport/client/roundtrippers" "github.com/go-courier/httptransport/httpx" "github.com/go-courier/httptransport/transformers" "github.com/go-courier/reflectx/typesutil" "github.com/go-courier/statuserror" - "github.com/sirupsen/logrus" "golang.org/x/net/http2" - - "github.com/go-courier/httptransport" ) type HttpTransport func(rt http.RoundTripper) http.RoundTripper @@ -42,7 +41,7 @@ func (c *Client) SetDefaults() { c.RequestTransformerMgr.SetDefaults() } if c.HttpTransports == nil { - c.HttpTransports = []HttpTransport{roundtrippers.NewLogRoundTripper(logrus.WithField("client", ""))} + c.HttpTransports = []HttpTransport{roundtrippers.NewLogRoundTripper()} } if c.NewError == nil { c.NewError = func(resp *http.Response) error { diff --git a/client/generator/client_generator.go b/client/generator/client_generator.go index bd9d908..f43f3a4 100644 --- a/client/generator/client_generator.go +++ b/client/generator/client_generator.go @@ -3,7 +3,6 @@ package generator import ( "context" "encoding/json" - "fmt" "io/ioutil" "log" "net/http" @@ -15,6 +14,7 @@ import ( "github.com/fatih/color" "github.com/go-courier/codegen" "github.com/go-courier/oas" + "github.com/pkg/errors" "golang.org/x/mod/modfile" "golang.org/x/tools/go/packages" ) @@ -55,7 +55,7 @@ type ClientGenerator struct { func (g *ClientGenerator) Load() { if g.URL == nil { - panic(fmt.Errorf("missing spec-url or file")) + panic(errors.Errorf("missing spec-url or file")) } if g.URL.Scheme == "file" { diff --git a/client/roundtrippers/log_round_tripper.go b/client/roundtrippers/log_round_tripper.go index 4407089..b7eecaa 100644 --- a/client/roundtrippers/log_round_tripper.go +++ b/client/roundtrippers/log_round_tripper.go @@ -5,42 +5,44 @@ import ( "net/http" "time" - "github.com/sirupsen/logrus" + "github.com/go-courier/logr" + "github.com/pkg/errors" ) -func NewLogRoundTripper(logger *logrus.Entry) func(roundTripper http.RoundTripper) http.RoundTripper { +func NewLogRoundTripper() func(roundTripper http.RoundTripper) http.RoundTripper { return func(roundTripper http.RoundTripper) http.RoundTripper { return &LogRoundTripper{ - logger: logger, nextRoundTripper: roundTripper, } } } type LogRoundTripper struct { - logger *logrus.Entry nextRoundTripper http.RoundTripper } func (rt *LogRoundTripper) RoundTrip(req *http.Request) (*http.Response, error) { startedAt := time.Now() - resp, err := rt.nextRoundTripper.RoundTrip(req) + ctx, logger := logr.Start(req.Context(), "Request") + defer logger.End() + + resp, err := rt.nextRoundTripper.RoundTrip(req.WithContext(ctx)) defer func() { cost := time.Since(startedAt) - logger := rt.logger.WithContext(req.Context()).WithFields(logrus.Fields{ - "cost": fmt.Sprintf("%0.3fms", float64(cost/time.Millisecond)), - "method": req.Method, - "url": req.URL.String(), - "metadata": req.Header, - }) + logger := logger.WithValues( + "cost", fmt.Sprintf("%0.3fms", float64(cost/time.Millisecond)), + "method", req.Method, + "url", req.URL.String(), + "metadata", req.Header, + ) if err == nil { - logger.Infof("success") + logger.Info("success") } else { - logger.Warnf("do http request failed %s", err) + logger.Warn(errors.Wrap(err, "http request failed")) } }() diff --git a/client/roundtrippers/log_round_tripper_test.go b/client/roundtrippers/log_round_tripper_test.go index 5315b1b..969d711 100644 --- a/client/roundtrippers/log_round_tripper_test.go +++ b/client/roundtrippers/log_round_tripper_test.go @@ -1,12 +1,9 @@ package roundtrippers import ( - "context" "net/http" "testing" - "github.com/sirupsen/logrus" - "github.com/go-courier/httptransport" ) @@ -16,5 +13,5 @@ func TestLogRoundTripper(t *testing.T) { req, _ := mgr.NewRequest(http.MethodGet, "https://github.com", nil) - _, _ = NewLogRoundTripper(logrus.WithContext(context.Background()))(http.DefaultTransport).RoundTrip(req) + _, _ = NewLogRoundTripper()(http.DefaultTransport).RoundTrip(req) } diff --git a/go.mod b/go.mod index 9df9019..bce2d88 100644 --- a/go.mod +++ b/go.mod @@ -7,6 +7,7 @@ require ( github.com/go-courier/codegen v1.1.2 github.com/go-courier/courier v1.4.1 github.com/go-courier/enumeration v1.3.0 + github.com/go-courier/logr v0.0.0 github.com/go-courier/metax v1.2.1 github.com/go-courier/oas v1.2.1 github.com/go-courier/packagesx v1.0.2 @@ -18,11 +19,11 @@ require ( github.com/julienschmidt/httprouter v1.3.0 github.com/konsorten/go-windows-terminal-sequences v1.0.3 // indirect github.com/magefile/mage v1.11.0 // indirect - github.com/sirupsen/logrus v1.8.0 + github.com/pkg/errors v0.9.1 github.com/stretchr/testify v1.7.0 - golang.org/x/mod v0.4.1 // indirect - golang.org/x/net v0.0.0-20210222171744-9060382bd457 - golang.org/x/sys v0.0.0-20210220050731-9a76102bfb43 // indirect + golang.org/x/mod v0.4.1 + golang.org/x/net v0.0.0-20210226172049-e18ecbb05110 + golang.org/x/sys v0.0.0-20210309074719-68d13333faf2 // indirect golang.org/x/text v0.3.5 // indirect - golang.org/x/tools v0.1.0 // indirect -) \ No newline at end of file + golang.org/x/tools v0.1.0 +) diff --git a/handlers/log_handler.go b/handlers/log_handler.go index 9a25d34..ebf933b 100644 --- a/handlers/log_handler.go +++ b/handlers/log_handler.go @@ -7,23 +7,23 @@ import ( "strings" "time" + "github.com/go-courier/logr" + "github.com/pkg/errors" + "github.com/go-courier/httptransport/httpx" "github.com/go-courier/metax" "github.com/google/uuid" - "github.com/sirupsen/logrus" ) -func LogHandler(logger *logrus.Entry) func(handler http.Handler) http.Handler { +func LogHandler() func(handler http.Handler) http.Handler { return func(handler http.Handler) http.Handler { return &loggerHandler{ - logger: logger, nextHandler: handler, } } } type loggerHandler struct { - logger *logrus.Entry nextHandler http.Handler } @@ -69,42 +69,38 @@ func (h *loggerHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request) { startAt := time.Now() - level, _ := logrus.ParseLevel(strings.ToLower(req.Header.Get("x-log-level"))) - if level == logrus.PanicLevel { - level = h.logger.Logger.Level - } + logger := logr.FromContext(req.Context()) + + level, _ := logr.ParseLevel(strings.ToLower(req.Header.Get("x-log-level"))) defer func() { duration := time.Since(startAt) - logger := h.logger.WithContext(metax.ContextWithMeta(req.Context(), metax.ParseMeta(loggerRw.Header().Get("X-Meta")))) - header := req.Header - fields := logrus.Fields{ - "tag": "access", - "cost": fmt.Sprintf("%0.3fms", float64(duration/time.Millisecond)), - "remote_ip": httpx.ClientIP(req), - "method": req.Method, - "request_url": req.URL.String(), - "user_agent": header.Get(httpx.HeaderUserAgent), + fields := []interface{}{ + "tag", "access", + "cost", fmt.Sprintf("%0.3fms", float64(duration/time.Millisecond)), + "remote_ip", httpx.ClientIP(req), + "method", req.Method, + "request_url", req.URL.String(), + "user_agent", header.Get(httpx.HeaderUserAgent), + "status", loggerRw.StatusCode, } - fields["status"] = loggerRw.StatusCode - if loggerRw.ErrMsg.Len() > 0 { if loggerRw.StatusCode >= http.StatusInternalServerError { - if level >= logrus.ErrorLevel { - logger.WithFields(fields).Error(loggerRw.ErrMsg.String()) + if level >= logr.ErrorLevel { + logger.WithValues(fields).Error(errors.New(loggerRw.ErrMsg.String())) } } else { - if level >= logrus.WarnLevel { - logger.WithFields(fields).Warn(loggerRw.ErrMsg.String()) + if level >= logr.WarnLevel { + logger.WithValues(fields).Warn(errors.New(loggerRw.ErrMsg.String())) } } } else { - if level >= logrus.InfoLevel { - logger.WithFields(fields).Info() + if level >= logr.InfoLevel { + logger.WithValues(fields).Info("") } } }() diff --git a/handlers/log_handler_test.go b/handlers/log_handler_test.go index 5dcade3..eaadc05 100644 --- a/handlers/log_handler_test.go +++ b/handlers/log_handler_test.go @@ -1,15 +1,16 @@ package handlers import ( + "context" "net/http" "time" "github.com/go-courier/httptransport/testify" - "github.com/sirupsen/logrus" + "github.com/go-courier/logr" ) func ExampleLogHandler() { - logrus.SetLevel(logrus.DebugLevel) + ctx := logr.WithLogger(context.Background(), logr.StdLogger()) var handle http.HandlerFunc = func(rw http.ResponseWriter, req *http.Request) { time.Sleep(20 * time.Millisecond) @@ -29,10 +30,10 @@ func ExampleLogHandler() { } } - handler := LogHandler(logrus.WithField("service", ""))(handle).(*loggerHandler) + handler := LogHandler()(handle).(*loggerHandler) for _, method := range []string{http.MethodGet, http.MethodPut, http.MethodDelete, http.MethodPost} { - req, _ := http.NewRequest(method, "/", nil) + req, _ := http.NewRequestWithContext(ctx, method, "/", nil) handler.ServeHTTP(testify.NewMockResponseWriter(), req) } // Output: diff --git a/http_route_handler.go b/http_route_handler.go index a5e6b52..7f317a8 100644 --- a/http_route_handler.go +++ b/http_route_handler.go @@ -2,11 +2,12 @@ package httptransport import ( "context" - "fmt" "io" "net/http" "reflect" + "github.com/pkg/errors" + "github.com/go-courier/courier" "github.com/go-courier/httptransport/httpx" "github.com/go-courier/httptransport/transformers" @@ -19,7 +20,7 @@ func NewHttpRouteHandler(serviceMeta *ServiceMeta, httpRoute *HttpRouteMeta, req operatorFactories := httpRoute.OperatorFactoryWithRouteMetas if len(operatorFactories) == 0 { - panic(fmt.Errorf("missing valid operator")) + panic(errors.Errorf("missing valid operator")) } requestTransformers := make([]*RequestTransformer, len(operatorFactories)) diff --git a/http_transport.go b/http_transport.go index 069e51f..b8faa09 100644 --- a/http_transport.go +++ b/http_transport.go @@ -10,12 +10,15 @@ import ( "syscall" "time" + "github.com/pkg/errors" + + "github.com/go-courier/logr" + "github.com/go-courier/courier" "github.com/go-courier/httptransport/handlers" "github.com/go-courier/httptransport/transformers" "github.com/go-courier/validator" "github.com/julienschmidt/httprouter" - "github.com/sirupsen/logrus" ) func MiddlewareChain(mw ...HttpMiddleware) HttpMiddleware { @@ -53,9 +56,6 @@ type HttpTransport struct { // transformer mgr for parameter transforming TransformerMgr transformers.TransformerMgr - // Logger - Logger *logrus.Entry - CertFile string KeyFile string @@ -75,12 +75,8 @@ func (t *HttpTransport) SetDefaults() { t.TransformerMgr = transformers.TransformerMgrDefault } - if t.Logger == nil { - t.Logger = logrus.WithField("service", t.ServiceMeta.String()) - } - if t.Middlewares == nil { - t.Middlewares = []HttpMiddleware{handlers.LogHandler(t.Logger)} + t.Middlewares = []HttpMiddleware{handlers.LogHandler()} } if t.Port == 0 { @@ -97,8 +93,14 @@ func courierPrintln(format string, args ...interface{}) { } func (t *HttpTransport) Serve(router *courier.Router) error { + return t.ServeContext(context.Background(), router) +} + +func (t *HttpTransport) ServeContext(ctx context.Context, router *courier.Router) error { t.SetDefaults() + logger := logr.FromContext(ctx) + t.httpRouter = t.convertRouterToHttpRouter(router) srv := &http.Server{} @@ -108,7 +110,7 @@ func (t *HttpTransport) Serve(router *courier.Router) error { for i := range t.ServerModifiers { if err := t.ServerModifiers[i](srv); err != nil { - t.Logger.Fatal(err) + logger.Fatal(err) } } @@ -118,9 +120,9 @@ func (t *HttpTransport) Serve(router *courier.Router) error { if t.CertFile != "" && t.KeyFile != "" { if err := srv.ListenAndServeTLS(t.CertFile, t.KeyFile); err != nil { if err == http.ErrServerClosed { - logrus.Error(err) + logger.Error(err) } else { - logrus.Fatal(err) + logger.Fatal(err) } } return @@ -128,9 +130,9 @@ func (t *HttpTransport) Serve(router *courier.Router) error { if err := srv.ListenAndServe(); err != nil { if err == http.ErrServerClosed { - logrus.Error(err) + logger.Error(err) } else { - logrus.Fatal(err) + logger.Fatal(err) } } }() @@ -144,7 +146,7 @@ func (t *HttpTransport) Serve(router *courier.Router) error { ctx, cancel := context.WithTimeout(context.Background(), timeout) defer cancel() - t.Logger.Infof("shutdowning in %s", timeout) + logger.Info("shutdowning in %s", timeout) return srv.Shutdown(ctx) } @@ -153,7 +155,7 @@ func (t *HttpTransport) convertRouterToHttpRouter(router *courier.Router) *httpr routes := router.Routes() if len(routes) == 0 { - panic(fmt.Errorf("need to register Operator to Router %#v before serve", router)) + panic(errors.Errorf("need to register Operator to Router %#v before serve", router)) } routeMetas := make([]*HttpRouteMeta, len(routes)) @@ -178,7 +180,7 @@ func (t *HttpTransport) convertRouterToHttpRouter(router *courier.Router) *httpr NewHttpRouteHandler(&t.ServiceMeta, httpRoute, NewRequestTransformerMgr(t.TransformerMgr, t.ValidatorMgr)).ServeHTTP, ) }); err != nil { - panic(fmt.Errorf("register http route `%s` failed: %s", httpRoute, err)) + panic(errors.Errorf("register http route `%s` failed: %s", httpRoute, err)) } } diff --git a/httpx/__codegen__/method/main.go b/httpx/__codegen__/method/main.go index 1172f5e..3f2010b 100644 --- a/httpx/__codegen__/method/main.go +++ b/httpx/__codegen__/method/main.go @@ -1,7 +1,6 @@ package main import ( - "fmt" "go/ast" "go/parser" "go/token" @@ -10,6 +9,7 @@ import ( "strings" "github.com/go-courier/codegen" + "github.com/pkg/errors" "golang.org/x/tools/go/packages" ) @@ -84,7 +84,7 @@ func getPkgDir(importPath string) string { panic(err) } if len(pkgs) == 0 { - panic(fmt.Errorf("package `%s` not found", importPath)) + panic(errors.Errorf("package `%s` not found", importPath)) } return filepath.Dir(pkgs[0].GoFiles[0]) } diff --git a/httpx/__codegen__/redirect/main.go b/httpx/__codegen__/redirect/main.go index 3257389..9c211c0 100644 --- a/httpx/__codegen__/redirect/main.go +++ b/httpx/__codegen__/redirect/main.go @@ -1,7 +1,6 @@ package main import ( - "fmt" "go/ast" "go/parser" "go/token" @@ -11,6 +10,7 @@ import ( "strconv" "github.com/go-courier/codegen" + "github.com/pkg/errors" "golang.org/x/tools/go/packages" ) @@ -111,7 +111,7 @@ func getPkgDir(importPath string) string { panic(err) } if len(pkgs) == 0 { - panic(fmt.Errorf("package `%s` not found", importPath)) + panic(errors.Errorf("package `%s` not found", importPath)) } return filepath.Dir(pkgs[0].GoFiles[0]) } diff --git a/openapi/generator/__examples__/definition_scanner/enum__generated.go b/openapi/generator/__examples__/definition_scanner/enum__generated.go index 3824f8a..912c769 100644 --- a/openapi/generator/__examples__/definition_scanner/enum__generated.go +++ b/openapi/generator/__examples__/definition_scanner/enum__generated.go @@ -3,7 +3,8 @@ package definition_scanner import ( "bytes" database_sql_driver "database/sql/driver" - "errors" + + "github.com/pkg/errors" github_com_go_courier_enumeration "github.com/go-courier/enumeration" ) diff --git a/openapi/generator/definition_scanner.go b/openapi/generator/definition_scanner.go index 759c17a..9266b8e 100644 --- a/openapi/generator/definition_scanner.go +++ b/openapi/generator/definition_scanner.go @@ -1,7 +1,7 @@ package generator import ( - "fmt" + "context" "go/ast" "go/types" "reflect" @@ -9,13 +9,15 @@ import ( "sort" "strings" + "github.com/go-courier/logr" + "github.com/pkg/errors" + "github.com/go-courier/enumeration/scanner" "github.com/go-courier/codegen" "github.com/go-courier/oas" "github.com/go-courier/packagesx" "github.com/go-courier/reflectx/typesutil" - "github.com/sirupsen/logrus" ) func NewDefinitionScanner(pkg *packagesx.Package) *DefinitionScanner { @@ -79,12 +81,12 @@ func (scanner *DefinitionScanner) BindSchemas(openapi *oas.OpenAPI) { openapi.Components.Schemas = scanner.schemas } -func (scanner *DefinitionScanner) Def(typeName *types.TypeName) *oas.Schema { +func (scanner *DefinitionScanner) Def(ctx context.Context, typeName *types.TypeName) *oas.Schema { if s, ok := scanner.definitions[typeName]; ok { return s } - logrus.Debugf("scanning Type `%s.%s`", typeName.Pkg().Path(), typeName.Name()) + logr.FromContext(ctx).Debug("scanning Type `%s.%s`", typeName.Pkg().Path(), typeName.Name()) if typeName.IsAlias() { typeName = typeName.Type().(*types.Named).Obj() @@ -184,7 +186,7 @@ func (scanner *DefinitionScanner) Def(typeName *types.TypeName) *oas.Schema { } if !hasDefinedByInterface { - s = scanner.GetSchemaByType(typeName.Type().Underlying()) + s = scanner.GetSchemaByType(ctx, typeName.Type().Underlying()) } setMetaFromDoc(s, doc) @@ -271,13 +273,13 @@ func (r SchemaRefer) RefString() string { return oas.NewComponentRefer("schemas", s.Extensions[XID].(string)).RefString() } -func (scanner *DefinitionScanner) GetSchemaByType(typ types.Type) *oas.Schema { +func (scanner *DefinitionScanner) GetSchemaByType(ctx context.Context, typ types.Type) *oas.Schema { switch t := typ.(type) { case *types.Named: if t.String() == "mime/multipart.FileHeader" { return oas.Binary() } - return oas.RefSchemaByRefer(NewSchemaRefer(scanner.Def(t.Obj()))) + return oas.RefSchemaByRefer(NewSchemaRefer(scanner.Def(ctx, t.Obj()))) case *types.Interface: return &oas.Schema{} case *types.Basic: @@ -298,20 +300,20 @@ func (scanner *DefinitionScanner) GetSchemaByType(typ types.Type) *oas.Schema { } } - s := scanner.GetSchemaByType(elem) + s := scanner.GetSchemaByType(ctx, elem) markPointer(s, count) return s case *types.Map: - keySchema := scanner.GetSchemaByType(t.Key()) + keySchema := scanner.GetSchemaByType(ctx, t.Key()) if keySchema != nil && len(keySchema.Type) > 0 && keySchema.Type != "string" { - panic(fmt.Errorf("only support map[string]interface{}")) + panic(errors.New("only support map[string]interface{}")) } - return oas.KeyValueOf(keySchema, scanner.GetSchemaByType(t.Elem())) + return oas.KeyValueOf(keySchema, scanner.GetSchemaByType(ctx, t.Elem())) case *types.Slice: - return oas.ItemsOf(scanner.GetSchemaByType(t.Elem())) + return oas.ItemsOf(scanner.GetSchemaByType(ctx, t.Elem())) case *types.Array: length := uint64(t.Len()) - s := oas.ItemsOf(scanner.GetSchemaByType(t.Elem())) + s := oas.ItemsOf(scanner.GetSchemaByType(ctx, t.Elem())) s.MaxItems = &length s.MinItems = &length return s @@ -345,7 +347,7 @@ func (scanner *DefinitionScanner) GetSchemaByType(typ types.Type) *oas.Schema { structSchema = oas.Binary() break } - s := scanner.GetSchemaByType(structFieldType) + s := scanner.GetSchemaByType(ctx, structFieldType) if s != nil { schemas = append(schemas, s) } @@ -363,7 +365,7 @@ func (scanner *DefinitionScanner) GetSchemaByType(typ types.Type) *oas.Schema { structSchema.SetProperty( name, - scanner.propSchemaByField(field.Name(), structFieldType, tags, name, flags, scanner.pkg.CommentsOf(scanner.pkg.IdentOf(field))), + scanner.propSchemaByField(ctx, field.Name(), structFieldType, tags, name, flags, scanner.pkg.CommentsOf(scanner.pkg.IdentOf(field))), required, ) } @@ -378,6 +380,7 @@ func (scanner *DefinitionScanner) GetSchemaByType(typ types.Type) *oas.Schema { } func (scanner *DefinitionScanner) propSchemaByField( + ctx context.Context, fieldName string, fieldType types.Type, tags reflect.StructTag, @@ -385,7 +388,7 @@ func (scanner *DefinitionScanner) propSchemaByField( flags map[string]bool, desc string, ) *oas.Schema { - propSchema := scanner.GetSchemaByType(fieldType) + propSchema := scanner.GetSchemaByType(ctx, fieldType) refSchema := (*oas.Schema)(nil) @@ -499,5 +502,5 @@ func getSchemaTypeFromBasicType(basicTypeName string) (typ oas.Type, format stri if schemaTypeAndFormat, ok := basicTypeToSchemaType[basicTypeName]; ok { return oas.Type(schemaTypeAndFormat[0]), schemaTypeAndFormat[1] } - panic(fmt.Errorf("unsupported type %q", basicTypeName)) + panic(errors.Errorf("unsupported type %q", basicTypeName)) } diff --git a/openapi/generator/definition_scanner_test.go b/openapi/generator/definition_scanner_test.go index 4fed840..1b98785 100644 --- a/openapi/generator/definition_scanner_test.go +++ b/openapi/generator/definition_scanner_test.go @@ -1,6 +1,7 @@ package generator import ( + "context" "encoding/json" "fmt" "os" @@ -10,6 +11,7 @@ import ( "github.com/go-courier/oas" "github.com/go-courier/packagesx" + "github.com/pkg/errors" "github.com/stretchr/testify/require" ) @@ -314,7 +316,7 @@ func TestDefinitionScanner(t *testing.T) { for _, c := range cases { t.Run(c[0], func(t *testing.T) { - s := scanner.Def(pkg.TypeName(c[0])) + s := scanner.Def(context.Background(), pkg.TypeName(c[0])) data, _ := json.MarshalIndent(s, "", " ") require.Equal(t, strings.TrimSpace(c[1]), string(data)) }) @@ -331,7 +333,7 @@ func TestDefinitionScanner(t *testing.T) { t.Run("invalid", func(t *testing.T) { err := tryCatch(func() { - scanner.Def(pkg.TypeName("InvalidComposed")) + scanner.Def(context.Background(), pkg.TypeName("InvalidComposed")) }) require.Error(t, err) }) @@ -340,7 +342,7 @@ func TestDefinitionScanner(t *testing.T) { func tryCatch(fn func()) (err error) { defer func() { if e := recover(); e != nil { - err = fmt.Errorf("%v", e) + err = errors.Errorf("%v", e) } }() diff --git a/openapi/generator/openapi_generator.go b/openapi/generator/openapi_generator.go index ee1ac90..dd9330b 100644 --- a/openapi/generator/openapi_generator.go +++ b/openapi/generator/openapi_generator.go @@ -1,8 +1,8 @@ package generator import ( + "context" "encoding/json" - "fmt" "go/ast" "go/types" "io/ioutil" @@ -15,6 +15,7 @@ import ( "github.com/fatih/color" "github.com/go-courier/oas" "github.com/go-courier/packagesx" + "github.com/pkg/errors" ) func NewOpenAPIGenerator(pkg *packagesx.Package) *OpenAPIGenerator { @@ -53,7 +54,7 @@ func rootRouter(pkgInfo *packagesx.Package, callExpr *ast.CallExpr) *types.Var { return nil } -func (g *OpenAPIGenerator) Scan() { +func (g *OpenAPIGenerator) Scan(ctx context.Context) { defer func() { g.routerScanner.operatorScanner.BindSchemas(g.openapi) }() @@ -80,7 +81,7 @@ func (g *OpenAPIGenerator) Scan() { operation := g.OperationByOperatorTypes(method, route.Operators...) if _, exists := operationIDs[operation.OperationId]; exists { - panic(fmt.Errorf("operationID %s should be unique", operation.OperationId)) + panic(errors.Errorf("operationID %s should be unique", operation.OperationId)) } operationIDs[operation.OperationId] = route diff --git a/openapi/generator/openapi_generator_test.go b/openapi/generator/openapi_generator_test.go index 7c9a274..4ba0b78 100644 --- a/openapi/generator/openapi_generator_test.go +++ b/openapi/generator/openapi_generator_test.go @@ -1,12 +1,14 @@ package generator import ( + "context" "os" "path/filepath" "testing" + "github.com/go-courier/logr" + "github.com/go-courier/packagesx" - "github.com/sirupsen/logrus" "github.com/stretchr/testify/require" ) @@ -14,12 +16,13 @@ func TestOpenAPIGenerator(t *testing.T) { cwd, _ := os.Getwd() dir := filepath.Join(cwd, "../../__examples__/server/cmd/app") + ctx := logr.WithLogger(context.Background(), logr.StdLogger()) + pkg, err := packagesx.Load(dir) require.NoError(t, err) - logrus.SetLevel(logrus.DebugLevel) g := NewOpenAPIGenerator(pkg) - g.Scan() + g.Scan(ctx) g.Output(dir) } diff --git a/openapi/generator/operator_scanner.go b/openapi/generator/operator_scanner.go index 677add2..2a82a49 100644 --- a/openapi/generator/operator_scanner.go +++ b/openapi/generator/operator_scanner.go @@ -13,6 +13,9 @@ import ( "strconv" "strings" + "github.com/go-courier/logr" + "github.com/pkg/errors" + "github.com/go-courier/httptransport" "github.com/go-courier/httptransport/httpx" "github.com/go-courier/httptransport/transformers" @@ -20,7 +23,6 @@ import ( "github.com/go-courier/packagesx" "github.com/go-courier/reflectx/typesutil" "github.com/go-courier/statuserror" - "github.com/sirupsen/logrus" ) func NewOperatorScanner(pkg *packagesx.Package) *OperatorScanner { @@ -38,7 +40,7 @@ type OperatorScanner struct { operators map[*types.TypeName]*Operator } -func (scanner *OperatorScanner) Operator(typeName *types.TypeName) *Operator { +func (scanner *OperatorScanner) Operator(ctx context.Context, typeName *types.TypeName) *Operator { if typeName == nil { return nil } @@ -58,11 +60,11 @@ func (scanner *OperatorScanner) Operator(typeName *types.TypeName) *Operator { return operator } - logrus.Debugf("scanning Operator `%s.%s`", typeName.Pkg().Path(), typeName.Name()) + logr.FromContext(ctx).Debug("scanning Operator `%s.%s`", typeName.Pkg().Path(), typeName.Name()) defer func() { if e := recover(); e != nil { - panic(fmt.Errorf("scan Operator `%s` failed, panic: %s; calltrace: %s", fullTypeName(typeName), fmt.Sprint(e), string(debug.Stack()))) + panic(errors.Errorf("scan Operator `%s` failed, panic: %s; calltrace: %s", fullTypeName(typeName), fmt.Sprint(e), string(debug.Stack()))) } }() @@ -72,8 +74,8 @@ func (scanner *OperatorScanner) Operator(typeName *types.TypeName) *Operator { operator.Tag = scanner.tagFrom(typeName.Pkg().Path()) scanner.scanRouteMeta(operator, typeName) - scanner.scanParameterOrRequestBody(operator, typeStruct) - scanner.scanReturns(operator, typeName) + scanner.scanParameterOrRequestBody(ctx, operator, typeStruct) + scanner.scanReturns(ctx, operator, typeName) // cached scanned if scanner.operators == nil { @@ -105,7 +107,7 @@ func (scanner *OperatorScanner) singleReturnOf(typeName *types.TypeName, name st if v.Value != nil { s, err := strconv.Unquote(v.Value.ExactString()) if err != nil { - panic(fmt.Errorf("%s: %s", err, v.Value)) + panic(errors.Errorf("%s: %s", err, v.Value)) } return s, true } @@ -191,7 +193,7 @@ func (scanner *OperatorScanner) scanRouteMeta(op *Operator, typeName *types.Type } } -func (scanner *OperatorScanner) scanReturns(op *Operator, typeName *types.TypeName) { +func (scanner *OperatorScanner) scanReturns(ctx context.Context, op *Operator, typeName *types.TypeName) { for _, typ := range []types.Type{ typeName.Type(), types.NewPointer(typeName.Type()), @@ -204,10 +206,10 @@ func (scanner *OperatorScanner) scanReturns(op *Operator, typeName *types.TypeNa if v.Type != nil { if v.Type.String() != types.Typ[types.UntypedNil].String() { if op.SuccessType != nil && op.SuccessType.String() != v.Type.String() { - logrus.Warnf(fmt.Sprintf("%s success result must be same struct, but got %v, already set %v", op.ID, v.Type, op.SuccessType)) + logr.FromContext(ctx).Warn(errors.Errorf("%s success result must be same struct, but got %v, already set %v", op.ID, v.Type, op.SuccessType)) } op.SuccessType = v.Type - op.SuccessStatus, op.SuccessResponse = scanner.getResponse(v.Type, v.Expr) + op.SuccessStatus, op.SuccessResponse = scanner.getResponse(ctx, v.Type, v.Expr) } } } @@ -215,7 +217,7 @@ func (scanner *OperatorScanner) scanReturns(op *Operator, typeName *types.TypeNa if scanner.StatusErrScanner.StatusErrType != nil { op.StatusErrors = scanner.StatusErrScanner.StatusErrorsInFunc(method.(*typesutil.TMethod).Func) - op.StatusErrorSchema = scanner.DefinitionScanner.GetSchemaByType(scanner.StatusErrScanner.StatusErrType) + op.StatusErrorSchema = scanner.DefinitionScanner.GetSchemaByType(ctx, scanner.StatusErrScanner.StatusErrType) } } } @@ -239,7 +241,7 @@ func (scanner *OperatorScanner) firstValueOfFunc(named *types.Named, name string return nil, false } -func (scanner *OperatorScanner) getResponse(tpe types.Type, expr ast.Expr) (statusCode int, response *oas.Response) { +func (scanner *OperatorScanner) getResponse(ctx context.Context, tpe types.Type, expr ast.Expr) (statusCode int, response *oas.Response) { response = &oas.Response{} if tpe.String() == "error" { @@ -321,22 +323,23 @@ func (scanner *OperatorScanner) getResponse(tpe types.Type, expr ast.Expr) (stat contentType = httpx.MIME_JSON } - response.AddContent(contentType, oas.NewMediaTypeWithSchema(scanner.DefinitionScanner.GetSchemaByType(tpe))) + response.AddContent(contentType, oas.NewMediaTypeWithSchema(scanner.DefinitionScanner.GetSchemaByType(ctx, tpe))) return } -func (scanner *OperatorScanner) scanParameterOrRequestBody(op *Operator, typeStruct *types.Struct) { +func (scanner *OperatorScanner) scanParameterOrRequestBody(ctx context.Context, op *Operator, typeStruct *types.Struct) { typesutil.EachField(typesutil.FromTType(typeStruct), "name", func(field typesutil.StructField, fieldDisplayName string, omitempty bool) bool { location, _ := tagValueAndFlagsByTagString(field.Tag().Get("in")) if location == "" { - panic(fmt.Errorf("missing tag `in` for %s of %s", field.Name(), op.ID)) + panic(errors.Errorf("missing tag `in` for %s of %s", field.Name(), op.ID)) } name, flags := tagValueAndFlagsByTagString(field.Tag().Get("name")) schema := scanner.DefinitionScanner.propSchemaByField( + ctx, field.Name(), field.Type().(*typesutil.TType).Type, field.Tag(), diff --git a/openapi/generator/operator_scanner_test.go b/openapi/generator/operator_scanner_test.go index fc5c3cb..6797a70 100644 --- a/openapi/generator/operator_scanner_test.go +++ b/openapi/generator/operator_scanner_test.go @@ -1,6 +1,7 @@ package generator import ( + "context" "encoding/json" "fmt" "os" @@ -195,7 +196,7 @@ func TestOperatorScanner(t *testing.T) { for n, result := range cases { t.Run(n, func(t *testing.T) { operation := &oas.Operation{} - op := scanner.Operator(pkg.TypeName(n)) + op := scanner.Operator(context.Background(), pkg.TypeName(n)) op.BindOperation("", operation, true) data, _ := json.MarshalIndent(operation, "", " ") fmt.Println(string(data)) diff --git a/openapi/generator/router_scanner.go b/openapi/generator/router_scanner.go index 3687c16..efd7a44 100644 --- a/openapi/generator/router_scanner.go +++ b/openapi/generator/router_scanner.go @@ -2,6 +2,7 @@ package generator import ( "bytes" + "context" "go/ast" "go/types" "sort" @@ -174,7 +175,7 @@ func (scanner *RouterScanner) OperatorTypeNameFromType(typ types.Type) *Operator case *types.Named: typeName := t.Obj() - if operator := scanner.operatorScanner.Operator(typeName); operator != nil { + if operator := scanner.operatorScanner.Operator(context.Background(), typeName); operator != nil { return &OperatorWithTypeName{ Operator: operator, TypeName: typeName, diff --git a/pathname_pattern.go b/pathname_pattern.go index e06aa94..a653233 100644 --- a/pathname_pattern.go +++ b/pathname_pattern.go @@ -1,9 +1,10 @@ package httptransport import ( - "fmt" "strings" + "github.com/pkg/errors" + "github.com/julienschmidt/httprouter" ) @@ -66,7 +67,7 @@ func (pattern *PathnamePattern) Parse(pathname string) (params httprouter.Params parts := toPathParts(pathname) if len(parts) != len(pattern.parts) { - return nil, fmt.Errorf("pathname %s is not match %s", pathname, pattern) + return nil, errors.Errorf("pathname %s is not match %s", pathname, pattern) } for idx, part := range pattern.parts { @@ -76,7 +77,7 @@ func (pattern *PathnamePattern) Parse(pathname string) (params httprouter.Params Value: parts[idx], }) } else if part != parts[idx] { - return nil, fmt.Errorf("pathname %s is not match %s", pathname, pattern) + return nil, errors.Errorf("pathname %s is not match %s", pathname, pattern) } } diff --git a/request_transformer.go b/request_transformer.go index d4468b9..74ea44c 100644 --- a/request_transformer.go +++ b/request_transformer.go @@ -3,7 +3,6 @@ package httptransport import ( "bytes" "context" - "fmt" "go/ast" "io" "io/ioutil" @@ -16,6 +15,9 @@ import ( "sync" "time" + verrors "github.com/go-courier/validator/errors" + "github.com/pkg/errors" + "github.com/go-courier/courier" "github.com/go-courier/httptransport/httpx" "github.com/go-courier/httptransport/transformers" @@ -23,7 +25,6 @@ import ( "github.com/go-courier/reflectx/typesutil" "github.com/go-courier/statuserror" "github.com/go-courier/validator" - "github.com/go-courier/validator/errors" "github.com/julienschmidt/httprouter" ) @@ -93,7 +94,7 @@ func isRequestOut(ctx context.Context) bool { } func (mgr *RequestTransformerMgr) newRequestTransformer(ctx context.Context, typ reflect.Type) (*RequestTransformer, error) { - errSet := errors.NewErrorSet("") + errSet := verrors.NewErrorSet("") rt := &RequestTransformer{} rt.Type = reflectx.Deref(typ) @@ -105,7 +106,7 @@ func (mgr *RequestTransformerMgr) newRequestTransformer(ctx context.Context, typ in, exists := tag.Lookup("in") if !exists { - panic(fmt.Errorf("missing tag `in` of %s", field.Name())) + panic(errors.Errorf("missing tag `in` of %s", field.Name())) } if in == "path" { @@ -182,10 +183,10 @@ func (t *RequestTransformer) NewRequestWithContext(ctx context.Context, method s typ := reflectx.Deref(rv.Type()) if !typ.ConvertibleTo(t.Type) { - return nil, fmt.Errorf("unmatched request transformer, need %s but got %s", t.Type, typ) + return nil, errors.Errorf("unmatched request transformer, need %s but got %s", t.Type, typ) } - errSet := errors.NewErrorSet("") + errSet := verrors.NewErrorSet("") params := httprouter.Params{} query := url.Values{} header := http.Header{} @@ -316,15 +317,15 @@ func (e *BadRequest) SetMsg(msg string) { } func (e *BadRequest) AddErr(err error, in string, nameOrIdx ...interface{}) { - errSet := errors.NewErrorSet("") + errSet := verrors.NewErrorSet("") - if es, ok := err.(*errors.ErrorSet); ok && in == "body" { + if es, ok := err.(*verrors.ErrorSet); ok && in == "body" { errSet = es } else { errSet.AddErr(err, nameOrIdx...) } - errSet.Flatten().Each(func(fieldErr *errors.FieldError) { + errSet.Flatten().Each(func(fieldErr *verrors.FieldError) { e.errorFields = append(e.errorFields, statuserror.NewErrorField(in, fieldErr.Field.String(), fieldErr.Error.Error())) }) } @@ -359,7 +360,7 @@ func (t *RequestTransformer) DecodeFrom(info *RequestInfo, meta *courier.Operato typ := reflectx.Deref(rv.Type()) if !typ.ConvertibleTo(t.Type) { - return fmt.Errorf("unmatched request transformer, need %s but got %s", t.Type, typ) + return errors.Errorf("unmatched request transformer, need %s but got %s", t.Type, typ) } badRequestError := &BadRequest{} @@ -547,7 +548,7 @@ func (info *RequestInfo) Body() io.Reader { func OperatorParamsFromStruct(v interface{}) map[string][]string { rv := reflectx.Indirect(reflect.ValueOf(v)) if rv.Kind() != reflect.Struct { - panic(fmt.Errorf("must struct")) + panic(errors.Errorf("must struct")) } params := map[string][]string{} diff --git a/request_transformer_test.go b/request_transformer_test.go index 0bac877..50c4b04 100644 --- a/request_transformer_test.go +++ b/request_transformer_test.go @@ -21,6 +21,7 @@ import ( "github.com/go-courier/reflectx" "github.com/go-courier/statuserror" "github.com/go-courier/validator/errors" + perrors "github.com/pkg/errors" "github.com/stretchr/testify/require" "github.com/go-courier/httptransport" @@ -482,7 +483,7 @@ type ReqWithPostValidate struct { } func (ReqWithPostValidate) PostValidate(badRequest *httptransport.BadRequest) { - badRequest.AddErr(fmt.Errorf("ops"), "query", "StartedAt") + badRequest.AddErr(perrors.Errorf("ops"), "query", "StartedAt") } func ExampleRequestTransformer_DecodeFrom_requestInfo_failedOfPost() { diff --git a/service_meta.go b/service_meta.go index 89dbb05..875a9be 100644 --- a/service_meta.go +++ b/service_meta.go @@ -4,8 +4,6 @@ import ( "context" "net/http" "os" - - "github.com/sirupsen/logrus" ) type ServiceMeta struct { @@ -51,16 +49,3 @@ func ServerMetaFromContext(ctx context.Context) ServiceMeta { p, _ := ctx.Value(contextKeyServiceMetaKey(1)).(ServiceMeta) return p } - -type ServiceMetaHook struct { - ServiceMeta -} - -func (ServiceMetaHook) Levels() []logrus.Level { - return logrus.AllLevels -} - -func (s *ServiceMetaHook) Fire(entry *logrus.Entry) error { - entry.Data["service"] = s.String() - return nil -} diff --git a/service_meta_test.go b/service_meta_test.go index bbaa6c6..861564b 100644 --- a/service_meta_test.go +++ b/service_meta_test.go @@ -5,7 +5,6 @@ import ( "os" "testing" - "github.com/sirupsen/logrus" "github.com/stretchr/testify/require" ) @@ -30,17 +29,3 @@ func TestServiceMetaWithContext(t *testing.T) { serviceMeta := ServerMetaFromContext(ctx) require.Equal(t, "test", serviceMeta.Name) } - -func TestHookForServiceMeta(t *testing.T) { - hook := ServiceMetaHook{ - ServiceMeta{ - Name: "test", - }, - } - - entry := logrus.NewEntry(logrus.StandardLogger()) - - require.Equal(t, logrus.AllLevels, hook.Levels()) - require.NoError(t, hook.Fire(entry)) - require.Equal(t, hook.ServiceMeta.String(), entry.Data["service"]) -} diff --git a/transformers/form_transformer.go b/transformers/form_transformer.go index d2eedda..8647b0e 100644 --- a/transformers/form_transformer.go +++ b/transformers/form_transformer.go @@ -3,7 +3,6 @@ package transformers import ( "bytes" "context" - "fmt" "io" "io/ioutil" "mime" @@ -12,7 +11,8 @@ import ( "reflect" "github.com/go-courier/reflectx/typesutil" - "github.com/go-courier/validator/errors" + verrors "github.com/go-courier/validator/errors" + "github.com/pkg/errors" ) func init() { @@ -56,7 +56,7 @@ func (FormTransformer) New(ctx context.Context, typ typesutil.Type) (Transformer typ = typesutil.Deref(typ) if typ.Kind() != reflect.Struct { - return nil, fmt.Errorf("content transformer `%s` should be used for struct type", transformer) + return nil, errors.Errorf("content transformer `%s` should be used for struct type", transformer) } transformer.FlattenParams = &FlattenParams{} @@ -76,7 +76,7 @@ func (transformer *FormTransformer) EncodeToWriter(w io.Writer, v interface{}) ( valueAdder := url.Values{} - errSet := errors.NewErrorSet("") + errSet := verrors.NewErrorSet("") NamedStructFieldValueRange(reflect.Indirect(rv), func(fieldValue reflect.Value, field *reflect.StructField) { fieldOpt := transformer.fieldOpts[field.Name] @@ -124,7 +124,7 @@ func (transformer *FormTransformer) DecodeFromReader(r io.Reader, v interface{}, return err } - errSet := errors.NewErrorSet("") + errSet := verrors.NewErrorSet("") NamedStructFieldValueRange(reflect.Indirect(rv), func(fieldValue reflect.Value, field *reflect.StructField) { fieldOpt := transformer.fieldOpts[field.Name] diff --git a/transformers/json_transformer_test.go b/transformers/json_transformer_test.go index 0d733b1..9fd78dc 100644 --- a/transformers/json_transformer_test.go +++ b/transformers/json_transformer_test.go @@ -3,19 +3,20 @@ package transformers import ( "bytes" "context" - "fmt" "reflect" "testing" + verrors "github.com/go-courier/validator/errors" + "github.com/pkg/errors" + "github.com/go-courier/reflectx/typesutil" - "github.com/go-courier/validator/errors" "github.com/stretchr/testify/require" ) type S string func (s *S) UnmarshalText(data []byte) error { - return fmt.Errorf("err") + return errors.Errorf("err") } func TestJSONTransformer(t *testing.T) { @@ -105,7 +106,7 @@ func TestJSONTransformer(t *testing.T) { for _, c := range cases { b := bytes.NewBufferString(c.json) err := ct.DecodeFromReader(b, &data) - err.(*errors.ErrorSet).Each(func(fieldErr *errors.FieldError) { + err.(*verrors.ErrorSet).Each(func(fieldErr *verrors.FieldError) { require.Equal(t, c.location, fieldErr.Field.String()) }) } diff --git a/transformers/multipart_transformer.go b/transformers/multipart_transformer.go index 724770c..2c2eaed 100644 --- a/transformers/multipart_transformer.go +++ b/transformers/multipart_transformer.go @@ -11,9 +11,11 @@ import ( "reflect" "strconv" + "github.com/pkg/errors" + "github.com/go-courier/httptransport/httpx" "github.com/go-courier/reflectx/typesutil" - "github.com/go-courier/validator/errors" + verrors "github.com/go-courier/validator/errors" ) func init() { @@ -44,7 +46,7 @@ func (MultipartTransformer) New(ctx context.Context, typ typesutil.Type) (Transf typ = typesutil.Deref(typ) if typ.Kind() != reflect.Struct { - return nil, fmt.Errorf("content transformer `%s` should be used for struct type", transformer) + return nil, errors.Errorf("content transformer `%s` should be used for struct type", transformer) } transformer.FlattenParams = &FlattenParams{} @@ -65,7 +67,7 @@ func (transformer *MultipartTransformer) EncodeToWriter(w io.Writer, v interface multipartWriter := multipart.NewWriter(w) return superWrite(w, func(w io.Writer) error { - errSet := errors.NewErrorSet("") + errSet := verrors.NewErrorSet("") addPart := func(rv reflect.Value, fieldName string, fieldTransformer Transformer, omitempty bool) error { buf := bytes.NewBuffer(nil) @@ -175,7 +177,7 @@ func (transformer *MultipartTransformer) DecodeFromReader(r io.Reader, v interfa return err } - errSet := errors.NewErrorSet("") + errSet := verrors.NewErrorSet("") setValue := func(rv reflect.Value, fieldTransformer Transformer, fieldName string, idx int, omitempty bool) error { if rv.Type().ConvertibleTo(typeFileHeader) { diff --git a/transformers/transformer.go b/transformers/transformer.go index 3d92c4b..4c7e7e1 100644 --- a/transformers/transformer.go +++ b/transformers/transformer.go @@ -3,13 +3,14 @@ package transformers import ( "bytes" "context" - "fmt" "io" "net/textproto" "net/url" "reflect" "sync" + "github.com/pkg/errors" + "github.com/go-courier/reflectx" "github.com/go-courier/reflectx/typesutil" ) @@ -168,7 +169,7 @@ func (c *TransformerFactory) NewTransformer(ctx context.Context, typ typesutil.T return contentTransformer, nil } - return nil, fmt.Errorf("fmt %s is not supported for content transformer", key) + return nil, errors.Errorf("fmt %s is not supported for content transformer", key) } type Adder interface { diff --git a/utils.go b/utils.go index 34afe93..f32ac5b 100644 --- a/utils.go +++ b/utils.go @@ -1,13 +1,11 @@ package httptransport -import ( - "fmt" -) +import "github.com/pkg/errors" func TryCatch(fn func()) (err error) { defer func() { if e := recover(); e != nil { - err = fmt.Errorf("%v", e) + err = errors.Errorf("%+v", e) } }()