Skip to content

Instantly share code, notes, and snippets.

@ahmagdy
Last active February 17, 2019 15:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmagdy/af7ea8ceaf51721fdfc7e49150b891c7 to your computer and use it in GitHub Desktop.
Save ahmagdy/af7ea8ceaf51721fdfc7e49150b891c7 to your computer and use it in GitHub Desktop.
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