How to use New method of grpc Package

Best K6 code snippet using grpc.New

main.go

Source:main.go Github

copy

Full Screen

...36 logger *zap.Logger37 err error38 )39 if release {40 logger, _ = zap.NewProduction()41 } else {42 config := zap.NewDevelopmentConfig()43 config.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder44 logger, err = config.Build()45 }46 if err != nil {47 log.Fatalln("init logger", err)48 }49 db := getDB()50 token := os.Getenv(envToken)51 grpcAddr := os.Getenv(envGRPCAddr)52 if grpcAddr == "" {53 grpcAddr = ":5081"54 }55 execServerAddr := os.Getenv(envExecServer)56 if execServerAddr == "" {57 execServerAddr = "localhost:5051"58 }59 execClient := createExecClient(execServerAddr, token, logger)60 ds := newDemoServer(db, execClient, logger)61 var grpcServer *grpc.Server62 grpc_zap.ReplaceGrpcLoggerV2(logger)63 streamMiddleware := []grpc.StreamServerInterceptor{64 grpc_prometheus.StreamServerInterceptor,65 grpc_zap.StreamServerInterceptor(logger),66 grpc_recovery.StreamServerInterceptor(),67 }68 unaryMiddleware := []grpc.UnaryServerInterceptor{69 grpc_prometheus.UnaryServerInterceptor,70 grpc_zap.UnaryServerInterceptor(logger),71 grpc_recovery.UnaryServerInterceptor(),72 }73 if token != "" {74 authFunc := grpcTokenAuth(token)75 streamMiddleware = append(streamMiddleware, grpc_auth.StreamServerInterceptor(authFunc))76 unaryMiddleware = append(unaryMiddleware, grpc_auth.UnaryServerInterceptor(authFunc))77 }78 grpcServer = grpc.NewServer(79 grpc.StreamInterceptor(grpc_middleware.ChainStreamServer(streamMiddleware...)),80 grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(unaryMiddleware...)),81 )82 pb.RegisterDemoBackendServer(grpcServer, ds)83 grpc_prometheus.Register(grpcServer)84 grpc_prometheus.EnableHandlingTimeHistogram()85 lis, err := net.Listen("tcp", grpcAddr)86 if err != nil {87 log.Fatalln(err)88 }89 go func() {90 logger.Sugar().Info("Starting gRPC server at ", grpcAddr)91 logger.Sugar().Info("gRPC serve finished: ", grpcServer.Serve(lis))92 }()93 // collect metrics94 go func() {95 http.Handle("/metrics", promhttp.Handler())96 http.ListenAndServe(":5082", nil)97 }()98 // Graceful shutdown...99 sig := make(chan os.Signal, 1)100 signal.Notify(sig, os.Interrupt)101 <-sig102 grpcServer.GracefulStop()103}104func grpcTokenAuth(token string) func(context.Context) (context.Context, error) {105 return func(ctx context.Context) (context.Context, error) {106 reqToken, err := grpc_auth.AuthFromMD(ctx, "bearer")107 if err != nil {108 return nil, err109 }110 if reqToken != token {111 return nil, status.Errorf(codes.Unauthenticated, "invalid auth token: %v", err)112 }113 return ctx, nil114 }115}116func createExecClient(execServer, token string, logger *zap.Logger) execpb.ExecutorClient {117 conn, err := createGRPCConnection(execServer, token, logger)118 if err != nil {119 log.Fatalln("client", err)120 }121 return execpb.NewExecutorClient(conn)122}123func createGRPCConnection(addr, token string, logger *zap.Logger) (*grpc.ClientConn, error) {124 opts := []grpc.DialOption{125 grpc.WithTransportCredentials(insecure.NewCredentials()),126 grpc.WithUnaryInterceptor(grpc_middleware.ChainUnaryClient(127 grpc_prometheus.UnaryClientInterceptor,128 grpc_zap.UnaryClientInterceptor(logger),129 )),130 grpc.WithStreamInterceptor(131 grpc_middleware.ChainStreamClient(132 grpc_prometheus.StreamClientInterceptor,133 grpc_zap.StreamClientInterceptor(logger),134 ))}135 if token != "" {136 opts = append(opts, grpc.WithPerRPCCredentials(newTokenAuth(token)))137 }138 return grpc.Dial(addr, opts...)139}...

Full Screen

Full Screen

server.go

Source:server.go Github

copy

Full Screen

...29type GrpcServer struct {30 db *sqlx.DB31 batchSize uint32}33// NewGrpcServer returns gRPC server with supporting of batch listing34func NewGrpcServer(db *sqlx.DB, batchSize uint) *GrpcServer {35 return &GrpcServer{36 db: db,37 batchSize: batchSize,38 }39}40// Start method runs server41func (s *GrpcServer) Start(cfg *config.Config) error {42 ctx, cancel := context.WithCancel(context.Background())43 defer cancel()44 gatewayAddr := fmt.Sprintf("%s:%v", cfg.Rest.Host, cfg.Rest.Port)45 grpcAddr := fmt.Sprintf("%s:%v", cfg.Grpc.Host, cfg.Grpc.Port)46 metricsAddr := fmt.Sprintf("%s:%v", cfg.Metrics.Host, cfg.Metrics.Port)47 gatewayServer := createGatewayServer(grpcAddr, gatewayAddr)48 go func() {49 log.Info().Msgf("Gateway server is running on %s", gatewayAddr)50 if err := gatewayServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {51 log.Error().Err(err).Msg("Failed running gateway server")52 cancel()53 }54 }()55 metricsServer := createMetricsServer(cfg)56 go func() {57 log.Info().Msgf("Metrics server is running on %s", metricsAddr)58 if err := metricsServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {59 log.Error().Err(err).Msg("Failed running metrics server")60 cancel()61 }62 }()63 isReady := &atomic.Value{}64 isReady.Store(false)65 statusServer := createStatusServer(cfg, isReady)66 go func() {67 statusAdrr := fmt.Sprintf("%s:%v", cfg.Status.Host, cfg.Status.Port)68 log.Info().Msgf("Status server is running on %s", statusAdrr)69 if err := statusServer.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {70 log.Error().Err(err).Msg("Failed running status server")71 }72 }()73 l, err := net.Listen("tcp", grpcAddr)74 if err != nil {75 return fmt.Errorf("failed to listen: %w", err)76 }77 defer l.Close()78 grpcServer := grpc.NewServer(79 grpc.KeepaliveParams(keepalive.ServerParameters{80 MaxConnectionIdle: time.Duration(cfg.Grpc.MaxConnectionIdle) * time.Minute,81 Timeout: time.Duration(cfg.Grpc.Timeout) * time.Second,82 MaxConnectionAge: time.Duration(cfg.Grpc.MaxConnectionAge) * time.Minute,83 Time: time.Duration(cfg.Grpc.Timeout) * time.Minute,84 }),85 grpc.UnaryInterceptor(grpc_middleware.ChainUnaryServer(86 grpc_ctxtags.UnaryServerInterceptor(),87 grpc_prometheus.UnaryServerInterceptor,88 grpc_opentracing.UnaryServerInterceptor(),89 grpcrecovery.UnaryServerInterceptor(),90 )),91 )92 r := repo.NewAirportRepo(s.db, s.batchSize)93 pb.RegisterTrvAirportApiServiceServer(grpcServer, api.NewAirportAPI(r))94 grpc_prometheus.EnableHandlingTimeHistogram()95 grpc_prometheus.Register(grpcServer)96 go func() {97 log.Info().Msgf("GRPC Server is listening on: %s", grpcAddr)98 if err := grpcServer.Serve(l); err != nil {99 log.Fatal().Err(err).Msg("Failed running gRPC server")100 }101 }()102 go func() {103 time.Sleep(2 * time.Second)104 isReady.Store(true)105 log.Info().Msg("The service is ready to accept requests")106 }()107 if cfg.Project.Debug {...

Full Screen

Full Screen

grpc_server.go

Source:grpc_server.go Github

copy

Full Screen

...36}37/*38Instantiate a GRPC server data structure39*/40func NewGrpcServer(41 address string,42 port int32,43 certs *GrpcSecurity,44 secure bool,45) *GrpcServer {46 server := &GrpcServer{47 address: address,48 port: port,49 secure: secure,50 GrpcSecurity: certs,51 }52 return server53}54/*55Start prepares the GRPC server and starts servicing requests56*/57func (s *GrpcServer) Start(ctx context.Context) {58 host := strings.Join([]string{59 s.address,60 strconv.Itoa(int(s.port)),61 }, ":")62 lis, err := net.Listen("tcp", host)63 if err != nil {64 common.Logger().Fatalf("failed to listen: %v", err)65 }66 if s.secure {67 creds, err := credentials.NewServerTLSFromFile(s.CertFile, s.KeyFile)68 if err != nil {69 common.Logger().Fatalf("could not load TLS keys: %s", err)70 }71 s.gs = grpc.NewServer(grpc.Creds(creds))72 } else {73 common.Logger().Println("In DEFAULT\n")74 s.gs = grpc.NewServer()75 }76 // Register all required services77 for _, service := range s.services {78 service(s.gs)79 }80 if err := s.gs.Serve(lis); err != nil {81 common.Logger().Fatalf("failed to serve: %v\n", err)82 }83}84/*85Stop servicing GRPC requests86*/87func (s *GrpcServer) Stop() {88 s.gs.Stop()89}90/*91AddService appends a generic service request function92*/93func (s *GrpcServer) AddService(94 registerFunction func(*grpc.Server, interface{}),95 handler interface{},96) {97 s.services = append(s.services, func(gs *grpc.Server) { registerFunction(gs, handler) })98}99/*100AddPonSimService appends service request functions for PonSim devices101*/102func (s *GrpcServer) AddPonSimService(device core.PonSimInterface) {103 s.services = append(104 s.services,105 func(gs *grpc.Server) {106 voltha.RegisterPonSimServer(gs, nbi.NewPonSimHandler(device))107 },108 )109}110/*111AddCommonService appends service request functions common to all PonSim devices112*/113func (s *GrpcServer) AddCommonService(device core.PonSimInterface) {114 s.services = append(115 s.services,116 func(gs *grpc.Server) {117 ponsim.RegisterPonSimCommonServer(gs, sbi.NewPonSimCommonHandler(device))118 },119 )120}121/*122AddOltService appends service request functions specific to OLT devices123*/124func (s *GrpcServer) AddOltService(device core.PonSimInterface) {125 s.services = append(126 s.services,127 func(gs *grpc.Server) {128 ponsim.RegisterPonSimOltServer(129 gs,130 sbi.NewPonSimOltHandler(device.(*core.PonSimOltDevice)),131 )132 },133 )134}135/*136AddXPonService appends service request functions specific to XPonSim137*/138func (s *GrpcServer) AddXPonService() {139 s.services = append(140 s.services,141 func(gs *grpc.Server) {142 voltha.RegisterXPonSimServer(gs, nbi.NewXPonSimHandler())143 },144 )145}146/*147AddBalService appends service request functions specific to BAL148*/149func (s *GrpcServer) AddBalService() {150 s.services = append(151 s.services,152 func(gs *grpc.Server) {153 bal.RegisterBalServer(gs, nbi.NewBalHandler())154 },155 )156}...

Full Screen

Full Screen

disneyland_server.go

Source:disneyland_server.go Github

copy

Full Screen

...34 caCert, err := ioutil.ReadFile(Config.CACert)35 if err != nil {36 return nil, err37 }38 caCertPool := x509.NewCertPool()39 caCertPool.AppendCertsFromPEM(caCert)40 tc := credentials.NewTLS(&tls.Config{41 Certificates: []tls.Certificate{peerCert},42 ClientCAs: caCertPool,43 ClientAuth: tls.RequireAndVerifyClientCert,44 })45 return &tc, nil46}47func main() {48 Config = &DisneylandServerConfig{}49 config_path := os.Getenv("DISNEYLAND_CONFIG")50 content, err := ioutil.ReadFile(config_path)51 if err != nil {52 log.Fatalf("Error loading config: %v", err)53 }54 err = yaml.Unmarshal([]byte(content), Config)55 if err != nil {56 log.Fatalf("Error parsing config: %v", err)57 }58 storage, err := disneyland.NewDisneylandStorage(Config.DatabaseURI)59 if err != nil {60 log.Fatal(err)61 }62 lis, err := net.Listen("tcp", Config.ListenOn)63 if err != nil {64 log.Fatalf("failed to listen: %v", err)65 }66 server := &disneyland.Server{67 Storage: storage,68 }69 logger := &logrus.Logger{70 Out: os.Stderr,71 Formatter: new(logrus.TextFormatter),72 Hooks: make(logrus.LevelHooks),73 Level: logrus.DebugLevel,74 }75 logrusEntry := logrus.NewEntry(logger)76 transportCredentials, err := getTransportCredentials()77 if err != nil {78 log.Fatalf("failed to get credentials: %v", err)79 }80 s := grpc.NewServer(81 grpc.MaxRecvMsgSize(maxMessageSizeInBytes),82 grpc.MaxSendMsgSize(maxMessageSizeInBytes),83 grpc.Creds(*transportCredentials),84 grpc_middleware.WithUnaryServerChain(85 grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),86 grpc_logrus.UnaryServerInterceptor(logrusEntry),87 grpc_auth.UnaryServerInterceptor(nil),88 ),89 grpc_middleware.WithStreamServerChain(90 grpc_ctxtags.StreamServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),91 grpc_logrus.StreamServerInterceptor(logrusEntry),92 grpc_auth.StreamServerInterceptor(nil),93 ),94 )...

Full Screen

Full Screen

New

Using AI Code Generation

copy

Full Screen

1conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())2if err != nil {3 log.Fatalf("did not connect: %v", err)4}5defer conn.Close()6c := pb.NewGreeterClient(conn)7if len(os.Args) > 1 {8}9ctx, cancel := context.WithTimeout(context.Background(), time.Second)10defer cancel()11r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})12if err != nil {13 log.Fatalf("could not greet: %v", err)14}15log.Printf("Greeting: %s", r.Message)16conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())17if err != nil {18 log.Fatalf("did not connect: %v", err)19}20defer conn.Close()21c := pb.NewGreeterClient(conn)22if len(os.Args) > 1 {23}24ctx, cancel := context.WithTimeout(context.Background(), time.Second)25defer cancel()26r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})27if err != nil {28 log.Fatalf("could not greet: %v", err)29}30log.Printf("Greeting: %s", r.Message)31conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())32if err != nil {33 log.Fatalf("did not connect: %v", err)34}35defer conn.Close()36c := pb.NewGreeterClient(conn)37if len(os.Args) > 1 {38}39ctx, cancel := context.WithTimeout(context.Background(), time.Second)40defer cancel()41r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})42if err != nil {43 log.Fatalf("could not greet: %v", err)44}45log.Printf("Greeting: %s", r.Message)

Full Screen

Full Screen

New

Using AI Code Generation

copy

Full Screen

1conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())2if err != nil {3 log.Fatalf("did not connect: %v", err)4}5defer conn.Close()6c := pb.NewGreeterClient(conn)7r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})8if err != nil {9 log.Fatalf("could not greet: %v", err)10}11log.Printf("Greeting: %s", r.Message)12conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())13if err != nil {14 log.Fatalf("did not connect: %v", err)15}16defer conn.Close()17c := pb.NewGreeterClient(conn)18r, err := c.SayHelloAgain(context.Background(), &pb.HelloRequest{Name: name})19if err != nil {20 log.Fatalf("could not greet: %v", err)21}22log.Printf("Greeting: %s", r.Message)

Full Screen

Full Screen

New

Using AI Code Generation

copy

Full Screen

1conn, err := grpc.Dial("localhost:8080", grpc.WithInsecure())2if err != nil {3 log.Fatalf("did not connect: %v", err)4}5defer conn.Close()6c := pb.NewGreeterClient(conn)7ctx, cancel := context.WithTimeout(context.Background(), time.Second)8defer cancel()9r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})10if err != nil {11 log.Fatalf("could not greet: %v", err)12}13log.Printf("Greeting: %s", r.Message)14conn, err := grpc.Dial("localhost:8080", grpc.WithInsecure())15if err != nil {16 log.Fatalf("did not connect: %v", err)17}18defer conn.Close()19c := pb.NewGreeterClient(conn)20ctx, cancel := context.WithTimeout(context.Background(), time.Second)21defer cancel()22r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})23if err != nil {24 log.Fatalf("could not greet: %v", err)25}26log.Printf("Greeting: %s", r.Message)

Full Screen

Full Screen

New

Using AI Code Generation

copy

Full Screen

1import (2const (3type server struct {4}5func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {6 return &pb.HelloReply{Message: "Hello " + in.Name}, nil7}8func main() {9 lis, err := net.Listen("tcp", port)10 if err != nil {11 log.Fatalf("failed to listen: %v", err)12 }13 s := grpc.NewServer()14 pb.RegisterGreeterServer(s, &server{})15 if err := s.Serve(lis); err != nil {16 log.Fatalf("failed to serve: %v", err)17 }18}19import (20const (21func main() {22 conn, err := grpc.Dial(address, grpc.WithInsecure(), grpc.WithBlock())23 if err != nil {24 log.Fatalf("did not connect: %v", err)25 }26 defer conn.Close()27 c := pb.NewGreeterClient(conn)28 if len(os.Args) > 1 {29 }30 r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})31 if err != nil {32 log.Fatalf("could not greet: %v", err)33 }34 log.Printf("Greeting: %s", r.Message)35}36import (37const (

Full Screen

Full Screen

New

Using AI Code Generation

copy

Full Screen

1func main() {2 conn, err := grpc.Dial("localhost:8080", grpc.WithInsecure())3 if err != nil {4 log.Fatalf("could not connect: %v", err)5 }6 defer conn.Close()7 c := greetpb.NewGreetServiceClient(conn)8 fmt.Printf("Created client: %f", c)9}10func NewGreetServiceClient(cc *grpc.ClientConn) GreetServiceClient {11 return &greetServiceClient{cc}12}13func NewGreetServiceClient(cc *grpc.ClientConn) GreetServiceClient {14 return &greetServiceClient{cc}15}16func NewGreetServiceClient(cc *grpc.ClientConn) GreetServiceClient {17 return &greetServiceClient{cc}18}19func NewGreetServiceClient(cc *grpc.ClientConn) GreetServiceClient {20 return &greetServiceClient{cc}21}22func NewGreetServiceClient(cc *grpc.ClientConn) GreetServiceClient {23 return &greetServiceClient{cc}24}25func NewGreetServiceClient(cc *grpc.ClientConn) GreetServiceClient {26 return &greetServiceClient{cc}27}28func NewGreetServiceClient(cc *grpc.ClientConn) GreetServiceClient {29 return &greetServiceClient{cc}30}31func NewGreetServiceClient(cc *grpc.ClientConn) GreetServiceClient {32 return &greetServiceClient{cc}33}34func NewGreetServiceClient(cc *grpc.ClientConn) GreetServiceClient {35 return &greetServiceClient{cc

Full Screen

Full Screen

New

Using AI Code Generation

copy

Full Screen

1func main() {2 conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())3 if err != nil {4 log.Fatalf("did not connect: %v", err)5 }6 defer conn.Close()7 c := pb.NewGreeterClient(conn)8 r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})9 if err != nil {10 log.Fatalf("could not greet: %v", err)11 }12 log.Printf("Greeting: %s", r.Message)13}14func main() {15 conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())16 if err != nil {17 log.Fatalf("did not connect: %v", err)18 }19 defer conn.Close()20 c := pb.NewGreeterClient(conn)21 r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})22 if err != nil {23 log.Fatalf("could not greet: %v", err)24 }25 log.Printf("Greeting: %s", r.Message)26}27func main() {28 conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())29 if err != nil {30 log.Fatalf("did not connect: %v", err)31 }32 defer conn.Close()33 c := pb.NewGreeterClient(conn)34 r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})35 if err != nil {36 log.Fatalf("could not greet: %v", err)37 }38 log.Printf("Greeting: %s", r.Message)39}40func main() {41 conn, err := grpc.Dial("localhost:50051", grpc.WithIn

Full Screen

Full Screen

New

Using AI Code Generation

copy

Full Screen

1import (2type server struct{}3func (*server) Greet(ctx context.Context, req *greetpb.GreetRequest) (*greetpb.GreetResponse, error) {4 fmt.Printf("Greet function was invoked with %v5 firstName := req.GetGreeting().GetFirstName()6 res := &greetpb.GreetResponse{7 }8}9func main() {10 fmt.Println("Hello World")11 lis, err := net.Listen("tcp", "

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful