使用包文件将数据写入云存储?

huangapple go评论91阅读模式
英文:

Use package file to write to Cloud Storage?

问题

Golang提供了file package来访问云存储。

该包的Create函数需要io.WriteCloser接口。然而,我没有找到任何一个示例或文档来展示如何将文件实际保存到云存储。

有人可以帮忙吗?是否有更高级别的io.WriteCloser实现,可以让我们将文件存储在云存储中?有任何示例代码吗?

我们已经尝试过自己在Google上搜索,但没有找到任何内容,现在希望社区能够提供帮助。

英文:

Golang provides the file package to access Cloud Storage.

The package's Create function requires the io.WriteCloser interface. However, I have not found a single sample or documentation showing how to actually save a file to Cloud Storage.

Can anybody help? Is there a higher level implementation of io.WriteCloser that would allow us to store files in Cloud Storage? Any sample code?

We've obviously tried to Google it ourselves but found nothing and now hope for the community to help.

答案1

得分: 2

也许在文档中行为定义不清晰。

如果你查看代码:https://code.google.com/p/appengine-go/source/browse/appengine/file/write.go#133

在每次调用Write时,数据都会被发送到云端(第139行)。所以你不需要保存。(当你完成后应该关闭文件。)

无论如何,我对你的措辞感到困惑:“包的Create函数要求io.WriteCloser接口。”这是不正确的。包的Create函数返回一个io.WriteCloser,也就是一个你可以写入和关闭的东西。

yourFile, _, err := Create(ctx, "filename", nil)
// 检查 err != nil

defer func() {
    err := yourFile.Close()
    // 检查 err != nil
}()

yourFile.Write([]byte("这将立即发送到文件中。"))
fmt.Fprintln(yourFile, "这也是。")
io.Copy(yourFile, someReader)

这就是Go中接口的工作方式。它们只提供一组你可以调用的方法,将实际的实现隐藏起来;当你只依赖于特定的接口而不是特定的实现时,你可以以多种方式组合,就像fmt.Fprintlnio.Copy一样。

英文:

It's perhaps true than the behavior is not well defined in the documentation.

If you check the code: https://code.google.com/p/appengine-go/source/browse/appengine/file/write.go#133

In each call to Write the data is sent to the cloud (line 139). So you don't need to save. (You should close the file when you're done, through.)

Anyway, I'm confused with your wording: "The package's Create function requires the io.WriteCloser interface." That's not true. The package's Create functions returns a io.WriteCloser, that is, a thingy you can write to and close.

yourFile, _, err := Create(ctx, "filename", nil)
// Check err != nil here.

defer func() {
    err := yourFile.Close()
    // Check err != nil here.
}()

yourFile.Write([]byte("This will be sent to the file immediately."))
fmt.Fprintln(yourFile, "This too.")
io.Copy(yourFile, someReader)

This is how interfaces work in Go. They just provide you with a set of methods you can call, hiding the actual implementation from you; and, when you just depend on a particular interface instead of a particular implementation, you can combine in multiple ways, as fmt.Fprintln and io.Copy do.

huangapple
  • 本文由 发表于 2014年3月12日 20:37:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/22351780.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定