Usa Cloud Storage

Puedes usar Cloud Storage para almacenar y entregar archivos tal como películas, imágenes y otros contenidos estáticos.

En este documento se describe cómo utilizar la biblioteca cliente de Google Cloud en tu app para almacenar y recuperar datos de Cloud Storage.

Antes de comenzar

  • Sigue las instrucciones en “Hello, World!” para Go en App Engine a fin de configurar tu entorno y proyecto, y entender cómo se estructuran las aplicaciones de Go en App Engine. Escribe y guarda el ID del proyecto, ya que lo necesitarás para ejecutar la aplicación de muestra que se describe en este documento.

  • Asegúrate de crear un bucket de Cloud Storage para tu aplicación con este comando:

    gsutil mb gs://[YOUR_BUCKET_NAME]
    
  • Haz que el bucket pueda leerse públicamente para que pueda entregar archivos:

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

Descarga la muestra

Para clonar el repositorio:

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

Instala dependencias y edita la configuración del proyecto

En app.yaml, establece GCLOUD_STORAGE_BUCKET; este valor es el nombre del bucket de Cloud Storage que creaste antes.

# 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 de la aplicación

La aplicación de muestra presenta una página web en la que se solicita al usuario que proporcione un archivo para almacenarlo en Cloud Storage. Cuando el usuario selecciona un archivo y hace clic en enviar, el controlador de cargas escribe el archivo en el depósito de Cloud Storage con Cloud Storage NewWriter

Ten en cuenta que, para recuperar este archivo de Cloud Storage, tendrás que especificar el nombre del bucket y el del archivo. Almacena estos valores en tu app para poder usarlos más adelante.

// 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 obtener más información

Para obtener más información sobre Cloud Storage, consulta la documentación de Cloud Storage.