Como usar o Cloud Storage

Use o Cloud Storage para armazenar e disponibilizar arquivos como filmes, imagens ou outros conteúdos estáticos.

Neste documento, descrevemos como usar a biblioteca de cliente do Google Cloud no seu aplicativo para armazenar e recuperar dados do Cloud Storage.

Antes de começar

  • Siga as instruções sobre o "Hello, World!" para Go para configurar o ambiente e o projeto, além de compreender a estrutura de aplicativos do Go no App Engine. Anote e salve o código do projeto. Você precisará dele para executar o aplicativo de amostra descrito neste documento.

  • Certifique-se de criar um bucket do Cloud Storage para o aplicativo invocando o seguinte comando:

    gsutil mb gs://[YOUR_BUCKET_NAME]
    
  • Configure o bucket como acessível para leitura pública para disponibilização de arquivos:

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

Fazer o download da amostra

Para clonar o repositório:

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

Edite a configuração do projeto e instale as dependências

Em app.yaml, defina GCLOUD_STORAGE_BUCKET. Esse valor é o nome do bucket do Cloud Storage criado anteriormente.

# 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

Código do aplicativo

O aplicativo de amostra apresenta uma página da Web que solicita ao usuário um arquivo para armazenar no Cloud Storage. Quando o usuário seleciona um arquivo e clica em enviar, o gerenciador de uploads grava o arquivo no bucket do Cloud Storage usando a função NewWriter do Cloud Storage.

Para recuperar esse arquivo do Cloud Storage, especifique o nome do bucket e o nome do arquivo. Armazene esses valores no app para uso futuro.

// 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>`

Para saber mais

Consulte a documentação do Cloud Storage para informações completas.