package grpcapi import ( context "context" "fmt" "log" "net" "git.coopgo.io/coopgo-platform/mobility-accounts/handlers" "github.com/spf13/viper" "google.golang.org/grpc" codes "google.golang.org/grpc/codes" "google.golang.org/grpc/reflection" status "google.golang.org/grpc/status" ) type MobilityAccountsServerImpl struct { handler handlers.MobilityAccountsHandler } func NewMobilityAccountsServer(h handlers.MobilityAccountsHandler) *MobilityAccountsServerImpl { return &MobilityAccountsServerImpl{ handler: h, } } func (s MobilityAccountsServerImpl) Login(ctx context.Context, req *LoginRequest) (*LoginResponse, error) { account, err := s.handler.Login(req.Username, req.Password, req.Namespace) if err != nil { return nil, status.Errorf(codes.NotFound, "could not log in : %v", err) } response := AccountFromStorageType(account) return &LoginResponse{Account: response}, nil } func (s MobilityAccountsServerImpl) Register(ctx context.Context, req *RegisterRequest) (*RegisterResponse, error) { a := req.Account.ToStorageType() account, err := s.handler.Register(a) if err != nil { fmt.Println(err) return nil, status.Errorf(codes.AlreadyExists, "account creation failed : %v", err) } response := AccountFromStorageType(account) return &RegisterResponse{Account: response}, nil } func (MobilityAccountsServerImpl) UpdateData(context.Context, *UpdateDataRequest) (*UpdateDataResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method UpdateData not implemented") } func (MobilityAccountsServerImpl) GetAccount(context.Context, *GetAccountRequest) (*GetAccountResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method GetAccount not implemented") } func (s MobilityAccountsServerImpl) GetAccounts(ctx context.Context, req *GetAccountsRequest) (*GetAccountsResponse, error) { responses, err := s.handler.GetAccounts(req.Namespaces) if err != nil { return nil, status.Errorf(codes.NotFound, "could not get accounts : %v", err) } var accounts []*Account for _, a := range responses { accounts = append(accounts, AccountFromStorageType(&a)) } return &GetAccountsResponse{Accounts: accounts}, nil } func (MobilityAccountsServerImpl) ChangePassword(ctc context.Context, req *ChangePasswordRequest) (*ChangePasswordResponse, error) { return nil, status.Errorf(codes.Unimplemented, "method not implemented") } func (MobilityAccountsServerImpl) mustEmbedUnimplementedMobilityAccountsServer() {} func Run(done chan error, cfg *viper.Viper, handler handlers.MobilityAccountsHandler) { var ( dev_env = cfg.GetBool("dev_env") address = ":" + cfg.GetString("services.grpc.port") ) fmt.Println("-> GRPC server on", address) server := grpc.NewServer() RegisterMobilityAccountsServer(server, NewMobilityAccountsServer(handler)) l, err := net.Listen("tcp", address) if err != nil { log.Fatal(err) } if dev_env { reflection.Register(server) } if err := server.Serve(l); err != nil { fmt.Println("gRPC service ended") done <- err } }