Go 1.11은 지원이 종료되었으며 2026년 1월 31일에
지원 중단됩니다. 지원 중단 후에는 조직에서 이전에 조직 정책을 사용하여 레거시 런타임의 배포를 다시 사용 설정한 경우에도 Go 1.11 애플리케이션을 배포할 수 없습니다. 기존 Go 1.11 애플리케이션은
지원 중단 날짜 이후에도 계속 실행되고 트래픽을 수신합니다.
지원되는 최신 Go 버전으로 마이그레이션하는 것이 좋습니다.
Cloud Storage 읽기 및 쓰기
컬렉션을 사용해 정리하기
내 환경설정을 기준으로 콘텐츠를 저장하고 분류하세요.
이 문서에서는 Cloud Storage 클라이언트 라이브러리를 사용하여 데이터를 저장 및 검색하는 방법을 설명합니다. 여기서는 Cloud Storage 설정에 설명된 작업을 완료하여 Cloud Storage 버킷을 활성화하고 클라이언트 라이브러리를 다운로드했다고 가정합니다. 또한 App Engine 애플리케이션을 빌드하는 방법을 알고 있다고 가정합니다.
추가 코드 샘플은 Cloud Storage 클라이언트 라이브러리를 참조하세요.
필수 가져오기
App Engine 및 Cloud Storage에 필요한 파일의 가져오기 항목은 다음과 같습니다.
google.golang.org/appengine
,
google.golang.org/appengine/file
cloud.google.com/go/storage
위 항목의 예시는 다음 스니펫에 나와 있습니다.
Cloud Storage 버킷 지정
Cloud Storage 작업을 실행하려면 먼저 버킷 이름을 제공해야 합니다. 가장 쉬운 방법은 프로젝트의 기본 버킷을 사용하는 것이며, 다음 스니펫에 표시된 대로 App Engine 컨텍스트에서 획득할 수 있습니다.
Cloud Storage에 쓰기
Cloud Storage에 파일을 쓰려면 다음을 실행합니다.
파일이 생성되면 샘플은 Cloud Storage 헤더(x-goog-meta-foo
및 x-goog-meta-bar
)를 지정합니다. 이 선택적 코드는 다음에 적용 가능한 Cloud Storage 헤더 사용에 대한 개념을 소개합니다.
위의 x-goog-meta-*
헤더는 개발자가 설정할 수 있는 커스텀 파일 메타데이터이며 항상 파일과 함께 반환됩니다. 커스텀 헤더 및 이 헤더 데이터에 사용할 수 있는 공간은 몇 KB로 제한되므로 주의해서 사용해야 합니다.
코드 샘플에서는 x-goog-acl
을 설정하지 않으므로 객체가 버킷에 기록될 때 기본 Cloud Storage ACL의 공개 읽기가 객체에 적용됩니다.
마지막으로 쓰기를 마친 후에 파일을 Close()
하기 위한 호출을 확인합니다. 그렇지 않으면 파일이 Cloud Storage에 기록되지 않습니다. Close()
를 호출한 후에는 파일에 아무 것도 추가할 수 없습니다.
Cloud Storage에서 읽기
Cloud Storage에서 파일을 읽으려면 다음 안내를 따르세요.
버킷 콘텐츠 나열
이 샘플 코드는 버킷 콘텐츠를 나열하는 방법을 보여줍니다.
Cloud Storage의 파일 삭제
아래 코드는 ObjectHandle.delete()
메서드를 사용하여 Cloud Storage에서 파일을 삭제하는 방법을 보여줍니다.
이 예는 Cloud Storage에 쓰기 섹션의 버킷에 기록된 파일을 정리합니다.
다음 단계
달리 명시되지 않는 한 이 페이지의 콘텐츠에는 Creative Commons Attribution 4.0 라이선스에 따라 라이선스가 부여되며, 코드 샘플에는 Apache 2.0 라이선스에 따라 라이선스가 부여됩니다. 자세한 내용은 Google Developers 사이트 정책을 참조하세요. 자바는 Oracle 및/또는 Oracle 계열사의 등록 상표입니다.
최종 업데이트: 2025-09-04(UTC)
[[["이해하기 쉬움","easyToUnderstand","thumb-up"],["문제가 해결됨","solvedMyProblem","thumb-up"],["기타","otherUp","thumb-up"]],[["이해하기 어려움","hardToUnderstand","thumb-down"],["잘못된 정보 또는 샘플 코드","incorrectInformationOrSampleCode","thumb-down"],["필요한 정보/샘플이 없음","missingTheInformationSamplesINeed","thumb-down"],["번역 문제","translationIssue","thumb-down"],["기타","otherDown","thumb-down"]],["최종 업데이트: 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."]]