Como ler e gravar no Cloud Storage
Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Neste documento, descrevemos como armazenar e recuperar dados usando a
biblioteca de cliente do Cloud Storage. O ideal é que você já tenha concluído as tarefas descritas na seção
Como configurar o Google Cloud Storage
para ativar um bucket do Cloud Storage e fazer o download das bibliotecas de cliente. Também é necessário que você saiba criar um aplicativo do App Engine.
Para ver outras amostras de código, consulte Bibliotecas de cliente do Cloud Storage
Importações obrigatórias
As importações necessárias no arquivo para o App Engine e para o Cloud Storage são:
google.golang.org/appengine
,
google.golang.org/appengine/file
cloud.google.com/go/storage
como mostrado no seguinte snippet:
Como especificar o bucket do Cloud Storage
Antes de executar qualquer operação do Cloud Storage, é necessário fornecer o
nome do bucket. A maneira mais fácil de fazer isso é usar o bucket padrão para o
projeto, que pode ser obtido no contexto do App Engine, conforme mostrado neste
snippet:
Como gravar no Cloud Storage
Para gravar um arquivo no Cloud Storage:
Quando o arquivo é criado, a amostra especifica os cabeçalhos do Cloud Storage (x-goog-meta-foo
e x-goog-meta-bar
). Esse código opcional apresenta a noção
de uso de cabeçalhos do Cloud Storage, que você
pode aplicar para:
- afetar o comportamento da solicitação;
- especificar o acesso ao arquivo no bucket diferente dos padrões (veja x-goog-acl);
- gravar metadados de arquivo.
Os cabeçalhos x-goog-meta-*
mostrados acima são metadados de arquivos personalizados configuráveis e sempre são retornados com o arquivo. Observe que o espaço disponível para cabeçalhos personalizados e os dados deles é limitado a alguns kilobytes. Por isso, use-os com cuidado.
Como o código de amostra não define x-goog-acl
, a ACL padrão do Cloud Storage de leitura pública é aplicada ao objeto quando ele é gravado no bucket.
Por fim, observe a chamada para usar Close()
no arquivo depois de concluir a gravação. Se
não usá-lo, o arquivo não será gravado no Cloud Storage. Depois de
chamar Close()
, não será possível anexar ao arquivo.
Como fazer a leitura do Cloud Storage
Para ler um arquivo do Cloud Storage:
Como listar conteúdo do bucket
Com este código de amostra, é possível listar o conteúdo do bucket:
Como excluir arquivos no Cloud Storage
O código abaixo demonstra como excluir um arquivo do Cloud Storage usando o método ObjectHandle.delete()
.
Este exemplo limpa os arquivos que foram gravados no bucket na seção Como gravar no Cloud Storage.
A seguir
Exceto em caso de indicação contrária, o conteúdo desta página é licenciado de acordo com a Licença de atribuição 4.0 do Creative Commons, e as amostras de código são licenciadas de acordo com a Licença Apache 2.0. Para mais detalhes, consulte as políticas do site do Google Developers. Java é uma marca registrada da Oracle e/ou afiliadas.
Última atualização 2025-09-04 UTC.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-09-04 UTC."],[[["\u003cp\u003eThis guide details how to interact with Cloud Storage for data storage and retrieval using the client library, assuming prerequisite setup tasks are completed.\u003c/p\u003e\n"],["\u003cp\u003eThe document provides code snippets for essential operations including writing to Cloud Storage, which demonstrates the use of headers for request behavior, access control, and metadata.\u003c/p\u003e\n"],["\u003cp\u003eInstructions are provided on reading data back from Cloud Storage, including how to access files using their name, and the necessary steps to process the retrieved content.\u003c/p\u003e\n"],["\u003cp\u003eThe content also covers how to list the contents of a specified Cloud Storage bucket and how to properly delete files from it.\u003c/p\u003e\n"],["\u003cp\u003eThe guide explains the required imports, such as \u003ccode\u003egoogle.golang.org/appengine\u003c/code\u003e, \u003ccode\u003egoogle.golang.org/appengine/file\u003c/code\u003e, and \u003ccode\u003ecloud.google.com/go/storage\u003c/code\u003e, necessary to utilize Cloud Storage within an App Engine application.\u003c/p\u003e\n"]]],[],null,["# Reading and writing to Cloud Storage\n\nThis document describes how to store and retrieve data using the\nCloud Storage client library. It assumes that you completed the tasks\ndescribed in [Setting up for Cloud Storage](/appengine/docs/legacy/standard/go111/googlecloudstorageclient/setting-up-cloud-storage) to activate a Cloud Storage\nbucket and download the client libraries. It also assumes that you know how to\nbuild an App Engine application.\n| This API is supported for first-generation runtimes and can be used when [upgrading to corresponding second-generation runtimes](/appengine/docs/standard/\n| go\n| /services/access). If you are updating to the App Engine Go 1.12+ runtime, refer to the [migration guide](/appengine/migration-center/standard/migrate-to-second-gen/go-differences) to learn about your migration options for legacy bundled services.\n\nFor additional code samples, see [Cloud Storage client libraries](/storage/docs/reference/libraries#client-libraries-usage-python)\n\nRequired imports\n----------------\n\nThe imports in the file required for App Engine and for Cloud Storage are:\n\n- `google.golang.org/appengine`,\n- `google.golang.org/appengine/file`\n- `cloud.google.com/go/storage`\n\nas shown in the following snippet: \n\n import (\n \t\"bytes\"\n \t\"fmt\"\n \t\"io\"\n \t\"io/ioutil\"\n \t\"net/http\"\n \t\"strings\"\n\n \t\"cloud.google.com/go/storage\"\n \t\"golang.org/x/net/context\"\n \t\"google.golang.org/api/iterator\"\n \t\"google.golang.org/appengine\"\n \t\"google.golang.org/appengine/file\"\n \t\"google.golang.org/appengine/log\"\n )\n\nSpecifying the Cloud Storage bucket\n-----------------------------------\n\nBefore you can execute any Cloud Storage operation, you must supply the\nbucket name. The easiest way to do this is to use the default bucket for your\nproject, which can be obtained from the App Engine context, as shown in\nthis snippet: \n\n // Use `dev_appserver.py --default_gcs_bucket_name GCS_BUCKET_NAME`\n // when running locally.\n bucket, err := file.DefaultBucketName(ctx)\n if err != nil {\n \tlog.Errorf(ctx, \"failed to get default GCS bucket name: %v\", err)\n }\n\nWriting to Cloud Storage\n------------------------\n\nTo write a file to Cloud Storage: \n\n // createFile creates a file in Google Cloud Storage.\n func (d *demo) createFile(fileName string) {\n \tfmt.Fprintf(d.w, \"Creating file /%v/%v\\n\", d.bucketName, fileName)\n\n \twc := d.bucket.Object(fileName).NewWriter(d.ctx)\n \twc.ContentType = \"text/plain\"\n \twc.Metadata = map[string]string{\n \t\t\"x-goog-meta-foo\": \"foo\",\n \t\t\"x-goog-meta-bar\": \"bar\",\n \t}\n \td.cleanUp = append(d.cleanUp, fileName)\n\n \tif _, err := wc.Write([]byte(\"abcde\\n\")); err != nil {\n \t\td.errorf(\"createFile: unable to write data to bucket %q, file %q: %v\", d.bucketName, fileName, err)\n \t\treturn\n \t}\n \tif _, err := wc.Write([]byte(strings.Repeat(\"f\", 1024*4) + \"\\n\")); err != nil {\n \t\td.errorf(\"createFile: unable to write data to bucket %q, file %q: %v\", d.bucketName, fileName, err)\n \t\treturn\n \t}\n \tif err := wc.Close(); err != nil {\n \t\td.errorf(\"createFile: unable to close bucket %q, file %q: %v\", d.bucketName, fileName, err)\n \t\treturn\n \t}\n }\n\nWhen the file is created, the sample specifies Cloud Storage headers (`x-goog-meta-foo` and `x-goog-meta-bar`). This optional code introduces the notion\nof using [Cloud Storage headers](/storage/docs/reference-headers), which you\ncan apply to:\n\n- Affect request behavior\n- Specify access to the file in the bucket different from the defaults (see [x-goog-acl](/storage/docs/reference-headers#xgoogacl))\n- Write [file metadata](/storage/docs/metadata).\n\nThe [`x-goog-meta-*`](/storage/docs/reference-headers#xgoogmeta) headers shown\nabove are custom file metadata that you can set; these headers are always\nreturned with the file. Note that the space available for custom headers and\ntheir data is limited to a few kilobytes, so use these carefully.\n\nBecause the code sample doesn't set `x-goog-acl`, the default\nCloud Storage ACL of [public read](/storage/docs/access-control)\nis applied to the object when it is written to the bucket.\n\nFinally, notice the call to `Close()` the file after you finish the write. If\nyou don't do this, the file is not written to Cloud Storage. Be aware\nthat after you call `Close()`, you cannot append to the file.\n\nReading from Cloud Storage\n--------------------------\n\nTo read a file from Cloud Storage:\n\n\u003cbr /\u003e\n\n // readFile reads the named file in Google Cloud Storage.\n func (d *demo) readFile(fileName string) {\n \tio.WriteString(d.w, \"\\nAbbreviated file content (first line and last 1K):\\n\")\n\n \trc, err := d.bucket.Object(fileName).NewReader(d.ctx)\n \tif err != nil {\n \t\td.errorf(\"readFile: unable to open file from bucket %q, file %q: %v\", d.bucketName, fileName, err)\n \t\treturn\n \t}\n \tdefer rc.Close()\n \tslurp, err := ioutil.ReadAll(rc)\n \tif err != nil {\n \t\td.errorf(\"readFile: unable to read data from bucket %q, file %q: %v\", d.bucketName, fileName, err)\n \t\treturn\n \t}\n\n \tfmt.Fprintf(d.w, \"%s\\n\", bytes.SplitN(slurp, []byte(\"\\n\"), 2)[0])\n \tif len(slurp) \u003e 1024 {\n \t\tfmt.Fprintf(d.w, \"...%s\\n\", slurp[len(slurp)-1024:])\n \t} else {\n \t\tfmt.Fprintf(d.w, \"%s\\n\", slurp)\n \t}\n }\n\nListing bucket contents\n-----------------------\n\nThis sample code shows how to list the contents of the bucket: \n\n // listBucket lists the contents of a bucket in Google Cloud Storage.\n func (d *demo) listBucket() {\n \tio.WriteString(d.w, \"\\nListbucket result:\\n\")\n\n \tquery := &storage.Query{Prefix: \"foo\"}\n \tit := d.bucket.Objects(d.ctx, query)\n \tfor {\n \t\tobj, err := it.Next()\n \t\tif err == iterator.Done {\n \t\t\tbreak\n \t\t}\n \t\tif err != nil {\n \t\t\td.errorf(\"listBucket: unable to list bucket %q: %v\", d.bucketName, err)\n \t\t\treturn\n \t\t}\n \t\td.dumpStats(obj)\n \t}\n }\n\nDeleting files in Cloud Storage\n-------------------------------\n\nThe code below demonstrates how to delete a file from Cloud Storage using the\n[`ObjectHandle.delete()`](https://godoc.org/cloud.google.com/go/storage#ObjectHandle.Delete)\nmethod. \n\n\n // deleteFiles deletes all the temporary files from a bucket created by this demo.\n func (d *demo) deleteFiles() {\n \tio.WriteString(d.w, \"\\nDeleting files...\\n\")\n \tfor _, v := range d.cleanUp {\n \t\tfmt.Fprintf(d.w, \"Deleting file %v\\n\", v)\n \t\tif err := d.bucket.Object(v).Delete(d.ctx); err != nil {\n \t\t\td.errorf(\"deleteFiles: unable to delete bucket %q, file %q: %v\", d.bucketName, v, err)\n \t\t\treturn\n \t\t}\n \t}\n }\n\nThis example cleans up the files that were written to the bucket in the\n[Writing to Cloud Storage](#writing_to_cloud_storage) section.\n\nWhat's next\n-----------\n\n- Visit the [API Reference documentation](https://godoc.org/cloud.google.com/go/storage).\n- See the [Cloud Storage documentation](/storage/docs) for more guides and tutorials."]]