Best Venom code snippet using grpc.New
main.go
Source:main.go
...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}...
server.go
Source:server.go
...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 {...
grpc_server.go
Source:grpc_server.go
...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}...
disneyland_server.go
Source:disneyland_server.go
...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 )...
New
Using AI Code Generation
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)16$ docker run --rm -it -v "$(pwd)":/go/src/app -w /go/src/app golang:1.9.2 go run 1.go17$ docker run --rm -it -v "$(pwd)":/go/src/app -w /go/src/app golang:1.9.2 go run 2.go
New
Using AI Code Generation
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 if len(os.Args) > 1 {9 }10 ctx, cancel := context.WithTimeout(context.Background(), time.Second)11 defer cancel()12 r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})13 if err != nil {14 log.Fatalf("could not greet: %v", err)15 }16 log.Printf("Greeting: %s", r.Message)17}
New
Using AI Code Generation
1conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())2if err != nil {3log.Fatalf("did not connect: %v", err)4}5defer conn.Close()6c := pb.NewGreeterClient(conn)7if len(os.Args) > 1 {8}9r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})10if err != nil {11log.Fatalf("could not greet: %v", err)12}13log.Printf("Greeting: %s", r.Message)14conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())15if err != nil {16log.Fatalf("did not connect: %v", err)17}18defer conn.Close()19c := pb.NewGreeterClient(conn)20if len(os.Args) > 1 {21}22r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})23if err != nil {24log.Fatalf("could not greet: %v", err)25}26log.Printf("Greeting: %s", r.Message)27conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())28if err != nil {29log.Fatalf("did not connect: %v", err)30}31defer conn.Close()32c := pb.NewGreeterClient(conn)33if len(os.Args) > 1 {34}35r, err := c.SayHello(context.Background(), &pb.HelloRequest{Name: name})36if err != nil {37log.Fatalf("could not greet: %v", err)38}39log.Printf("Greeting: %s", r.Message)40conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())41if err != nil {42log.Fatalf("did not connect: %v", err)43}44defer conn.Close()45c := pb.NewGreeterClient(conn)46if len(os.Args) > 1
New
Using AI Code Generation
1var conn, 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)7var conn, err = grpc.Dial("localhost:50051", grpc.WithInsecure())8if err != nil {9 log.Fatalf("did not connect: %v", err)10}11defer conn.Close()12c := pb.NewGreeterClient(conn)13var conn, err = grpc.Dial("localhost:50051", grpc.WithInsecure())14if err != nil {15 log.Fatalf("did not connect: %v", err)16}17defer conn.Close()18c := pb.NewGreeterClient(conn)19var conn, err = grpc.Dial("localhost:50051", grpc.WithInsecure())20if err != nil {21 log.Fatalf("did not connect: %v", err)22}23defer conn.Close()24c := pb.NewGreeterClient(conn)25var conn, err = grpc.Dial("localhost:50051", grpc.WithInsecure())26if err != nil {27 log.Fatalf("did not connect: %v", err)28}29defer conn.Close()30c := pb.NewGreeterClient(conn)31var conn, 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)37var conn, err = grpc.Dial("localhost:50051", grpc.WithInsecure())38if err != nil {39 log.Fatalf("did not connect: %v", err)40}41defer conn.Close()42c := pb.NewGreeterClient(conn)43var conn, err = grpc.Dial("localhost:50051", grpc.WithInsecure())44if err != nil {45 log.Fatalf("did not connect: %v", err)46}47defer conn.Close()48c := pb.NewGreeterClient(conn)49var conn, err = grpc.Dial("localhost:50051", grpc.WithInsecure())
New
Using AI Code Generation
1conn, err := grpc.New("localhost:50051")2conn, err := grpc.New("localhost:50051")3conn, err := grpc.New("localhost:50051")4conn, err := grpc.New("localhost:50051")5conn, err := grpc.New("localhost:50051")6conn, err := grpc.New("localhost:50051")7conn, err := grpc.New("localhost:50051")8conn, err := grpc.New("localhost:50051")9conn, err := grpc.New("localhost:50051")10conn, err := grpc.New("localhost:50051")11conn, err := grpc.New("localhost:50051")12conn, err := grpc.New("localhost:50051")13conn, err := grpc.New("localhost:50051")14conn, err := grpc.New("localhost:50051")15conn, err := grpc.New("localhost:50051")16conn, err := grpc.New("localhost:50051")17conn, err := grpc.New("localhost:50051")
New
Using AI Code Generation
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 ctx, cancel := context.WithTimeout(context.Background(), time.Second)31 defer cancel()32 r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})33 if err != nil {34 log.Fatalf("could not greet: %v",
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!