使用 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 -u -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 說明文件