Last active
February 17, 2019 15:51
-
-
Save ahmagdy/af7ea8ceaf51721fdfc7e49150b891c7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"log" | |
"net" | |
"errors" | |
pb "github.com/Ahmad-Magdy/grpc-by-example/proto-go" | |
"google.golang.org/grpc" | |
"google.golang.org/grpc/reflection" | |
"github.com/satori/go.uuid" | |
) | |
type Account struct { | |
ID string | |
Username string | |
Email string | |
} | |
var ( | |
accounts []*Account | |
) | |
type server struct{} | |
func (s *server) CreateAccount(ctx context.Context, accountRequest *pb.CreateAccountRequest) (*pb.CreateAccountResponse, error) { | |
log.Printf("Server: Recived, %s\n", accountRequest.GetUsername()) | |
newAccount := &Account{ | |
ID: uuid.NewV4().String() , | |
Username: accountRequest.GetUsername(), | |
Email: accountRequest.GetEmail(), | |
} | |
accounts = append(accounts, newAccount) | |
return &pb.CreateAccountResponse{Id: newAccount.ID}, nil | |
} | |
func (s *server) GetAccountInformation(ctx context.Context, m *pb.GetAccountInformationRequest) (*pb.GetAccountInformationResponse,error){ | |
for _,accountItem:= range accounts{ | |
if accountItem.ID == m.GetId(){ | |
return &pb.GetAccountInformationResponse{ | |
Id:accountItem.ID, | |
Username : accountItem.Username, | |
Email:accountItem.Email, }, nil | |
} | |
} | |
return nil, errors.New("account not found") | |
} | |
func main() { | |
lis, err := net.Listen("tcp", ":3000") | |
if err != nil { | |
log.Fatal("Failed to listen: %v", err) | |
} | |
s := grpc.NewServer() | |
pb.RegisterAccountServiceServer(s, &server{}) | |
reflection.Register(s) | |
if err := s.Serve(lis); err != nil { | |
log.Fatal("Failed to serve: %v", err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment