Go
Platform API 토큰을 만들고 platform.proto를 받으려면 gRPC 가이드부터 시작하세요. protoc, Go 및 Go protobuf 플러그인을 설치하세요.
모듈을 만들고 생성기를 설치하세요:
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
플러그인을 protoc에서 사용할 수 있게 한 다음 클라이언트를 생성하세요. 다른 모듈 경로를 쓰면 모듈과 명령 모두에서 example.com/reconstruct-client를 바꾸세요:
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 옆에 main.go로 저장하세요:
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와 go run .를 실행하세요. 생성되는 파일은 platformpb/platform.pb.go, platformpb/platform_grpc.pb.go입니다.