【问题标题】:Using Buckets in Google Cloud Platform with Golang通过 Golang 在 Google Cloud Platform 中使用存储桶
【发布时间】:2018-12-06 10:09:02
【问题描述】:

我正在尝试在 Google Cloud Platform 上托管一个 Go 应用程序,我需要它来执行一些文件写入。 GCP 不允许您直接在 App Engine 中进行文件写入,但需要您使用存储桶。

从他们的文档中,您可以像这样访问 PHP 中的存储桶

$default_bucket = CloudStorageTools::getDefaultGoogleStorageBucketName();
$fp = fopen("gs://${default_bucket}/hello_default_stream.txt", 'w');
fwrite($fp, $newFileContent);
fclose($fp);

有没有对应的 Golang 语言?

【问题讨论】:

标签: go google-cloud-platform google-cloud-storage


【解决方案1】:

正如 Daz 在第一条评论中所分享的,the docs for Standard 上有关于如何执行此操作的介绍。这使用了cloud.google.com/go/storage 库,尽管您也可以使用被取代的google.golang.org/appengine/blobstore(如docs 中所述)。

使用这些文档,您可以简化它们,直到获得以下代码(经过测试并按预期工作):

package minimal_gcs

import (
        s "cloud.google.com/go/storage"
        a "google.golang.org/appengine"
        h "net/http"
)

func init() {
        h.HandleFunc("/", func(w h.ResponseWriter, r *h.Request) {
                cx := a.NewContext(r)
                c, _ := s.NewClient(cx)
                wr := c.Bucket("<bucket_id>").Object("<object_id>").NewWriter(cx)
                _, _ = wr.Write([]byte("Hello World!!1"))
                _ = wr.Close()
        })
}

请注意,这是非常糟糕的代码(没有错误处理,...),但我认为展示使用 Go 在 GAE 标准中处理 GCS 文件的基本步骤很有用。

【讨论】:

    猜你喜欢
    • 2017-02-02
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    • 2019-02-23
    • 2020-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多