From 725d60134c26a3b6e00c623ea778d4a353864ed1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=8C=85=E5=AD=90?= Date: Mon, 28 Jun 2021 23:50:30 +0800 Subject: [PATCH] examples: add examples/middleware (#1121) * examples: add examples/middleware Co-authored-by: chenzhihui --- examples/middleware/main.go | 69 +++++++++++++++++++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 examples/middleware/main.go diff --git a/examples/middleware/main.go b/examples/middleware/main.go new file mode 100644 index 000000000..a0a58035b --- /dev/null +++ b/examples/middleware/main.go @@ -0,0 +1,69 @@ +package main + +import ( + "context" + "fmt" + "log" + + "github.com/go-kratos/kratos/examples/helloworld/helloworld" + "github.com/go-kratos/kratos/v2" + "github.com/go-kratos/kratos/v2/middleware" + "github.com/go-kratos/kratos/v2/transport/grpc" + "github.com/go-kratos/kratos/v2/transport/http" +) + +type server struct { + helloworld.UnimplementedGreeterServer +} + +func (s *server) SayHello(ctx context.Context, in *helloworld.HelloRequest) (*helloworld.HelloReply, error) { + return &helloworld.HelloReply{Message: "hello"}, nil +} + +func authMiddleware(handler middleware.Handler) middleware.Handler { + return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + log.Println("auth middleware in", req) + reply, err = handler(ctx, req) + fmt.Println("auth middleware out", reply) + return + } +} + +func loggingMiddleware(handler middleware.Handler) middleware.Handler { + return func(ctx context.Context, req interface{}) (reply interface{}, err error) { + fmt.Println("logging middleware in", req) + reply, err = handler(ctx, req) + fmt.Println("logging middleware out", reply) + return + } +} + +func main() { + httpSrv := http.NewServer( + http.Address(":8000"), + http.Middleware( + loggingMiddleware, + authMiddleware, + ), + ) + grpcSrv := grpc.NewServer( + grpc.Address(":9000"), + grpc.Middleware( + loggingMiddleware, + authMiddleware, + ), + ) + s := &server{} + helloworld.RegisterGreeterServer(grpcSrv, s) + helloworld.RegisterGreeterHTTPServer(httpSrv, s) + app := kratos.New( + kratos.Name("helloworld"), + kratos.Server( + httpSrv, + grpcSrv, + ), + ) + if err := app.Run(); err != nil { + log.Fatal(err) + } +}