![](/img/trans.png)
[英]Unable to access Google Cloud Storage from Google Kubernetes Engine using default service account and google cloud libraries
[英]Unable to create an interface to mock Google Cloud Storage
我正在嘗試創建一個接口來抽象谷歌雲存儲。
我有以下接口:
type Client interface {
Bucket(name string) *BucketHandle
Close() error
}
type BucketHandle interface {
Create(context.Context, string, *storage.BucketAttrs) error
Delete(context.Context) error
Attrs(context.Context) (*storage.BucketAttrs, error)
}
還有我的代碼
type Bucket struct {
handler Client
}
func NewStorage(ctx context.Context, bucketName string) Bucket {
var bkt Bucket
client, err := storage.NewClient(ctx)
if err != nil {
return Bucket{}
}
bkt.handler = client
return bkt
}
我收到以下錯誤: cannot use client (variable of type *storage.Client) as Client value in assignment: wrong type for method Bucket
goland 顯示以下內容
Cannot use 'client' (type *Client) as type Client Type does not implement 'Client' need method: Bucket(name string) *BucketHandle have method: Bucket(name string) *BucketHandle
我不知道為什么類型不一樣。
不能使用“客戶端”(類型 *Client),因為客戶端類型未實現“客戶端”需要方法:Bucket(名稱字符串)*BucketHandle 具有方法:Bucket(名稱字符串)*BucketHandle
這個錯誤沒有錯。 它看起來具有誤導性的原因是因為您創建了一個接口,其名稱與庫中的具體結構完全相同,即BucketHandle
仔細注意這兩個函數的返回類型之間的區別:
// In your interface, the return type is an interface that you created
Bucket(name string) *BucketHandle
// In the library, the return type is a concrete struct that exists in that lib
Bucket(name string) *BucketHandle
您需要將Client
界面修改為以下內容,它應該可以正常工作。
type Client interface {
Bucket(name string) *storage.BucketHandle
Close() error
}
storage.NewClient(ctx)
返回 *storage.Client。 而你試圖分配給客戶端,你的客戶端應該實現 storage.Client 實現的方法
客戶端界面應該是
type Client interface {
Close() error
ServiceAccount(ctx context.Context, projectID string) (string, error)
}
和桶可以
type Bucket struct {
handler Client
}
在這里查看https://github.com/googleapis/google-cloud-go/blob/master/storage/storage.go#L101
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.