go - 使用 golangGoogle Cloud Storage 认证

标签 go google-cloud-storage

我有一个在服务器上运行的 go 应用程序。该应用程序需要访问权限才能将图像保存到 Google Cloud Storage。来自Google Cloud Storage authentication文档可以看到如何创建 PKCS12 key 。

我正在使用

import(
storage "google.golang.org/api/storage/v1"
)

如何在应用程序中将此 key 与 golang“存储”客户端一起使用?

问候

最佳答案

func ExampleJWTConfigFromJSON() {
    // Your credentials should be obtained from the Google
    // Developer Console (https://console.developers.google.com).
    // Navigate to your project, then see the "Credentials" page
    // under "APIs & Auth".
    // To create a service account client, click "Create new Client ID",
    // select "Service Account", and click "Create Client ID". A JSON
    // key file will then be downloaded to your computer.
    data, err := ioutil.ReadFile("/path/to/your-project-key.json")
    if err != nil {
        log.Fatal(err)
    }
    conf, err := google.JWTConfigFromJSON(data, "https://www.googleapis.com/auth/bigquery")
    if err != nil {
        log.Fatal(err)
    }
    // Initiate an http.Client. The following GET request will be
    // authorized and authenticated on the behalf of
    // your service account.
    client := conf.Client(oauth2.NoContext)
    client.Get("...")
}

--

func JWTConfigFromJSON(jsonKey []byte, scope ...string) (*jwt.Config, error)
{
    var key struct {
        Email      string `json:"client_email"`
        PrivateKey string `json:"private_key"`
    }
    if err := json.Unmarshal(jsonKey, &key); err != nil {
        return nil, err
    }
    return &jwt.Config{
        Email:      key.Email,
        PrivateKey: []byte(key.PrivateKey),
        Scopes:     scope,
        TokenURL:   JWTTokenURL,
    }, nil
}

详情:

https://github.com/golang/oauth2/blob/master/google/example_test.go https://github.com/golang/oauth2/blob/master/google/google.go

希望这会有所帮助。

关于go - 使用 golangGoogle Cloud Storage 认证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33189486/

相关文章:

google-cloud-storage - 如何列出最近添加到 GCS 存储桶的文件

c - inb() 和 outb() Linux 系统调用的包装器

date - 时间数据的RFC3339格式无效

python - 如何将 OAuth2Decorator 与 Google Cloud Storage 结合使用?

iOS 上传文件到谷歌云存储 - 获取 401 : 'Login Required'

bash - gsutil:参数列表太长

loops - 循环中是否满足条件

go - Golang 中的不可变结构

go - go exec 对不同 shell 命令的不同行为

node.js - 如何使用multer和NodeJS将图像上传到GCS存储桶?