我正在尝试使用与gcloudCLI 相同的凭据向 GCP PubSub 发布消息,但没有取得很大成功。
我可以通过以下方式确认我可以发布到某个主题
gcloud pubsub topics publish myTopic --project "myProject" --message "Hello World!"
但是,当我使用下面的代码尝试使用与 gcloud 完全相同的凭据时
creds, err := google.FindDefaultCredentials(context.Background())
if err != nil {
panic(fmt.Sprintf("Unable to retrieve default credentials: %v", err))
}
client, err := pubsub.NewClient(ctx, "myproject", option.WithCredentials(creds))
if err != nil {
panic(fmt.Sprintf("unable to create GCP storage client: %v", err))
}
topic := client.Topic("myTopic")
r := topic.Publish(ctx, &pubsub.Message{
Data: []byte("Hello World!"),
})
_, err = r.Get(ctx)
if err != nil {
panic(fmt.Sprintf("failed to publish message: %v", err))
}
我收到以下错误消息
panic: failed to publish message: rpc error: code = Unauthenticated desc = transport: oauth2: cannot fetch token: 400 Bad Request
Response: {
"error": "invalid_grant",
"error_description": "Bad Request"
}
我还尝试直接加载 json 文件,以确保它没有在某处获取其他默认凭据,但出现相同的错误。
如何使用与 gcloud CLI 相同的凭据发布到我有权访问的 pubsub 主题?
子衿沉夜
侃侃尔雅
芜湖不芜
相关分类