mirror of
				https://github.com/go-kratos/kratos.git
				synced 2025-10-30 23:47:59 +02:00 
			
		
		
		
	| @@ -31,19 +31,22 @@ func (e *Error) WithMetadata(md map[string]string) *Error { | |||||||
| // Is matches each error in the chain with the target value. | // Is matches each error in the chain with the target value. | ||||||
| func (e *Error) Is(err error) bool { | func (e *Error) Is(err error) bool { | ||||||
| 	if target := new(Error); errors.As(err, &target) { | 	if target := new(Error); errors.As(err, &target) { | ||||||
| 		return target.Code == e.Code && target.Reason == e.Reason | 		return target.Code == e.Code && | ||||||
|  | 			target.Domain == e.Domain && | ||||||
|  | 			target.Reason == e.Reason | ||||||
| 	} | 	} | ||||||
| 	return false | 	return false | ||||||
| } | } | ||||||
|  |  | ||||||
| func (e *Error) Error() string { | func (e *Error) Error() string { | ||||||
| 	return fmt.Sprintf("error: code = %d domain = %s reason = %s message = %s metadata = %v", e.Code, e.Domain, e.Reason, e.Message, e.Metadata) | 	return fmt.Sprintf("error: code = %d domain = %s reason = %s message = %s", e.Code, e.Domain, e.Reason, e.Message) | ||||||
| } | } | ||||||
|  |  | ||||||
| // New returns an error object for the code, message and error info. | // New returns an error object for the code, message and error info. | ||||||
| func New(code int, reason, message string) *Error { | func New(code int, domain, reason, message string) *Error { | ||||||
| 	return &Error{ | 	return &Error{ | ||||||
| 		Code:    code, | 		Code:    code, | ||||||
|  | 		Domain:  domain, | ||||||
| 		Reason:  reason, | 		Reason:  reason, | ||||||
| 		Message: message, | 		Message: message, | ||||||
| 	} | 	} | ||||||
| @@ -85,5 +88,5 @@ func FromError(err error) *Error { | |||||||
| 	if target := new(Error); errors.As(err, &target) { | 	if target := new(Error); errors.As(err, &target) { | ||||||
| 		return target | 		return target | ||||||
| 	} | 	} | ||||||
| 	return New(http.StatusInternalServerError, "", err.Error()) | 	return New(http.StatusInternalServerError, "", "", err.Error()) | ||||||
| } | } | ||||||
|   | |||||||
| @@ -10,8 +10,8 @@ func TestError(t *testing.T) { | |||||||
| 	var ( | 	var ( | ||||||
| 		base *Error | 		base *Error | ||||||
| 	) | 	) | ||||||
| 	err := New(400, "reason", "message") | 	err := New(400, "domain", "reason", "message") | ||||||
| 	err2 := New(400, "reason", "message") | 	err2 := New(400, "domain", "reason", "message") | ||||||
| 	err3 := err.WithMetadata(map[string]string{ | 	err3 := err.WithMetadata(map[string]string{ | ||||||
| 		"foo": "bar", | 		"foo": "bar", | ||||||
| 	}) | 	}) | ||||||
|   | |||||||
| @@ -3,8 +3,8 @@ package errors | |||||||
| import "net/http" | import "net/http" | ||||||
|  |  | ||||||
| // BadRequest new BadRequest error that is mapped to a 400 response. | // BadRequest new BadRequest error that is mapped to a 400 response. | ||||||
| func BadRequest(reason, message string) *Error { | func BadRequest(domain, reason, message string) *Error { | ||||||
| 	return New(http.StatusBadRequest, reason, message) | 	return New(http.StatusBadRequest, domain, reason, message) | ||||||
| } | } | ||||||
|  |  | ||||||
| // IsBadRequest determines if err is an error which indicates a BadRequest error. | // IsBadRequest determines if err is an error which indicates a BadRequest error. | ||||||
| @@ -14,8 +14,8 @@ func IsBadRequest(err error) bool { | |||||||
| } | } | ||||||
|  |  | ||||||
| // Unauthorized new Unauthorized error that is mapped to a 401 response. | // Unauthorized new Unauthorized error that is mapped to a 401 response. | ||||||
| func Unauthorized(reason, message string) *Error { | func Unauthorized(domain, reason, message string) *Error { | ||||||
| 	return New(http.StatusUnauthorized, reason, message) | 	return New(http.StatusUnauthorized, domain, reason, message) | ||||||
| } | } | ||||||
|  |  | ||||||
| // IsUnauthorized determines if err is an error which indicates a Unauthorized error. | // IsUnauthorized determines if err is an error which indicates a Unauthorized error. | ||||||
| @@ -25,8 +25,8 @@ func IsUnauthorized(err error) bool { | |||||||
| } | } | ||||||
|  |  | ||||||
| // Forbidden new Forbidden error that is mapped to a 403 response. | // Forbidden new Forbidden error that is mapped to a 403 response. | ||||||
| func Forbidden(reason, message string) *Error { | func Forbidden(domain, reason, message string) *Error { | ||||||
| 	return New(http.StatusForbidden, reason, message) | 	return New(http.StatusForbidden, domain, reason, message) | ||||||
| } | } | ||||||
|  |  | ||||||
| // IsForbidden determines if err is an error which indicates a Forbidden error. | // IsForbidden determines if err is an error which indicates a Forbidden error. | ||||||
| @@ -36,8 +36,8 @@ func IsForbidden(err error) bool { | |||||||
| } | } | ||||||
|  |  | ||||||
| // NotFound new NotFound error that is mapped to a 404 response. | // NotFound new NotFound error that is mapped to a 404 response. | ||||||
| func NotFound(reason, message string) *Error { | func NotFound(domain, reason, message string) *Error { | ||||||
| 	return New(http.StatusNotFound, reason, message) | 	return New(http.StatusNotFound, domain, reason, message) | ||||||
| } | } | ||||||
|  |  | ||||||
| // IsNotFound determines if err is an error which indicates an NotFound error. | // IsNotFound determines if err is an error which indicates an NotFound error. | ||||||
| @@ -47,8 +47,8 @@ func IsNotFound(err error) bool { | |||||||
| } | } | ||||||
|  |  | ||||||
| // Conflict new Conflict error that is mapped to a 409 response. | // Conflict new Conflict error that is mapped to a 409 response. | ||||||
| func Conflict(reason, message string) *Error { | func Conflict(domain, reason, message string) *Error { | ||||||
| 	return New(http.StatusConflict, reason, message) | 	return New(http.StatusConflict, domain, reason, message) | ||||||
| } | } | ||||||
|  |  | ||||||
| // IsConflict determines if err is an error which indicates a Conflict error. | // IsConflict determines if err is an error which indicates a Conflict error. | ||||||
| @@ -58,8 +58,8 @@ func IsConflict(err error) bool { | |||||||
| } | } | ||||||
|  |  | ||||||
| // InternalServer new InternalServer error that is mapped to a 500 response. | // InternalServer new InternalServer error that is mapped to a 500 response. | ||||||
| func InternalServer(reason, message string) *Error { | func InternalServer(domain, reason, message string) *Error { | ||||||
| 	return New(http.StatusInternalServerError, reason, message) | 	return New(http.StatusInternalServerError, domain, reason, message) | ||||||
| } | } | ||||||
|  |  | ||||||
| // IsInternalServer determines if err is an error which indicates an InternalServer error. | // IsInternalServer determines if err is an error which indicates an InternalServer error. | ||||||
| @@ -69,8 +69,8 @@ func IsInternalServer(err error) bool { | |||||||
| } | } | ||||||
|  |  | ||||||
| // ServiceUnavailable new ServiceUnavailable error that is mapped to a HTTP 503 response. | // ServiceUnavailable new ServiceUnavailable error that is mapped to a HTTP 503 response. | ||||||
| func ServiceUnavailable(reason, message string) *Error { | func ServiceUnavailable(domain, reason, message string) *Error { | ||||||
| 	return New(http.StatusServiceUnavailable, reason, message) | 	return New(http.StatusServiceUnavailable, domain, reason, message) | ||||||
| } | } | ||||||
|  |  | ||||||
| // IsServiceUnavailable determines if err is an error which indicates a ServiceUnavailable error. | // IsServiceUnavailable determines if err is an error which indicates a ServiceUnavailable error. | ||||||
|   | |||||||
| @@ -5,13 +5,13 @@ import "testing" | |||||||
| func TestTypes(t *testing.T) { | func TestTypes(t *testing.T) { | ||||||
| 	var ( | 	var ( | ||||||
| 		input = []*Error{ | 		input = []*Error{ | ||||||
| 			BadRequest("reason_400", "message_400"), | 			BadRequest("domain_400", "reason_400", "message_400"), | ||||||
| 			Unauthorized("reason_401", "message_401"), | 			Unauthorized("domain_401", "reason_401", "message_401"), | ||||||
| 			Forbidden("reason_403", "message_403"), | 			Forbidden("domain_403", "reason_403", "message_403"), | ||||||
| 			NotFound("reason_404", "message_404"), | 			NotFound("domain_404", "reason_404", "message_404"), | ||||||
| 			Conflict("reason_409", "message_409"), | 			Conflict("domain_409", "reason_409", "message_409"), | ||||||
| 			InternalServer("reason_500", "message_500"), | 			InternalServer("domain_500", "reason_500", "message_500"), | ||||||
| 			ServiceUnavailable("reason_503", "message_503"), | 			ServiceUnavailable("domain_503", "reason_503", "message_503"), | ||||||
| 		} | 		} | ||||||
| 		output = []func(error) bool{ | 		output = []func(error) bool{ | ||||||
| 			IsBadRequest, | 			IsBadRequest, | ||||||
|   | |||||||
| @@ -4,6 +4,7 @@ import ( | |||||||
| 	v1 "github.com/go-kratos/kratos/examples/blog/api/blog/v1" | 	v1 "github.com/go-kratos/kratos/examples/blog/api/blog/v1" | ||||||
| 	"github.com/go-kratos/kratos/examples/blog/internal/conf" | 	"github.com/go-kratos/kratos/examples/blog/internal/conf" | ||||||
| 	"github.com/go-kratos/kratos/examples/blog/internal/service" | 	"github.com/go-kratos/kratos/examples/blog/internal/service" | ||||||
|  | 	"github.com/go-kratos/kratos/v2/log" | ||||||
| 	"github.com/go-kratos/kratos/v2/middleware" | 	"github.com/go-kratos/kratos/v2/middleware" | ||||||
| 	"github.com/go-kratos/kratos/v2/middleware/logging" | 	"github.com/go-kratos/kratos/v2/middleware/logging" | ||||||
| 	"github.com/go-kratos/kratos/v2/middleware/recovery" | 	"github.com/go-kratos/kratos/v2/middleware/recovery" | ||||||
| @@ -18,10 +19,10 @@ func NewGRPCServer(c *conf.Server, tracer trace.TracerProvider, blog *service.Bl | |||||||
| 	var opts = []grpc.ServerOption{ | 	var opts = []grpc.ServerOption{ | ||||||
| 		grpc.Middleware( | 		grpc.Middleware( | ||||||
| 			middleware.Chain( | 			middleware.Chain( | ||||||
| 				recovery.Recovery(), |  | ||||||
| 				status.Server(), | 				status.Server(), | ||||||
| 				tracing.Server(tracing.WithTracerProvider(tracer)), | 				tracing.Server(tracing.WithTracerProvider(tracer)), | ||||||
| 				logging.Server(), | 				logging.Server(log.DefaultLogger), | ||||||
|  | 				recovery.Recovery(), | ||||||
| 			), | 			), | ||||||
| 		), | 		), | ||||||
| 	} | 	} | ||||||
|   | |||||||
| @@ -4,6 +4,7 @@ import ( | |||||||
| 	v1 "github.com/go-kratos/kratos/examples/blog/api/blog/v1" | 	v1 "github.com/go-kratos/kratos/examples/blog/api/blog/v1" | ||||||
| 	"github.com/go-kratos/kratos/examples/blog/internal/conf" | 	"github.com/go-kratos/kratos/examples/blog/internal/conf" | ||||||
| 	"github.com/go-kratos/kratos/examples/blog/internal/service" | 	"github.com/go-kratos/kratos/examples/blog/internal/service" | ||||||
|  | 	"github.com/go-kratos/kratos/v2/log" | ||||||
| 	"github.com/go-kratos/kratos/v2/middleware" | 	"github.com/go-kratos/kratos/v2/middleware" | ||||||
| 	"github.com/go-kratos/kratos/v2/middleware/logging" | 	"github.com/go-kratos/kratos/v2/middleware/logging" | ||||||
| 	"github.com/go-kratos/kratos/v2/middleware/recovery" | 	"github.com/go-kratos/kratos/v2/middleware/recovery" | ||||||
| @@ -26,9 +27,9 @@ func NewHTTPServer(c *conf.Server, tracer trace.TracerProvider, blog *service.Bl | |||||||
| 	} | 	} | ||||||
| 	m := http.Middleware( | 	m := http.Middleware( | ||||||
| 		middleware.Chain( | 		middleware.Chain( | ||||||
| 			recovery.Recovery(), |  | ||||||
| 			tracing.Server(tracing.WithTracerProvider(tracer)), | 			tracing.Server(tracing.WithTracerProvider(tracer)), | ||||||
| 			logging.Server(), | 			logging.Server(log.DefaultLogger), | ||||||
|  | 			recovery.Recovery(), | ||||||
| 		), | 		), | ||||||
| 	) | 	) | ||||||
| 	srv := http.NewServer(opts...) | 	srv := http.NewServer(opts...) | ||||||
|   | |||||||
| @@ -5,9 +5,9 @@ go 1.16 | |||||||
| require ( | require ( | ||||||
| 	entgo.io/ent v0.6.0 | 	entgo.io/ent v0.6.0 | ||||||
| 	github.com/gin-gonic/gin v1.6.3 | 	github.com/gin-gonic/gin v1.6.3 | ||||||
| 	github.com/go-kratos/consul v0.0.0-20210311161349-cfb0345e820d | 	github.com/go-kratos/consul v0.0.0-20210425141546-e047a9f6ec87 | ||||||
| 	github.com/go-kratos/etcd v0.0.0-20210311162832-e0fdc8177742 | 	github.com/go-kratos/etcd v0.0.0-20210311162832-e0fdc8177742 | ||||||
| 	github.com/go-kratos/kratos/v2 v2.0.0-20210415063033-9007abfd2888 | 	github.com/go-kratos/kratos/v2 v2.0.0-20210425121923-9806191b7f32 | ||||||
| 	github.com/go-kratos/nacos v0.0.0-20210415082641-f1b756c16257 | 	github.com/go-kratos/nacos v0.0.0-20210415082641-f1b756c16257 | ||||||
| 	github.com/go-playground/validator/v10 v10.4.1 // indirect | 	github.com/go-playground/validator/v10 v10.4.1 // indirect | ||||||
| 	github.com/go-redis/redis/extra/redisotel v0.3.0 | 	github.com/go-redis/redis/extra/redisotel v0.3.0 | ||||||
| @@ -40,3 +40,5 @@ require ( | |||||||
| 	gopkg.in/yaml.v2 v2.4.0 | 	gopkg.in/yaml.v2 v2.4.0 | ||||||
| 	gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect | 	gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect | ||||||
| ) | ) | ||||||
|  |  | ||||||
|  | replace github.com/go-kratos/kratos/v2 => ../ | ||||||
|   | |||||||
| @@ -125,13 +125,10 @@ github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2 | |||||||
| github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= | github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8= | ||||||
| github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= | github.com/go-kit/kit v0.8.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= | ||||||
| github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= | github.com/go-kit/kit v0.9.0/go.mod h1:xBxKIO96dXMWWy0MnWVtmwkA9/13aqxPnvrjFYMA2as= | ||||||
| github.com/go-kratos/consul v0.0.0-20210311161349-cfb0345e820d h1:px9mGqOsFmcXYsidSYATFoDK/R7x43WnUqiE/9Pu8x8= | github.com/go-kratos/consul v0.0.0-20210425141546-e047a9f6ec87 h1:YKG1fpsSZivsGzeD31Mb91hsmouDFCPq8LR6Uz8SjTg= | ||||||
| github.com/go-kratos/consul v0.0.0-20210311161349-cfb0345e820d/go.mod h1:i/8iM3Xm0YwSmiCdFFZ611y+6rk5Bi1G5UZtBG3t9rg= | github.com/go-kratos/consul v0.0.0-20210425141546-e047a9f6ec87/go.mod h1:O21CidethNnnpWtHS7XcisEKl3P+f9sTZACoIyuvq4Y= | ||||||
| github.com/go-kratos/etcd v0.0.0-20210311162832-e0fdc8177742 h1:gEjXnGJ30PVLE3AMgh1z48PmHgVC4E1q8ZvkdkyJyt8= | github.com/go-kratos/etcd v0.0.0-20210311162832-e0fdc8177742 h1:gEjXnGJ30PVLE3AMgh1z48PmHgVC4E1q8ZvkdkyJyt8= | ||||||
| github.com/go-kratos/etcd v0.0.0-20210311162832-e0fdc8177742/go.mod h1:+1nilFyiWLlYpAWliKnbFhIax79n4l0mOTJhyNw5EEw= | github.com/go-kratos/etcd v0.0.0-20210311162832-e0fdc8177742/go.mod h1:+1nilFyiWLlYpAWliKnbFhIax79n4l0mOTJhyNw5EEw= | ||||||
| github.com/go-kratos/kratos/v2 v2.0.0-20210311152607-a4409adf164e/go.mod h1:oLvFyDBJkkWN8TPqb+NmpvRrSy9uM/K+XQubVRc11a8= |  | ||||||
| github.com/go-kratos/kratos/v2 v2.0.0-20210415063033-9007abfd2888 h1:GmcG4UBf9ome4mJMltFSqxRdQssIRgGBAhIvHJA9MVU= |  | ||||||
| github.com/go-kratos/kratos/v2 v2.0.0-20210415063033-9007abfd2888/go.mod h1:hwEYWw8GFuJ8IoNt3T/3k+7kUfYt+h2fHDcyFlR1jBA= |  | ||||||
| github.com/go-kratos/nacos v0.0.0-20210415082641-f1b756c16257 h1:mJdO5lD+C1UsxJ5NC0rQ2hPx1dA0tdXLp/3UFNWRaFc= | github.com/go-kratos/nacos v0.0.0-20210415082641-f1b756c16257 h1:mJdO5lD+C1UsxJ5NC0rQ2hPx1dA0tdXLp/3UFNWRaFc= | ||||||
| github.com/go-kratos/nacos v0.0.0-20210415082641-f1b756c16257/go.mod h1:GP7wV0ohYEG+x1P/qdNCJGb7K2jtbsMop+5BDaSqBlA= | github.com/go-kratos/nacos v0.0.0-20210415082641-f1b756c16257/go.mod h1:GP7wV0ohYEG+x1P/qdNCJGb7K2jtbsMop+5BDaSqBlA= | ||||||
| github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= | github.com/go-logfmt/logfmt v0.3.0/go.mod h1:Qt1PoO58o5twSAckw1HlFXLmHsOX5/0LbT9GBnD5lWE= | ||||||
| @@ -389,7 +386,6 @@ github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1y | |||||||
| github.com/onsi/gomega v1.10.3/go.mod h1:V9xEwhxec5O8UDM77eCW8vLymOMltsqPVYWrpDsH8xc= | github.com/onsi/gomega v1.10.3/go.mod h1:V9xEwhxec5O8UDM77eCW8vLymOMltsqPVYWrpDsH8xc= | ||||||
| github.com/onsi/gomega v1.10.5 h1:7n6FEkpFmfCoo2t+YYqXH0evK+a9ICQz0xcAy9dYcaQ= | github.com/onsi/gomega v1.10.5 h1:7n6FEkpFmfCoo2t+YYqXH0evK+a9ICQz0xcAy9dYcaQ= | ||||||
| github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48= | github.com/onsi/gomega v1.10.5/go.mod h1:gza4q3jKQJijlu05nKWRCW/GavJumGt8aNRxWg7mt48= | ||||||
| github.com/opentracing/opentracing-go v1.2.0/go.mod h1:GxEUsuufX4nBwe+T+Wl9TAgYrxe9dPLANfrWvHYVTgc= |  | ||||||
| github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= | github.com/pascaldekloe/goe v0.0.0-20180627143212-57f6aae5913c/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= | ||||||
| github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= | github.com/pascaldekloe/goe v0.1.0 h1:cBOtyMzM9HTpWjXfbbunk26uA6nG3a8n06Wieeh0MwY= | ||||||
| github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= | github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc= | ||||||
|   | |||||||
| @@ -20,7 +20,14 @@ func main() { | |||||||
| } | } | ||||||
|  |  | ||||||
| func callHTTP() { | func callHTTP() { | ||||||
| 	client, err := transhttp.NewClient(context.Background()) | 	client, err := transhttp.NewClient( | ||||||
|  | 		context.Background(), | ||||||
|  | 		transhttp.WithMiddleware( | ||||||
|  | 			middleware.Chain( | ||||||
|  | 				recovery.Recovery(), | ||||||
|  | 			), | ||||||
|  | 		), | ||||||
|  | 	) | ||||||
| 	if err != nil { | 	if err != nil { | ||||||
| 		log.Fatal(err) | 		log.Fatal(err) | ||||||
| 	} | 	} | ||||||
| @@ -71,7 +78,7 @@ func callGRPC() { | |||||||
| 	if err != nil { | 	if err != nil { | ||||||
| 		log.Printf("[grpc] SayHello error: %v\n", err) | 		log.Printf("[grpc] SayHello error: %v\n", err) | ||||||
| 	} | 	} | ||||||
| 	if errors.IsInvalidArgument(err) { | 	if errors.IsBadRequest(err) { | ||||||
| 		log.Printf("[grpc] SayHello error is invalid argument: %v\n", err) | 		log.Printf("[grpc] SayHello error is invalid argument: %v\n", err) | ||||||
| 	} | 	} | ||||||
| } | } | ||||||
|   | |||||||
| @@ -17,6 +17,14 @@ import ( | |||||||
| 	"github.com/go-kratos/kratos/v2/transport/http" | 	"github.com/go-kratos/kratos/v2/transport/http" | ||||||
| ) | ) | ||||||
|  |  | ||||||
|  | // go build -ldflags "-X main.Version=x.y.z" | ||||||
|  | var ( | ||||||
|  | 	// Name is the name of the compiled software. | ||||||
|  | 	Name = "helloworld" | ||||||
|  | 	// Version is the version of the compiled software. | ||||||
|  | 	Version = "v1.0.0" | ||||||
|  | ) | ||||||
|  |  | ||||||
| // server is used to implement helloworld.GreeterServer. | // server is used to implement helloworld.GreeterServer. | ||||||
| type server struct { | type server struct { | ||||||
| 	pb.UnimplementedGreeterServer | 	pb.UnimplementedGreeterServer | ||||||
| @@ -25,7 +33,7 @@ type server struct { | |||||||
| // SayHello implements helloworld.GreeterServer | // SayHello implements helloworld.GreeterServer | ||||||
| func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { | func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) { | ||||||
| 	if in.Name == "error" { | 	if in.Name == "error" { | ||||||
| 		return nil, errors.InvalidArgument("BadRequest", "invalid argument %s", in.Name) | 		return nil, errors.BadRequest(Name, "custom_error", fmt.Sprintf("invalid argument %s", in.Name)) | ||||||
| 	} | 	} | ||||||
| 	if in.Name == "panic" { | 	if in.Name == "panic" { | ||||||
| 		panic("grpc panic") | 		panic("grpc panic") | ||||||
| @@ -42,8 +50,8 @@ func main() { | |||||||
| 		grpc.Address(":9000"), | 		grpc.Address(":9000"), | ||||||
| 		grpc.Middleware( | 		grpc.Middleware( | ||||||
| 			middleware.Chain( | 			middleware.Chain( | ||||||
| 				logging.Server(logging.WithLogger(logger)), |  | ||||||
| 				status.Server(), | 				status.Server(), | ||||||
|  | 				logging.Server(logger), | ||||||
| 				recovery.Recovery(), | 				recovery.Recovery(), | ||||||
| 			), | 			), | ||||||
| 		)) | 		)) | ||||||
| @@ -55,14 +63,14 @@ func main() { | |||||||
| 	httpSrv.HandlePrefix("/", pb.NewGreeterHandler(s, | 	httpSrv.HandlePrefix("/", pb.NewGreeterHandler(s, | ||||||
| 		http.Middleware( | 		http.Middleware( | ||||||
| 			middleware.Chain( | 			middleware.Chain( | ||||||
| 				logging.Server(logging.WithLogger(logger)), | 				logging.Server(logger), | ||||||
| 				recovery.Recovery(), | 				recovery.Recovery(), | ||||||
| 			), | 			), | ||||||
| 		)), | 		)), | ||||||
| 	) | 	) | ||||||
|  |  | ||||||
| 	app := kratos.New( | 	app := kratos.New( | ||||||
| 		kratos.Name("helloworld"), | 		kratos.Name(Name), | ||||||
| 		kratos.Server( | 		kratos.Server( | ||||||
| 			httpSrv, | 			httpSrv, | ||||||
| 			grpcSrv, | 			grpcSrv, | ||||||
|   | |||||||
| @@ -11,29 +11,9 @@ import ( | |||||||
| 	"github.com/go-kratos/kratos/v2/transport/http" | 	"github.com/go-kratos/kratos/v2/transport/http" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| // Option is HTTP logging option. |  | ||||||
| type Option func(*options) |  | ||||||
|  |  | ||||||
| type options struct { |  | ||||||
| 	logger log.Logger |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // WithLogger with middleware logger. |  | ||||||
| func WithLogger(logger log.Logger) Option { |  | ||||||
| 	return func(o *options) { |  | ||||||
| 		o.logger = logger |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // Server is an server logging middleware. | // Server is an server logging middleware. | ||||||
| func Server(opts ...Option) middleware.Middleware { | func Server(l log.Logger) middleware.Middleware { | ||||||
| 	options := options{ | 	logger := log.NewHelper("middleware/logging", l) | ||||||
| 		logger: log.DefaultLogger, |  | ||||||
| 	} |  | ||||||
| 	for _, o := range opts { |  | ||||||
| 		o(&options) |  | ||||||
| 	} |  | ||||||
| 	logger := log.NewHelper("middleware/logging", options.logger) |  | ||||||
| 	return func(handler middleware.Handler) middleware.Handler { | 	return func(handler middleware.Handler) middleware.Handler { | ||||||
| 		return func(ctx context.Context, req interface{}) (interface{}, error) { | 		return func(ctx context.Context, req interface{}) (interface{}, error) { | ||||||
| 			var ( | 			var ( | ||||||
| @@ -80,14 +60,8 @@ func Server(opts ...Option) middleware.Middleware { | |||||||
| } | } | ||||||
|  |  | ||||||
| // Client is an client logging middleware. | // Client is an client logging middleware. | ||||||
| func Client(opts ...Option) middleware.Middleware { | func Client(l log.Logger) middleware.Middleware { | ||||||
| 	options := options{ | 	logger := log.NewHelper("middleware/logging", l) | ||||||
| 		logger: log.DefaultLogger, |  | ||||||
| 	} |  | ||||||
| 	for _, o := range opts { |  | ||||||
| 		o(&options) |  | ||||||
| 	} |  | ||||||
| 	logger := log.NewHelper("middleware/logging", options.logger) |  | ||||||
| 	return func(handler middleware.Handler) middleware.Handler { | 	return func(handler middleware.Handler) middleware.Handler { | ||||||
| 		return func(ctx context.Context, req interface{}) (interface{}, error) { | 		return func(ctx context.Context, req interface{}) (interface{}, error) { | ||||||
| 			var ( | 			var ( | ||||||
|   | |||||||
| @@ -40,7 +40,7 @@ func Recovery(opts ...Option) middleware.Middleware { | |||||||
| 	options := options{ | 	options := options{ | ||||||
| 		logger: log.DefaultLogger, | 		logger: log.DefaultLogger, | ||||||
| 		handler: func(ctx context.Context, req, err interface{}) error { | 		handler: func(ctx context.Context, req, err interface{}) error { | ||||||
| 			return errors.InternalServer("recovery", fmt.Sprintf("panic triggered: %v", err)) | 			return errors.InternalServer("", "recovery", fmt.Sprintf("panic triggered: %v", err)) | ||||||
| 		}, | 		}, | ||||||
| 	} | 	} | ||||||
| 	for _, o := range opts { | 	for _, o := range opts { | ||||||
|   | |||||||
| @@ -14,8 +14,6 @@ import ( | |||||||
| 	"google.golang.org/grpc/status" | 	"google.golang.org/grpc/status" | ||||||
| ) | ) | ||||||
|  |  | ||||||
| type domainKey struct{} |  | ||||||
|  |  | ||||||
| // HandlerFunc is middleware error handler. | // HandlerFunc is middleware error handler. | ||||||
| type HandlerFunc func(context.Context, error) error | type HandlerFunc func(context.Context, error) error | ||||||
|  |  | ||||||
| @@ -23,17 +21,9 @@ type HandlerFunc func(context.Context, error) error | |||||||
| type Option func(*options) | type Option func(*options) | ||||||
|  |  | ||||||
| type options struct { | type options struct { | ||||||
| 	domain  string |  | ||||||
| 	handler HandlerFunc | 	handler HandlerFunc | ||||||
| } | } | ||||||
|  |  | ||||||
| // WithDomain with service domain. |  | ||||||
| func WithDomain(domain string) Option { |  | ||||||
| 	return func(o *options) { |  | ||||||
| 		o.domain = domain |  | ||||||
| 	} |  | ||||||
| } |  | ||||||
|  |  | ||||||
| // WithHandler with status handler. | // WithHandler with status handler. | ||||||
| func WithHandler(h HandlerFunc) Option { | func WithHandler(h HandlerFunc) Option { | ||||||
| 	return func(o *options) { | 	return func(o *options) { | ||||||
| @@ -53,7 +43,6 @@ func Server(opts ...Option) middleware.Middleware { | |||||||
| 		return func(ctx context.Context, req interface{}) (interface{}, error) { | 		return func(ctx context.Context, req interface{}) (interface{}, error) { | ||||||
| 			reply, err := handler(ctx, req) | 			reply, err := handler(ctx, req) | ||||||
| 			if err != nil { | 			if err != nil { | ||||||
| 				ctx = context.WithValue(ctx, domainKey{}, options.domain) |  | ||||||
| 				return nil, options.handler(ctx, err) | 				return nil, options.handler(ctx, err) | ||||||
| 			} | 			} | ||||||
| 			return reply, nil | 			return reply, nil | ||||||
| @@ -82,9 +71,6 @@ func Client(opts ...Option) middleware.Middleware { | |||||||
|  |  | ||||||
| func encodeErr(ctx context.Context, err error) error { | func encodeErr(ctx context.Context, err error) error { | ||||||
| 	se := errors.FromError(err) | 	se := errors.FromError(err) | ||||||
| 	if se.Domain == "" { |  | ||||||
| 		se.Domain, _ = ctx.Value(domainKey{}).(string) |  | ||||||
| 	} |  | ||||||
| 	gs := status.Newf(httpToGRPCCode(se.Code), "%s: %s", se.Reason, se.Message) | 	gs := status.Newf(httpToGRPCCode(se.Code), "%s: %s", se.Reason, se.Message) | ||||||
| 	details := []proto.Message{ | 	details := []proto.Message{ | ||||||
| 		&errdetails.ErrorInfo{ | 		&errdetails.ErrorInfo{ | ||||||
|   | |||||||
| @@ -10,7 +10,7 @@ import ( | |||||||
| ) | ) | ||||||
|  |  | ||||||
| func TestErrEncoder(t *testing.T) { | func TestErrEncoder(t *testing.T) { | ||||||
| 	err := errors.BadRequest("InvalidArgument", "format") | 	err := errors.BadRequest("test", "invalid_argument", "format") | ||||||
| 	en := encodeErr(context.Background(), err) | 	en := encodeErr(context.Background(), err) | ||||||
| 	if code := status.Code(en); code != codes.InvalidArgument { | 	if code := status.Code(en); code != codes.InvalidArgument { | ||||||
| 		t.Errorf("expected %d got %d", codes.InvalidArgument, code) | 		t.Errorf("expected %d got %d", codes.InvalidArgument, code) | ||||||
|   | |||||||
| @@ -12,12 +12,12 @@ type validator interface { | |||||||
| } | } | ||||||
|  |  | ||||||
| // Validator is a validator middleware. | // Validator is a validator middleware. | ||||||
| func Validator() middleware.Middleware { | func Validator(domain string) middleware.Middleware { | ||||||
| 	return func(handler middleware.Handler) middleware.Handler { | 	return func(handler middleware.Handler) middleware.Handler { | ||||||
| 		return func(ctx context.Context, req interface{}) (reply interface{}, err error) { | 		return func(ctx context.Context, req interface{}) (reply interface{}, err error) { | ||||||
| 			if v, ok := req.(validator); ok { | 			if v, ok := req.(validator); ok { | ||||||
| 				if err := v.Validate(); err != nil { | 				if err := v.Validate(); err != nil { | ||||||
| 					return nil, errors.BadRequest("validator", err.Error()) | 					return nil, errors.BadRequest(domain, "validator", err.Error()) | ||||||
| 				} | 				} | ||||||
| 			} | 			} | ||||||
| 			return handler(ctx, req) | 			return handler(ctx, req) | ||||||
|   | |||||||
| @@ -6,7 +6,6 @@ import ( | |||||||
|  |  | ||||||
| 	"github.com/go-kratos/kratos/v2/middleware" | 	"github.com/go-kratos/kratos/v2/middleware" | ||||||
| 	"github.com/go-kratos/kratos/v2/middleware/recovery" | 	"github.com/go-kratos/kratos/v2/middleware/recovery" | ||||||
| 	"github.com/go-kratos/kratos/v2/middleware/status" |  | ||||||
| 	"github.com/go-kratos/kratos/v2/registry" | 	"github.com/go-kratos/kratos/v2/registry" | ||||||
| 	"github.com/go-kratos/kratos/v2/transport" | 	"github.com/go-kratos/kratos/v2/transport" | ||||||
| 	"github.com/go-kratos/kratos/v2/transport/grpc/resolver/discovery" | 	"github.com/go-kratos/kratos/v2/transport/grpc/resolver/discovery" | ||||||
| @@ -77,7 +76,6 @@ func dial(ctx context.Context, insecure bool, opts ...ClientOption) (*grpc.Clien | |||||||
| 		timeout: 500 * time.Millisecond, | 		timeout: 500 * time.Millisecond, | ||||||
| 		middleware: middleware.Chain( | 		middleware: middleware.Chain( | ||||||
| 			recovery.Recovery(), | 			recovery.Recovery(), | ||||||
| 			status.Client(), |  | ||||||
| 		), | 		), | ||||||
| 	} | 	} | ||||||
| 	for _, o := range opts { | 	for _, o := range opts { | ||||||
|   | |||||||
| @@ -10,7 +10,6 @@ import ( | |||||||
| 	"github.com/go-kratos/kratos/v2/log" | 	"github.com/go-kratos/kratos/v2/log" | ||||||
| 	"github.com/go-kratos/kratos/v2/middleware" | 	"github.com/go-kratos/kratos/v2/middleware" | ||||||
| 	"github.com/go-kratos/kratos/v2/middleware/recovery" | 	"github.com/go-kratos/kratos/v2/middleware/recovery" | ||||||
| 	"github.com/go-kratos/kratos/v2/middleware/status" |  | ||||||
| 	"github.com/go-kratos/kratos/v2/transport" | 	"github.com/go-kratos/kratos/v2/transport" | ||||||
|  |  | ||||||
| 	"google.golang.org/grpc" | 	"google.golang.org/grpc" | ||||||
| @@ -86,7 +85,6 @@ func NewServer(opts ...ServerOption) *Server { | |||||||
| 		log:     log.NewHelper(loggerName, log.DefaultLogger), | 		log:     log.NewHelper(loggerName, log.DefaultLogger), | ||||||
| 		middleware: middleware.Chain( | 		middleware: middleware.Chain( | ||||||
| 			recovery.Recovery(), | 			recovery.Recovery(), | ||||||
| 			status.Server(), |  | ||||||
| 		), | 		), | ||||||
| 	} | 	} | ||||||
| 	for _, o := range opts { | 	for _, o := range opts { | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user