go - 在 Google Cloud Platform 中使用 Buckets 和 Golang

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

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

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

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

是否有 Golang 的等价物?

最佳答案

正如 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 文件的基本步骤很有用。

关于go - 在 Google Cloud Platform 中使用 Buckets 和 Golang,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51754512/

相关文章:

google-cloud-platform - Google Cloud Identity Aware Proxy (IAP) 强制注销

javascript - 如何使用客户端库从 Node js 将文件夹上传到 GCS

java - 将不同语言的服务部署到同一个应用程序 [Google App Engine]

node.js - 是否可以获得存储在 Google Cloud Storage 上的图像的调整大小版本?

string - 如何获取字符串中的字符数

mongodb - 如何使用官方Go驱动程序在MongoDB中持久存储文件(小于16MB)

visual-studio-code - 将Visual Studio Code集成到Google Cloud中

python - 将 TensorFlow Checkpoint 部署到 Google Cloud Platform

去反射 panic : Call using interface{} as type

recursion - 我如何阻止(和加入)由未知数量的 goroutines 提供的 channel ?