Подключение к GRPC server’у

Simple server

Создание сервера

type server struct {
	productMap map[string]*pb.Product
	ecommerce.UnimplementedProductInfoServer
}
 
const (
	port = ":50051"
)
 
func main() {
	lis, err := net.Listen("tcp", port)
	if err != nil {
		log.Fatal(err)
	}
	s := grpc.NewServer()
	ecommerce.RegisterProductInfoServer(s, &server{})
	log.Printf("Starting gRPC listener on port %s", port)
	if err := s.Serve(lis); err != nil {
		log.Fatalf("failed serve: %v", err)
	}
}

Создание клиента

package main
 
import (
	"context"
	"log"
	"time"
 
	"client/ecommerce"
 
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)
 
const (
	address = "localhost:50051"
)
 
func main() {
	conn, err := grpc.Dial(address, grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close()
 
	c := ecommerce.NewProductInfoClient(conn)
	name := "Apple iPhone 11"
	description := "Some phone"
 
	ctx, cancel := context.WithTimeout(context.Background(), time.Second)
	defer cancel()
	r, err := c.AddProduct(ctx, &ecommerce.Product{Name: name, Description: description})
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Product ID: %s added successfully", r.Value)
 
	product, err := c.GetProduct(ctx, &ecommerce.ProductID{Value: r.Value})
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Product: %s", product.String())
}

Tinkoff OpenAPI

conn, err := grpc.Dial("invest-public-api.tinkoff.ru:443",
	grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{})),
	grpc.WithPerRPCCredentials(oauth.TokenSource{
		TokenSource: oauth2.StaticTokenSource(&oauth2.Token{
			AccessToken: "token",
			}),
		}))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	defer conn.Close()

После чего объект conn можно передавать в функции создание новых сервисов.