
# Go {/* #go */}

首先阅读 [gRPC 指南](/docs/zh/api/grpc)，获取平台 API 令牌并下载 `platform.proto`。安装 `protoc`、Go 和 [Go protobuf 插件](https://grpc.io/docs/languages/go/quickstart/)。

创建模块并安装生成器：

```bash
go mod init example.com/reconstruct-client
```

```bash
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
```

```bash
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
```

使 `protoc` 能够访问这些插件，然后生成客户端。若使用其他模块路径，请同时替换模块和命令中的 `example.com/reconstruct-client`：

```bash
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`：

```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`。
