transports.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package user
  2. import (
  3. "context"
  4. "errors"
  5. "github.com/go-kit/kit/transport/grpc"
  6. "github.com/longjoy/micro-go-course/section18/pb"
  7. )
  8. var (
  9. ErrorBadRequest = errors.New("invalid request parameter")
  10. )
  11. type grpcServer struct {
  12. checkPassword grpc.Handler
  13. }
  14. func (s *grpcServer) CheckPassword(ctx context.Context, r *pb.LoginRequest) (*pb.LoginResponse, error) {
  15. _, resp, err := s.checkPassword.ServeGRPC(ctx, r)
  16. if err != nil {
  17. return nil, err
  18. }
  19. return resp.(*pb.LoginResponse), nil
  20. }
  21. func NewUserServer(ctx context.Context, endpoints Endpoints) pb.UserServiceServer {
  22. return &grpcServer{
  23. checkPassword: grpc.NewServer(
  24. endpoints.UserEndpoint,
  25. DecodeLoginRequest,
  26. EncodeLoginResponse,
  27. ),
  28. }
  29. }
  30. func DecodeLoginRequest(ctx context.Context, r interface{}) (interface{}, error) {
  31. req := r.(*pb.LoginRequest)
  32. return LoginForm{
  33. Username: req.Username,
  34. Password: req.Password,
  35. }, nil
  36. }
  37. func EncodeLoginResponse(_ context.Context, r interface{}) (interface{}, error) {
  38. resp := r.(LoginResult)
  39. retStr := "fail"
  40. if resp.Ret {
  41. retStr = "success"
  42. }
  43. errStr := ""
  44. if resp.Err != nil {
  45. errStr = resp.Err.Error()
  46. }
  47. return &pb.LoginResponse{
  48. Ret: retStr,
  49. Err: errStr,
  50. }, nil
  51. }