Cloud Storage 사용

Cloud Storage를 사용하여 영화, 이미지 또는 기타 정적 콘텐츠와 같은 파일을 저장하고 제공할 수 있습니다.

이 문서는 앱에서 Google Cloud 클라이언트 라이브러리를 사용하여 Cloud Storage에 데이터를 저장하고 검색하는 방법을 설명합니다.

시작하기 전에

  • App Engine의 Go용 'Hello, World!'의 안내에 따라 환경과 프로젝트를 설정하고 App Engine에서 Go 앱이 구조화되는 방식을 이해합니다. 이 문서에 설명된 샘플 애플리케이션을 실행할 때 필요하므로 프로젝트 ID를 기록해 둡니다.

  • 다음 명령어를 호출하여 애플리케이션용 Cloud Storage 버킷을 만듭니다.

    gsutil mb gs://[YOUR_BUCKET_NAME]
    
  • 공개 읽기 가능 버킷으로 만들어 파일을 제공할 수 있도록 합니다.

    gsutil defacl set public-read gs://[YOUR_BUCKET_NAME]
    

샘플 다운로드

저장소를 복제하려면 다음을 사용하세요.

go get -d -v github.com/GoogleCloudPlatform/golang-samples/storage
cd $GOPATH/src/github.com/GoogleCloudPlatform/golang-samples/appengine_flexible/storage

프로젝트 구성 수정 및 종속 항목 설치

app.yaml에서 GCLOUD_STORAGE_BUCKET을 설정합니다. 이 값은 이전에 만든 Cloud Storage 버킷의 이름입니다.

# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

runtime: go
env: flex

automatic_scaling:
  min_num_instances: 1

env_variables:
  GCLOUD_STORAGE_BUCKET: your-bucket-name

애플리케이션 코드

샘플 애플리케이션은 웹페이지를 통해 사용자에게 Cloud Storage에 저장할 파일을 제공하라는 메시지를 표시합니다. 사용자가 파일을 선택하고 제출을 클릭하면 업로드 핸들러가 Cloud Storage NewWriter 함수를 사용하여 파일을 Cloud Storage 버킷에 씁니다.

Cloud Storage에서 이 파일을 검색하려면 버킷 이름과 파일 이름을 지정해야 합니다. 나중에 사용할 수 있도록 이 값을 앱에 저장해야 합니다.

// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// Sample storage demonstrates use of the cloud.google.com/go/storage package from App Engine flexible environment.
package main

import (
	"context"
	"fmt"
	"io"
	"log"
	"net/http"
	"net/url"
	"os"

	"cloud.google.com/go/storage"
	"google.golang.org/appengine"
)

var (
	storageClient *storage.Client

	// Set this in app.yaml when running in production.
	bucket = os.Getenv("GCLOUD_STORAGE_BUCKET")
)

func main() {
	ctx := context.Background()

	var err error
	storageClient, err = storage.NewClient(ctx)
	if err != nil {
		log.Fatal(err)
	}

	http.HandleFunc("/", formHandler)
	http.HandleFunc("/upload", uploadHandler)

	appengine.Main()
}

func uploadHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method != "POST" {
		http.Error(w, "", http.StatusMethodNotAllowed)
		return
	}

	ctx := appengine.NewContext(r)

	f, fh, err := r.FormFile("file")
	if err != nil {
		msg := fmt.Sprintf("Could not get file: %v", err)
		http.Error(w, msg, http.StatusBadRequest)
		return
	}
	defer f.Close()

	sw := storageClient.Bucket(bucket).Object(fh.Filename).NewWriter(ctx)
	if _, err := io.Copy(sw, f); err != nil {
		msg := fmt.Sprintf("Could not write file: %v", err)
		http.Error(w, msg, http.StatusInternalServerError)
		return
	}

	if err := sw.Close(); err != nil {
		msg := fmt.Sprintf("Could not put file: %v", err)
		http.Error(w, msg, http.StatusInternalServerError)
		return
	}

	u, _ := url.Parse("/" + bucket + "/" + sw.Attrs().Name)

	fmt.Fprintf(w, "Successful! URL: https://storage.googleapis.com%s", u.EscapedPath())
}

func formHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, formHTML)
}

const formHTML = `<!DOCTYPE html>
<html>
  <head>
    <title>Storage</title>
    <meta charset="utf-8">
  </head>
  <body>
    <form method="POST" action="/upload" enctype="multipart/form-data">
      <input type="file" name="file">
      <input type="submit">
    </form>
  </body>
</html>`

추가 정보

Cloud Storage에 대한 자세한 내용은 Cloud Storage 문서를 참조하세요.