Skip to content

Instantly share code, notes, and snippets.

@shijuvar
Created October 11, 2016 08:20
Show Gist options
  • Save shijuvar/f43959fb83276b9483601cafdde4cdb6 to your computer and use it in GitHub Desktop.
Save shijuvar/f43959fb83276b9483601cafdde4cdb6 to your computer and use it in GitHub Desktop.
A gRPC server
package main
import (
"log"
"net"
"strings"
"golang.org/x/net/context"
"google.golang.org/grpc"
pb "github.com/shijuvar/go-recipes/grpc/customer"
)
const (
port = ":50051"
)
// server is used to implement customer.CustomerServer.
type server struct {
savedCustomers []*pb.CustomerRequest
}
// CreateCustomer creates a new Customer
func (s *server) CreateCustomer(ctx context.Context, in *pb.CustomerRequest) (*pb.CustomerResponse, error) {
s.savedCustomers = append(s.savedCustomers, in)
return &pb.CustomerResponse{Id: in.Id, Success: true}, nil
}
// GetCustomers returns all customers by given filter
func (s *server) GetCustomers(filter *pb.CustomerFilter, stream pb.Customer_GetCustomersServer) error {
for _, customer := range s.savedCustomers {
if filter.Keyword != "" {
if !strings.Contains(customer.Name, filter.Keyword) {
continue
}
}
if err := stream.Send(customer); err != nil {
return err
}
}
return nil
}
func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
// Creates a new gRPC server
s := grpc.NewServer()
pb.RegisterCustomerServer(s, &server{})
s.Serve(lis)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment