Ana içeriğe geç

Go

Platform API belirteci oluşturmak ve platform.proto indirmek için gRPC kılavuzuyla başlayın. protoc, Go ve Go protobuf eklentilerini kurun.

Bir modül oluşturup üreticileri kurun:

go mod init example.com/reconstruct-client
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

Eklentileri protoc için kullanılabilir hale getirin, ardından istemciyi oluşturun. Farklı modül yolu kullanıyorsanız hem modülde hem komutta example.com/reconstruct-client değerini değiştirin:

export PATH="$(go env GOPATH)/bin:$PATH"
mkdir -p platformpb
protoc -I. platform.proto \
--go_out=platformpb --go_opt=paths=source_relative \
--go_opt=Mplatform.proto=example.com/reconstruct-client/platformpb \
--go-grpc_out=platformpb --go-grpc_opt=paths=source_relative \
--go-grpc_opt=Mplatform.proto=example.com/reconstruct-client/platformpb

platform.proto dosyasının yanına main.go olarak kaydedin:

package main

import (
"context"
"fmt"
"log"
"os"
"time"

pb "example.com/reconstruct-client/platformpb"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
)

func main() {
token := os.Getenv("CR_RECONSTRUCT_API_TOKEN")
if token == "" { log.Fatal("set CR_RECONSTRUCT_API_TOKEN") }

conn, err := grpc.NewClient("reconstruct.dev:443",
grpc.WithTransportCredentials(credentials.NewClientTLSFromCert(nil, "")))
if err != nil { log.Fatal(err) }
defer conn.Close()

ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
ctx = metadata.AppendToOutgoingContext(ctx, "authorization", "Bearer "+token)
client := pb.NewPlatformServiceClient(conn)

page, err := client.ListCatalogs(ctx, &pb.ListCatalogsRequest{PageSize: 10})
if err != nil { log.Fatal(err) }
for _, catalog := range page.GetCatalogs() {
detail, err := client.GetCatalog(ctx, &pb.GetCatalogRequest{CatalogId: catalog.GetCatalogId()})
if err != nil { log.Fatal(err) }
fmt.Println(detail.GetCatalogId(), detail.GetDescription())
}
}

go mod tidy, ardından go run . çalıştırın. Oluşturulan dosyalar platformpb/platform.pb.go ve platformpb/platform_grpc.pb.go şeklindedir.