Go 1.11 telah mencapai akhir dukungan
dan akan
dihentikan penggunaannya
pada 31 Januari 2026. Setelah penghentian penggunaan, Anda tidak akan dapat men-deploy aplikasi Go 1.11, meskipun organisasi Anda sebelumnya menggunakan kebijakan organisasi untuk mengaktifkan kembali deployment runtime lama. Aplikasi Go 1.11 yang ada akan terus berjalan dan menerima traffic setelah
tanggal penghentiannya. Sebaiknya Anda
bermigrasi ke Go versi terbaru yang didukung.
Membaca dan menulis ke Cloud Storage
Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Dokumen ini menjelaskan cara menyimpan dan mengambil data menggunakan library klien Cloud Storage. Anda dianggap telah menyelesaikan tugas yang dijelaskan dalam artikel Menyiapkan Cloud Storage untuk mengaktifkan bucket Cloud Storage dan mendownload library klien. Anda juga dianggap telah memahami cara
membuat aplikasi App Engine.
Untuk contoh kode tambahan, lihat Library klien Cloud Storage
Impor yang diperlukan
Impor file yang diperlukan untuk App Engine dan Cloud Storage adalah:
google.golang.org/appengine
,
google.golang.org/appengine/file
cloud.google.com/go/storage
seperti yang ditunjukkan dalam cuplikan berikut:
Menentukan bucket Cloud Storage
Sebelum dapat menjalankan operasi Cloud Storage, Anda harus memberikan nama bucket. Cara termudah untuk melakukannya adalah dengan menggunakan bucket default untuk project Anda, yang dapat diperoleh dari konteks App Engine, seperti yang ditunjukkan dalam cuplikan ini:
Menulis ke Cloud Storage
Untuk menulis file ke Cloud Storage:
Saat file dibuat, sampel akan menentukan header Cloud Storage (x-goog-meta-foo
dan x-goog-meta-bar
). Kode opsional ini memperkenalkan gagasan penggunaan header Cloud Storage, yang dapat Anda terapkan ke:
- Memengaruhi perilaku permintaan
- Tentukan akses ke file dalam bucket yang berbeda dengan setelan default-nya (lihat x-goog-acl)
- Tulis metadata file.
Header x-goog-meta-*
yang ditampilkan di atas adalah metadata file kustom yang dapat Anda tetapkan; header ini selalu
ditampilkan dengan file. Perhatikan bahwa ruang yang tersedia untuk header kustom dan datanya terbatas hingga beberapa kilobyte, jadi gunakan ruang penyimpanan ini dengan hati-hati.
Karena contoh kode tidak menetapkan x-goog-acl
, ACL Cloud Storage default dari pembacaan publik diterapkan ke objek saat ditulis ke bucket.
Terakhir, perhatikan panggilan ke Close()
file setelah Anda menyelesaikan penulisan. Jika Anda tidak melakukan hal ini, file tidak akan ditulis ke Cloud Storage. Perlu diketahui
bahwa setelah memanggil Close()
, Anda tidak dapat menambahkan ke file.
Membaca dari Cloud Storage
Untuk membaca file dari Cloud Storage:
Mencantumkan konten bucket
Kode contoh ini menunjukkan cara menampilkan daftar konten bucket:
Menghapus file di Cloud Storage
Kode di bawah ini menunjukkan cara menghapus file dari Cloud Storage menggunakan metode ObjectHandle.delete()
.
Contoh ini membersihkan file yang ditulis ke bucket di bagian Menulis ke Cloud Storage.
Langkah berikutnya
Kecuali dinyatakan lain, konten di halaman ini dilisensikan berdasarkan Lisensi Creative Commons Attribution 4.0, sedangkan contoh kode dilisensikan berdasarkan Lisensi Apache 2.0. Untuk mengetahui informasi selengkapnya, lihat Kebijakan Situs Google Developers. Java adalah merek dagang terdaftar dari Oracle dan/atau afiliasinya.
Terakhir diperbarui pada 2025-08-19 UTC.
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],["Terakhir diperbarui pada 2025-08-19 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."]]