美文网首页
kratos中间件使用

kratos中间件使用

作者: 彳亍口巴 | 来源:发表于2022-09-26 17:30 被阅读0次

自定义中间件执行逻辑,若不符合要求则报错

package main

import (
    "context"
    "fmt"
    "log"

    "github.com/go-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)
        log.Println("auth middleware out", reply)
        return
    }
}

func loggingMiddleware(handler middleware.Handler) middleware.Handler {
    return func(ctx context.Context, req interface{}) (interface{}, error) {
        //fmt.Println("logging middleware in", req)
        err := myLoginHandler(req)
        if err != nil {
            return nil, err
        }
        reply, err := handler(ctx, req)
        fmt.Println("logging middleware out", reply)
        return reply, err
    }
}

func myLoginHandler(r interface{}) error {
    fmt.Println("我的handler")
    req, ok := r.(helloworld.HelloReply)
    if !ok {
        return fmt.Errorf("err reply:%+v", r)
    }
    if req.Message != "1" {
        return fmt.Errorf("invalid param")
    }
    return nil
}

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)
    }
}

相关文章

网友评论

      本文标题:kratos中间件使用

      本文链接:https://www.haomeiwen.com/subject/zokxartx.html